diff --git a/changelogs/fragments/10942-mod-fstr-a.yml b/changelogs/fragments/10942-mod-fstr-a.yml new file mode 100644 index 0000000000..fcfdba3e42 --- /dev/null +++ b/changelogs/fragments/10942-mod-fstr-a.yml @@ -0,0 +1,22 @@ +minor_changes: + - hwc_utils module_utils plugin - adjust f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - manageiq module_utils plugin - adjust f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - aerospike_migrations - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - airbrake_deployment - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - aix_devices - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - aix_filesystem - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - aix_inittab - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - aix_lvg - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - aix_lvol - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - alerta_customer - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - ali_instance - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - alternatives - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - android_sdk - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - ansible_galaxy_install - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - apache2_mod_proxy - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - apache2_module - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - apk - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - apt_repo - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - apt_rpm - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - archive - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). + - awall - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942). diff --git a/plugins/module_utils/hwc_utils.py b/plugins/module_utils/hwc_utils.py index dee53cd787..596303527c 100644 --- a/plugins/module_utils/hwc_utils.py +++ b/plugins/module_utils/hwc_utils.py @@ -41,7 +41,7 @@ class HwcClientException(Exception): self._message = message def __str__(self): - msg = f" code={self._code!s}," if self._code != 0 else "" + msg = f" code={self._code}," if self._code != 0 else "" return f"[HwcClientException]{msg} message={self._message}" diff --git a/plugins/module_utils/manageiq.py b/plugins/module_utils/manageiq.py index 477fc9a326..4b89fd78cc 100644 --- a/plugins/module_utils/manageiq.py +++ b/plugins/module_utils/manageiq.py @@ -151,7 +151,7 @@ class ManageIQ(object): if resource: return resource else: - msg = f"{collection_name} where {params!s} does not exist in manageiq" + msg = f"{collection_name} where {params} does not exist in manageiq" self.module.fail_json(msg=msg) def policies(self, resource_id, resource_type, resource_name): diff --git a/plugins/modules/aerospike_migrations.py b/plugins/modules/aerospike_migrations.py index 02b8bd7730..5258f89c78 100644 --- a/plugins/modules/aerospike_migrations.py +++ b/plugins/modules/aerospike_migrations.py @@ -217,7 +217,7 @@ def run_module(): if has_migrations: module.fail_json(msg="Failed.", skip_reason=skip_reason) except Exception as e: - module.fail_json(msg="Error: {0}".format(e)) + module.fail_json(msg=f"Error: {e}") module.exit_json(**result) @@ -263,8 +263,7 @@ class Migrations: data = data.split("\t") if len(data) != 1 and len(data) != 2: self.module.fail_json( - msg="Unexpected number of values returned in info command: " + - str(len(data)) + msg=f"Unexpected number of values returned in info command: {len(data)}" ) # data will be in format 'command\touput' data = data[-1] @@ -329,7 +328,7 @@ class Migrations: """returns a True or False. Does the namespace have migrations for the node passed? If no node passed, uses the local node or the first one in the list""" - namespace_stats = self._info_cmd_helper("namespace/" + namespace, node) + namespace_stats = self._info_cmd_helper(f"namespace/{namespace}", node) try: namespace_tx = \ int(namespace_stats[self.module.params['migrate_tx_key']]) @@ -337,13 +336,10 @@ class Migrations: int(namespace_stats[self.module.params['migrate_rx_key']]) except KeyError: self.module.fail_json( - msg="Did not find partition remaining key:" + - self.module.params['migrate_tx_key'] + - " or key:" + - self.module.params['migrate_rx_key'] + - " in 'namespace/" + - namespace + - "' output." + msg=( + f"Did not find partition remaining key:{self.module.params['migrate_tx_key']} " + f"or key:{self.module.params['migrate_rx_key']} in 'namespace/{namespace}' output." + ) ) except TypeError: self.module.fail_json( @@ -433,7 +429,7 @@ class Migrations: cmd = "cluster-stable:" target_cluster_size = self.module.params['target_cluster_size'] if target_cluster_size is not None: - cmd = cmd + "size=" + str(target_cluster_size) + ";" + cmd = f"{cmd}size={target_cluster_size};" for node in self._nodes: try: cluster_key.add(self._info_cmd_helper(cmd, node)) @@ -475,8 +471,7 @@ class Migrations: stable, reason = self._cluster_good_state() if stable is not True: skip_reason.append( - "Skipping on try#" + str(try_num) + - " for reason:" + reason + f"Skipping on try#{try_num} for reason:{reason}" ) else: if self._can_use_cluster_stable(): @@ -485,14 +480,12 @@ class Migrations: else: consecutive_good = 0 skip_reason.append( - "Skipping on try#" + str(try_num) + - " for reason:" + " cluster_stable" + f"Skipping on try#{try_num} for reason: cluster_stable" ) elif self._has_migs(local): # print("_has_migs") skip_reason.append( - "Skipping on try#" + str(try_num) + - " for reason:" + " migrations" + f"Skipping on try#{try_num} for reason: migrations" ) consecutive_good = 0 else: diff --git a/plugins/modules/airbrake_deployment.py b/plugins/modules/airbrake_deployment.py index d55c04fa52..745d3fce5d 100644 --- a/plugins/modules/airbrake_deployment.py +++ b/plugins/modules/airbrake_deployment.py @@ -146,7 +146,7 @@ def main(): params["version"] = module.params["version"] # Build deploy url - url = module.params.get('url') + module.params["project_id"] + '/deploys?key=' + module.params["project_key"] + url = f"{module.params.get('url')}{module.params['project_id']}/deploys?key={module.params['project_key']}" json_body = module.jsonify(params) # Build header @@ -159,7 +159,7 @@ def main(): if info['status'] == 200 or info['status'] == 201: module.exit_json(changed=True) else: - module.fail_json(msg="HTTP result code: %d connecting to %s" % (info['status'], url)) + module.fail_json(msg=f"HTTP result code: {info['status']} connecting to {url}") if __name__ == '__main__': diff --git a/plugins/modules/aix_devices.py b/plugins/modules/aix_devices.py index a525f6fe05..8176b740bb 100644 --- a/plugins/modules/aix_devices.py +++ b/plugins/modules/aix_devices.py @@ -141,7 +141,7 @@ def _check_device(module, device): """ lsdev_cmd = module.get_bin_path('lsdev', True) - rc, lsdev_out, err = module.run_command(["%s" % lsdev_cmd, '-C', '-l', "%s" % device]) + rc, lsdev_out, err = module.run_command([lsdev_cmd, '-C', '-l', device]) if rc != 0: module.fail_json(msg="Failed to run lsdev", rc=rc, err=err) @@ -166,7 +166,7 @@ def _check_device_attr(module, device, attr): """ lsattr_cmd = module.get_bin_path('lsattr', True) - rc, lsattr_out, err = module.run_command(["%s" % lsattr_cmd, '-El', "%s" % device, '-a', "%s" % attr]) + rc, lsattr_out, err = module.run_command([lsattr_cmd, '-El', device, '-a', f"{attr}"]) hidden_attrs = ['delalias4', 'delalias6'] @@ -180,7 +180,7 @@ def _check_device_attr(module, device, attr): return current_param elif rc != 0: - module.fail_json(msg="Failed to run lsattr: %s" % err, rc=rc, err=err) + module.fail_json(msg=f"Failed to run lsattr: {err}", rc=rc, err=err) current_param = lsattr_out.split()[1] return current_param @@ -191,7 +191,7 @@ def discover_device(module, device): cfgmgr_cmd = module.get_bin_path('cfgmgr', True) if device is not None: - device = "-l %s" % device + device = f"-l {device}" else: device = '' @@ -199,7 +199,7 @@ def discover_device(module, device): changed = True msg = '' if not module.check_mode: - rc, cfgmgr_out, err = module.run_command(["%s" % cfgmgr_cmd, "%s" % device]) + rc, cfgmgr_out, err = module.run_command([cfgmgr_cmd, device]) changed = True msg = cfgmgr_out @@ -223,9 +223,9 @@ def change_device_attr(module, attributes, device, force): elif current_param != new_param: if force: - cmd = ["%s" % chdev_cmd, '-l', "%s" % device, '-a', "%s=%s" % (attr, attributes[attr]), "%s" % force] + cmd = [chdev_cmd, '-l', device, '-a', f"{attr}={attributes[attr]}", f"{force}"] else: - cmd = ["%s" % chdev_cmd, '-l', "%s" % device, '-a', "%s=%s" % (attr, attributes[attr])] + cmd = [chdev_cmd, '-l', device, '-a', f"{attr}={attributes[attr]}"] if not module.check_mode: rc, chdev_out, err = module.run_command(cmd) @@ -238,22 +238,22 @@ def change_device_attr(module, attributes, device, force): if len(attr_changed) > 0: changed = True - attr_changed_msg = "Attributes changed: %s. " % ','.join(attr_changed) + attr_changed_msg = f"Attributes changed: {','.join(attr_changed)}. " else: changed = False attr_changed_msg = '' if len(attr_not_changed) > 0: - attr_not_changed_msg = "Attributes already set: %s. " % ','.join(attr_not_changed) + attr_not_changed_msg = f"Attributes already set: {','.join(attr_not_changed)}. " else: attr_not_changed_msg = '' if len(attr_invalid) > 0: - attr_invalid_msg = "Invalid attributes: %s " % ', '.join(attr_invalid) + attr_invalid_msg = f"Invalid attributes: {', '.join(attr_invalid)} " else: attr_invalid_msg = '' - msg = "%s%s%s" % (attr_changed_msg, attr_not_changed_msg, attr_invalid_msg) + msg = f"{attr_changed_msg}{attr_not_changed_msg}{attr_invalid_msg}" return changed, msg @@ -281,9 +281,9 @@ def remove_device(module, device, force, recursive, state): if not module.check_mode: if state: - rc, rmdev_out, err = module.run_command(["%s" % rmdev_cmd, "-l", "%s" % device, "%s" % recursive, "%s" % force]) + rc, rmdev_out, err = module.run_command([rmdev_cmd, "-l", device, f"{recursive}", f"{force}"]) else: - rc, rmdev_out, err = module.run_command(["%s" % rmdev_cmd, "-l", "%s" % device, "%s" % recursive]) + rc, rmdev_out, err = module.run_command([rmdev_cmd, "-l", device, f"{recursive}"]) if rc != 0: module.fail_json(msg="Failed to run rmdev", rc=rc, err=err) @@ -329,7 +329,7 @@ def main(): if device_status: result['changed'], result['msg'] = change_device_attr(module, attributes, device, force) else: - result['msg'] = "Device %s does not exist." % device + result['msg'] = f"Device {device} does not exist." else: # discovery devices (cfgmgr) @@ -340,7 +340,7 @@ def main(): result['changed'], result['msg'] = discover_device(module, device) else: - result['msg'] = "Device %s does not exist." % device + result['msg'] = f"Device {device} does not exist." else: result['changed'], result['msg'] = discover_device(module, device) @@ -355,16 +355,16 @@ def main(): if check_device: if state == 'defined' and device_state == 'Defined': result['changed'] = False - result['msg'] = 'Device %s already in Defined' % device + result['msg'] = f'Device {device} already in Defined' else: result['changed'], result['msg'] = remove_device(module, device, force, recursive, state) else: - result['msg'] = "Device %s does not exist." % device + result['msg'] = f"Device {device} does not exist." else: - result['msg'] = "Unexpected state %s." % state + result['msg'] = f"Unexpected state {state}." module.fail_json(**result) module.exit_json(**result) diff --git a/plugins/modules/aix_filesystem.py b/plugins/modules/aix_filesystem.py index 58d49c0252..3b90848fe6 100644 --- a/plugins/modules/aix_filesystem.py +++ b/plugins/modules/aix_filesystem.py @@ -184,7 +184,7 @@ def _fs_exists(module, filesystem): return False else: - module.fail_json(msg="Failed to run lsfs. Error message: %s" % err) + module.fail_json(msg=f"Failed to run lsfs. Error message: {err}") else: @@ -203,7 +203,7 @@ def _check_nfs_device(module, nfs_host, device): showmount_cmd = module.get_bin_path('showmount', True) rc, showmount_out, err = module.run_command([showmount_cmd, "-a", nfs_host]) if rc != 0: - module.fail_json(msg="Failed to run showmount. Error message: %s" % err) + module.fail_json(msg=f"Failed to run showmount. Error message: {err}") else: showmount_data = showmount_out.splitlines() for line in showmount_data: @@ -225,20 +225,20 @@ def _validate_vg(module, vg): lsvg_cmd = module.get_bin_path('lsvg', True) rc, current_active_vgs, err = module.run_command([lsvg_cmd, "-o"]) if rc != 0: - module.fail_json(msg="Failed executing %s command." % lsvg_cmd) + module.fail_json(msg=f"Failed executing {lsvg_cmd} command.") rc, current_all_vgs, err = module.run_command([lsvg_cmd]) if rc != 0: - module.fail_json(msg="Failed executing %s command." % lsvg_cmd) + module.fail_json(msg=f"Failed executing {lsvg_cmd} command.") if vg in current_all_vgs and vg not in current_active_vgs: - msg = "Volume group %s is in varyoff state." % vg + msg = f"Volume group {vg} is in varyoff state." return False, msg elif vg in current_active_vgs: - msg = "Volume group %s is in varyon state." % vg + msg = f"Volume group {vg} is in varyon state." return True, msg else: - msg = "Volume group %s does not exist." % vg + msg = f"Volume group {vg} does not exist." return None, msg @@ -247,7 +247,7 @@ def resize_fs(module, filesystem, size): chfs_cmd = module.get_bin_path('chfs', True) if not module.check_mode: - rc, chfs_out, err = module.run_command([chfs_cmd, "-a", "size=%s" % size, filesystem]) + rc, chfs_out, err = module.run_command([chfs_cmd, "-a", f"size={size}", filesystem]) if rc == 28: changed = False @@ -257,7 +257,7 @@ def resize_fs(module, filesystem, size): changed = False return changed, err else: - module.fail_json(msg="Failed to run chfs. Error message: %s" % err) + module.fail_json(msg=f"Failed to run chfs. Error message: {err}") else: if re.findall('The filesystem size is already', chfs_out): @@ -301,19 +301,19 @@ def create_fs( if size is None: size = '' else: - size = "-a size=%s" % size + size = f"-a size={size}" if device is None: device = '' else: - device = "-d %s" % device + device = f"-d {device}" if vg is None: vg = '' else: vg_state, msg = _validate_vg(module, vg) if vg_state: - vg = "-g %s" % vg + vg = f"-g {vg}" else: changed = False @@ -323,7 +323,7 @@ def create_fs( mount_group = '' else: - mount_group = "-u %s" % mount_group + mount_group = f"-u {mount_group}" auto_mount = auto_mount_opt[auto_mount] account_subsystem = account_subsys_opt[account_subsystem] @@ -334,10 +334,10 @@ def create_fs( if not module.check_mode: rc, mknfsmnt_out, err = module.run_command([mknfsmnt_cmd, "-f", filesystem, device, "-h", nfs_server, "-t", permissions, auto_mount, "-w", "bg"]) if rc != 0: - module.fail_json(msg="Failed to run mknfsmnt. Error message: %s" % err) + module.fail_json(msg=f"Failed to run mknfsmnt. Error message: {err}") else: changed = True - msg = "NFS file system %s created." % filesystem + msg = f"NFS file system {filesystem} created." return changed, msg else: @@ -401,11 +401,10 @@ def create_fs( if rc == 10: module.exit_json( - msg="Using a existent previously defined logical volume, " - "volume group needs to be empty. %s" % err) + msg=f"Using a existent previously defined logical volume, volume group needs to be empty. {err}") elif rc != 0: - module.fail_json(msg="Failed to run %s. Error message: %s" % (cmd, err)) + module.fail_json(msg=f"Failed to run {cmd}. Error message: {err}") else: changed = True @@ -433,12 +432,12 @@ def remove_fs(module, filesystem, rm_mount_point): cmd = [rmfs_cmd, "-r", rm_mount_point, filesystem] rc, rmfs_out, err = module.run_command(cmd) if rc != 0: - module.fail_json(msg="Failed to run %s. Error message: %s" % (cmd, err)) + module.fail_json(msg=f"Failed to run {cmd}. Error message: {err}") else: changed = True msg = rmfs_out if not rmfs_out: - msg = "File system %s removed." % filesystem + msg = f"File system {filesystem} removed." return changed, msg else: @@ -455,10 +454,10 @@ def mount_fs(module, filesystem): if not module.check_mode: rc, mount_out, err = module.run_command([mount_cmd, filesystem]) if rc != 0: - module.fail_json(msg="Failed to run mount. Error message: %s" % err) + module.fail_json(msg=f"Failed to run mount. Error message: {err}") else: changed = True - msg = "File system %s mounted." % filesystem + msg = f"File system {filesystem} mounted." return changed, msg else: @@ -475,10 +474,10 @@ def unmount_fs(module, filesystem): if not module.check_mode: rc, unmount_out, err = module.run_command([unmount_cmd, filesystem]) if rc != 0: - module.fail_json(msg="Failed to run unmount. Error message: %s" % err) + module.fail_json(msg=f"Failed to run unmount. Error message: {err}") else: changed = True - msg = "File system %s unmounted." % filesystem + msg = f"File system {filesystem} unmounted." return changed, msg else: @@ -533,7 +532,7 @@ def main(): # Check if fs is mounted or exists. if fs_mounted or fs_exists: - result['msg'] = "File system %s already exists." % filesystem + result['msg'] = f"File system {filesystem} already exists." result['changed'] = False # If parameter size was passed, resize fs. @@ -569,32 +568,32 @@ def main(): elif state == 'absent': if ismount(filesystem): - result['msg'] = "File system %s mounted." % filesystem + result['msg'] = f"File system {filesystem} mounted." else: fs_status = _fs_exists(module, filesystem) if not fs_status: - result['msg'] = "File system %s does not exist." % filesystem + result['msg'] = f"File system {filesystem} does not exist." else: result['changed'], result['msg'] = remove_fs(module, filesystem, rm_mount_point) elif state == 'mounted': if ismount(filesystem): result['changed'] = False - result['msg'] = "File system %s already mounted." % filesystem + result['msg'] = f"File system {filesystem} already mounted." else: result['changed'], result['msg'] = mount_fs(module, filesystem) elif state == 'unmounted': if not ismount(filesystem): result['changed'] = False - result['msg'] = "File system %s already unmounted." % filesystem + result['msg'] = f"File system {filesystem} already unmounted." else: result['changed'], result['msg'] = unmount_fs(module, filesystem) else: # Unreachable codeblock - result['msg'] = "Unexpected state %s." % state + result['msg'] = f"Unexpected state {state}." module.fail_json(**result) module.exit_json(**result) diff --git a/plugins/modules/aix_inittab.py b/plugins/modules/aix_inittab.py index 407992ceba..f20f2e903d 100644 --- a/plugins/modules/aix_inittab.py +++ b/plugins/modules/aix_inittab.py @@ -182,8 +182,7 @@ def main(): if module.params['state'] == 'present': # create new entry string - new_entry = module.params['name'] + ":" + module.params['runlevel'] + \ - ":" + module.params['action'] + ":" + module.params['command'] + new_entry = f"{module.params['name']}:{module.params['runlevel']}:{module.params['action']}:{module.params['command']}" # If current entry exists or fields are different(if the entry does not # exists, then the entry will be created @@ -199,7 +198,7 @@ def main(): if rc != 0: module.fail_json( msg="could not change inittab", rc=rc, err=err) - result['msg'] = "changed inittab entry" + " " + current_entry['name'] + result['msg'] = f"changed inittab entry {current_entry['name']}" result['changed'] = True # If the entry does not exist create the entry @@ -215,7 +214,7 @@ def main(): if rc != 0: module.fail_json(msg="could not adjust inittab", rc=rc, err=err) - result['msg'] = "add inittab entry" + " " + module.params['name'] + result['msg'] = f"add inittab entry {module.params['name']}" result['changed'] = True elif module.params['state'] == 'absent': @@ -227,7 +226,7 @@ def main(): if rc != 0: module.fail_json( msg="could not remove entry from inittab)", rc=rc, err=err) - result['msg'] = "removed inittab entry" + " " + current_entry['name'] + result['msg'] = f"removed inittab entry {current_entry['name']}" result['changed'] = True module.exit_json(**result) diff --git a/plugins/modules/aix_lvg.py b/plugins/modules/aix_lvg.py index 7afc58e2f7..aa1a947e2f 100644 --- a/plugins/modules/aix_lvg.py +++ b/plugins/modules/aix_lvg.py @@ -115,27 +115,27 @@ def _validate_pv(module, vg, pvs): # Check if pv exists and is free. if pv not in lspv_list.keys(): - module.fail_json(msg="Physical volume '%s' doesn't exist." % pv) + module.fail_json(msg=f"Physical volume '{pv}' doesn't exist.") if lspv_list[pv] == 'None': # Disk None, looks free. # Check if PV is not already in use by Oracle ASM. lquerypv_cmd = module.get_bin_path('lquerypv', True) - rc, current_lquerypv, stderr = module.run_command([lquerypv_cmd, "-h", "/dev/%s" % pv, "20", "10"]) + rc, current_lquerypv, stderr = module.run_command([lquerypv_cmd, "-h", f"/dev/{pv}", "20", "10"]) if rc != 0: module.fail_json(msg="Failed executing lquerypv command.", rc=rc, stdout=current_lquerypv, stderr=stderr) if 'ORCLDISK' in current_lquerypv: - module.fail_json("Physical volume '%s' is already used by Oracle ASM." % pv) + module.fail_json(f"Physical volume '{pv}' is already used by Oracle ASM.") - msg = "Physical volume '%s' is ok to be used." % pv + msg = f"Physical volume '{pv}' is ok to be used." return True, msg # Check if PV is already in use for the same vg. elif vg != lspv_list[pv]: - module.fail_json(msg="Physical volume '%s' is in use by another volume group '%s'." % (pv, lspv_list[pv])) + module.fail_json(msg=f"Physical volume '{pv}' is in use by another volume group '{lspv_list[pv]}'.") - msg = "Physical volume '%s' is already used by volume group '%s'." % (pv, lspv_list[pv]) + msg = f"Physical volume '{pv}' is already used by volume group '{lspv_list[pv]}'." return False, msg @@ -151,21 +151,21 @@ def _validate_vg(module, vg): lsvg_cmd = module.get_bin_path('lsvg', True) rc, current_active_vgs, err = module.run_command([lsvg_cmd, "-o"]) if rc != 0: - module.fail_json(msg="Failed executing '%s' command." % lsvg_cmd) + module.fail_json(msg=f"Failed executing '{lsvg_cmd}' command.") rc, current_all_vgs, err = module.run_command([lsvg_cmd]) if rc != 0: - module.fail_json(msg="Failed executing '%s' command." % lsvg_cmd) + module.fail_json(msg=f"Failed executing '{lsvg_cmd}' command.") if vg in current_all_vgs and vg not in current_active_vgs: - msg = "Volume group '%s' is in varyoff state." % vg + msg = f"Volume group '{vg}' is in varyoff state." return False, msg if vg in current_active_vgs: - msg = "Volume group '%s' is in varyon state." % vg + msg = f"Volume group '{vg}' is in varyon state." return True, msg - msg = "Volume group '%s' does not exist." % vg + msg = f"Volume group '{vg}' does not exist." return None, msg @@ -205,10 +205,10 @@ def create_extend_vg(module, vg, pvs, pp_size, vg_type, force, vg_validation): rc, output, err = module.run_command([extendvg_cmd, vg] + pvs) if rc != 0: changed = False - msg = "Extending volume group '%s' has failed." % vg + msg = f"Extending volume group '{vg}' has failed." return changed, msg - msg = "Volume group '%s' extended." % vg + msg = f"Volume group '{vg}' extended." return changed, msg elif vg_state is None: @@ -221,10 +221,10 @@ def create_extend_vg(module, vg, pvs, pp_size, vg_type, force, vg_validation): rc, output, err = module.run_command([mkvg_cmd, vg_opt[vg_type], pp_size, force_opt[force], "-y", vg] + pvs) if rc != 0: changed = False - msg = "Creating volume group '%s' failed." % vg + msg = f"Creating volume group '{vg}' failed." return changed, msg - msg = "Volume group '%s' created." % vg + msg = f"Volume group '{vg}' created." return changed, msg @@ -246,16 +246,16 @@ def reduce_vg(module, vg, pvs, vg_validation): lsvg_cmd = module.get_bin_path('lsvg', True) rc, current_pvs, err = module.run_command([lsvg_cmd, "-p", vg]) if rc != 0: - module.fail_json(msg="Failing to execute '%s' command." % lsvg_cmd) + module.fail_json(msg=f"Failing to execute '{lsvg_cmd}' command.") pvs_to_remove = [] for line in current_pvs.splitlines()[2:]: pvs_to_remove.append(line.split()[0]) - reduce_msg = "Volume group '%s' removed." % vg + reduce_msg = f"Volume group '{vg}' removed." else: pvs_to_remove = pvs - reduce_msg = ("Physical volume(s) '%s' removed from Volume group '%s'." % (' '.join(pvs_to_remove), vg)) + reduce_msg = f"Physical volume(s) '{' '.join(pvs_to_remove)}' removed from Volume group '{vg}'." # Reduce volume group. if len(pvs_to_remove) <= 0: @@ -270,7 +270,7 @@ def reduce_vg(module, vg, pvs, vg_validation): reducevg_cmd = module.get_bin_path('reducevg', True) rc, stdout, stderr = module.run_command([reducevg_cmd, "-df", vg] + pvs_to_remove) if rc != 0: - module.fail_json(msg="Unable to remove '%s'." % vg, rc=rc, stdout=stdout, stderr=stderr) + module.fail_json(msg=f"Unable to remove '{vg}'.", rc=rc, stdout=stdout, stderr=stderr) msg = reduce_msg return changed, msg @@ -295,7 +295,7 @@ def state_vg(module, vg, state, vg_validation): if rc != 0: module.fail_json(msg="Command 'varyonvg' failed.", rc=rc, err=err) - msg = "Varyon volume group %s completed." % vg + msg = f"Varyon volume group {vg} completed." return changed, msg elif state == 'varyoff': @@ -312,7 +312,7 @@ def state_vg(module, vg, state, vg_validation): if rc != 0: module.fail_json(msg="Command 'varyoffvg' failed.", rc=rc, stdout=varyonvg_out, stderr=stderr) - msg = "Varyoff volume group %s completed." % vg + msg = f"Varyoff volume group {vg} completed." return changed, msg @@ -339,7 +339,7 @@ def main(): if pp_size is None: pp_size = '' else: - pp_size = "-s %s" % pp_size + pp_size = f"-s {pp_size}" vg_validation = _validate_vg(module, vg) diff --git a/plugins/modules/aix_lvol.py b/plugins/modules/aix_lvol.py index 53679fb48d..5f02a91f63 100644 --- a/plugins/modules/aix_lvol.py +++ b/plugins/modules/aix_lvol.py @@ -257,9 +257,9 @@ def main(): if rc != 0: if state == 'absent': - module.exit_json(changed=False, msg="Volume group %s does not exist." % vg) + module.exit_json(changed=False, msg=f"Volume group {vg} does not exist.") else: - module.fail_json(msg="Volume group %s does not exist." % vg, rc=rc, out=vg_info, err=err) + module.fail_json(msg=f"Volume group {vg} does not exist.", rc=rc, out=vg_info, err=err) this_vg = parse_vg(vg_info) @@ -272,7 +272,7 @@ def main(): if rc != 0: if state == 'absent': - module.exit_json(changed=False, msg="Logical Volume %s does not exist." % lv) + module.exit_json(changed=False, msg=f"Logical Volume {lv} does not exist.") changed = False @@ -285,56 +285,56 @@ def main(): if this_lv is None: if state == 'present': if lv_size > this_vg['free']: - module.fail_json(msg="Not enough free space in volume group %s: %s MB free." % (this_vg['name'], this_vg['free'])) + module.fail_json(msg=f"Not enough free space in volume group {this_vg['name']}: {this_vg['free']} MB free.") # create LV mklv_cmd = module.get_bin_path("mklv", required=True) - cmd = test_opt + [mklv_cmd, "-t", lv_type, "-y", lv, "-c", copies, "-e", lv_policy, opts, vg, "%sM" % (lv_size, )] + pvs + cmd = test_opt + [mklv_cmd, "-t", lv_type, "-y", lv, "-c", copies, "-e", lv_policy, opts, vg, f"{lv_size}M"] + pvs rc, out, err = module.run_command(cmd) if rc == 0: - module.exit_json(changed=True, msg="Logical volume %s created." % lv) + module.exit_json(changed=True, msg=f"Logical volume {lv} created.") else: - module.fail_json(msg="Creating logical volume %s failed." % lv, rc=rc, out=out, err=err) + module.fail_json(msg=f"Creating logical volume {lv} failed.", rc=rc, out=out, err=err) else: if state == 'absent': # remove LV rmlv_cmd = module.get_bin_path("rmlv", required=True) rc, out, err = module.run_command(test_opt + [rmlv_cmd, "-f", this_lv['name']]) if rc == 0: - module.exit_json(changed=True, msg="Logical volume %s deleted." % lv) + module.exit_json(changed=True, msg=f"Logical volume {lv} deleted.") else: - module.fail_json(msg="Failed to remove logical volume %s." % lv, rc=rc, out=out, err=err) + module.fail_json(msg=f"Failed to remove logical volume {lv}.", rc=rc, out=out, err=err) else: if this_lv['policy'] != policy: # change lv allocation policy chlv_cmd = module.get_bin_path("chlv", required=True) rc, out, err = module.run_command(test_opt + [chlv_cmd, "-e", lv_policy, this_lv['name']]) if rc == 0: - module.exit_json(changed=True, msg="Logical volume %s policy changed: %s." % (lv, policy)) + module.exit_json(changed=True, msg=f"Logical volume {lv} policy changed: {policy}.") else: - module.fail_json(msg="Failed to change logical volume %s policy." % lv, rc=rc, out=out, err=err) + module.fail_json(msg=f"Failed to change logical volume {lv} policy.", rc=rc, out=out, err=err) if vg != this_lv['vg']: - module.fail_json(msg="Logical volume %s already exist in volume group %s" % (lv, this_lv['vg'])) + module.fail_json(msg=f"Logical volume {lv} already exist in volume group {this_lv['vg']}") # from here the last remaining action is to resize it, if no size parameter is passed we do nothing. if not size: - module.exit_json(changed=False, msg="Logical volume %s already exist." % (lv)) + module.exit_json(changed=False, msg=f"Logical volume {lv} already exist.") # resize LV based on absolute values if int(lv_size) > this_lv['size']: extendlv_cmd = module.get_bin_path("extendlv", required=True) - cmd = test_opt + [extendlv_cmd, lv, "%sM" % (lv_size - this_lv['size'], )] + cmd = test_opt + [extendlv_cmd, lv, f"{lv_size - this_lv['size']}M"] rc, out, err = module.run_command(cmd) if rc == 0: - module.exit_json(changed=True, msg="Logical volume %s size extended to %sMB." % (lv, lv_size)) + module.exit_json(changed=True, msg=f"Logical volume {lv} size extended to {lv_size}MB.") else: - module.fail_json(msg="Unable to resize %s to %sMB." % (lv, lv_size), rc=rc, out=out, err=err) + module.fail_json(msg=f"Unable to resize {lv} to {lv_size}MB.", rc=rc, out=out, err=err) elif lv_size < this_lv['size']: - module.fail_json(msg="No shrinking of Logical Volume %s permitted. Current size: %s MB" % (lv, this_lv['size'])) + module.fail_json(msg=f"No shrinking of Logical Volume {lv} permitted. Current size: {this_lv['size']} MB") else: - module.exit_json(changed=False, msg="Logical volume %s size is already %sMB." % (lv, lv_size)) + module.exit_json(changed=False, msg=f"Logical volume {lv} size is already {lv_size}MB.") if __name__ == '__main__': diff --git a/plugins/modules/alerta_customer.py b/plugins/modules/alerta_customer.py index aec3923206..0fd997a1ae 100644 --- a/plugins/modules/alerta_customer.py +++ b/plugins/modules/alerta_customer.py @@ -109,7 +109,7 @@ class AlertaInterface(object): self.headers = {"Content-Type": "application/json"} if module.params.get('api_key', None): - self.headers["Authorization"] = "Key %s" % module.params['api_key'] + self.headers["Authorization"] = f"Key {module.params['api_key']}" else: self.headers["Authorization"] = basic_auth_header(module.params['api_username'], module.params['api_password']) @@ -118,28 +118,28 @@ class AlertaInterface(object): status_code = info["status"] if status_code == 401: - self.module.fail_json(failed=True, response=info, msg="Unauthorized to request '%s' on '%s'" % (method, url)) + self.module.fail_json(failed=True, response=info, msg=f"Unauthorized to request '{method}' on '{url}'") elif status_code == 403: - self.module.fail_json(failed=True, response=info, msg="Permission Denied for '%s' on '%s'" % (method, url)) + self.module.fail_json(failed=True, response=info, msg=f"Permission Denied for '{method}' on '{url}'") elif status_code == 404: - self.module.fail_json(failed=True, response=info, msg="Not found for request '%s' on '%s'" % (method, url)) + self.module.fail_json(failed=True, response=info, msg=f"Not found for request '{method}' on '{url}'") elif status_code in (200, 201): return self.module.from_json(response.read()) - self.module.fail_json(failed=True, response=info, msg="Alerta API error with HTTP %d for %s" % (status_code, url)) + self.module.fail_json(failed=True, response=info, msg=f"Alerta API error with HTTP {status_code} for {url}") def get_customers(self): - url = "%s/api/customers" % self.alerta_url + url = f"{self.alerta_url}/api/customers" response = self.send_request(url) pages = response["pages"] if pages > 1: for page in range(2, pages + 1): - page_url = url + '?page=' + str(page) + page_url = f"{url}?page={page}" new_results = self.send_request(page_url) response.update(new_results) return response def create_customer(self): - url = "%s/api/customer" % self.alerta_url + url = f"{self.alerta_url}/api/customer" payload = { 'customer': self.customer, @@ -151,7 +151,7 @@ class AlertaInterface(object): return response def delete_customer(self, id): - url = "%s/api/customer/%s" % (self.alerta_url, id) + url = f"{self.alerta_url}/api/customer/{id}" response = self.send_request(url, None, 'DELETE') return response @@ -184,20 +184,20 @@ def main(): if alerta_iface.state == 'present': response = alerta_iface.get_customers() if alerta_iface.find_customer_id(response): - module.exit_json(changed=False, response=response, msg="Customer %s already exists" % alerta_iface.customer) + module.exit_json(changed=False, response=response, msg=f"Customer {alerta_iface.customer} already exists") else: if not module.check_mode: response = alerta_iface.create_customer() - module.exit_json(changed=True, response=response, msg="Customer %s created" % alerta_iface.customer) + module.exit_json(changed=True, response=response, msg=f"Customer {alerta_iface.customer} created") else: response = alerta_iface.get_customers() id = alerta_iface.find_customer_id(response) if id: if not module.check_mode: alerta_iface.delete_customer(id) - module.exit_json(changed=True, response=response, msg="Customer %s with id %s deleted" % (alerta_iface.customer, id)) + module.exit_json(changed=True, response=response, msg=f"Customer {alerta_iface.customer} with id {id} deleted") else: - module.exit_json(changed=False, response=response, msg="Customer %s does not exists" % alerta_iface.customer) + module.exit_json(changed=False, response=response, msg=f"Customer {alerta_iface.customer} does not exists") if __name__ == "__main__": diff --git a/plugins/modules/ali_instance.py b/plugins/modules/ali_instance.py index 0434f0d79f..37b2f067e0 100644 --- a/plugins/modules/ali_instance.py +++ b/plugins/modules/ali_instance.py @@ -674,7 +674,7 @@ def run_instance(module, ecs, exact_count): if len(security_groups) <= 0: module.fail_json(msg='Expected the parameter security_groups is non-empty when create new ECS instances, aborting') - client_token = "Ansible-Alicloud-{0}-{1}".format(hash(str(module.params)), str(time.time())) + client_token = f"Ansible-Alicloud-{hash(str(module.params))}-{time.time()}" try: # call to create_instance method from footmark @@ -691,7 +691,7 @@ def run_instance(module, ecs, exact_count): spot_price_limit=spot_price_limit, spot_strategy=spot_strategy, unique_suffix=unique_suffix) except Exception as e: - module.fail_json(msg='Unable to create instance, error: {0}'.format(e)) + module.fail_json(msg=f'Unable to create instance, error: {e}') return instances @@ -730,7 +730,7 @@ def modify_instance(module, instance): try: return instance.modify(name=name, description=description, host_name=host_name, password=password, user_data=user_data) except Exception as e: - module.fail_json(msg="Modify instance {0} attribute got an error: {1}".format(instance.id, e)) + module.fail_json(msg=f"Modify instance {instance.id} attribute got an error: {e}") def wait_for_instance_modify_charge(ecs, instance_ids, charge_type, delay=10, timeout=300): @@ -749,7 +749,7 @@ def wait_for_instance_modify_charge(ecs, instance_ids, charge_type, delay=10, ti timeout -= delay time.sleep(delay) if timeout <= 0: - raise Exception("Timeout Error: Waiting for instance to {0}. ".format(charge_type)) + raise Exception(f"Timeout Error: Waiting for instance to {charge_type}. ") except Exception as e: raise e @@ -824,8 +824,7 @@ def main(): module.fail_json(msg='The parameter instance_ids should be a list, aborting') instances = ecs.describe_instances(zone_id=zone_id, instance_ids=instance_ids) if not instances: - module.fail_json(msg="There are no instances in our record based on instance_ids {0}. " - "Please check it and try again.".format(instance_ids)) + module.fail_json(msg=f"There are no instances in our record based on instance_ids {instance_ids}. Please check it and try again.") elif count_tag: instances = ecs.describe_instances(zone_id=zone_id, tags=eval(count_tag)) elif instance_name: @@ -848,7 +847,7 @@ def main(): module.exit_json(changed=changed, ids=ids, instances=[]) except Exception as e: - module.fail_json(msg='Delete instance got an error: {0}'.format(e)) + module.fail_json(msg=f'Delete instance got an error: {e}') if module.params['allocate_public_ip'] and max_bandwidth_out < 0: module.fail_json(msg="'max_bandwidth_out' should be greater than 0 when 'allocate_public_ip' is True.") @@ -861,13 +860,13 @@ def main(): for i in range(0, len(instances) - count): inst = instances[len(instances) - 1] if inst.status != 'stopped' and not force: - module.fail_json(msg="That to delete instance {0} is failed results from it is running, " - "and please stop it or set 'force' as True.".format(inst.id)) + module.fail_json(msg=f"That to delete instance {inst.id} is failed results from it is running, " + "and please stop it or set 'force' as True.") try: if inst.terminate(force=force): changed = True except Exception as e: - module.fail_json(msg="Delete instance {0} got an error: {1}".format(inst.id, e)) + module.fail_json(msg=f"Delete instance {inst.id} got an error: {e}") instances.pop(len(instances) - 1) else: try: @@ -879,7 +878,7 @@ def main(): changed = True instances.extend(new_instances) except Exception as e: - module.fail_json(msg="Create new instances got an error: {0}".format(e)) + module.fail_json(msg=f"Create new instances got an error: {e}") # Security Group join/leave begin security_groups = module.params['security_groups'] @@ -951,7 +950,7 @@ def main(): changed = True ids.extend(targets) except Exception as e: - module.fail_json(msg='Start instances got an error: {0}'.format(e)) + module.fail_json(msg=f'Start instances got an error: {e}') elif state == 'stopped': try: targets = [] @@ -965,7 +964,7 @@ def main(): if modify_instance(module, inst): changed = True except Exception as e: - module.fail_json(msg='Stop instances got an error: {0}'.format(e)) + module.fail_json(msg=f'Stop instances got an error: {e}') elif state == 'restarted': try: targets = [] @@ -977,7 +976,7 @@ def main(): changed = True ids.extend(targets) except Exception as e: - module.fail_json(msg='Reboot instances got an error: {0}'.format(e)) + module.fail_json(msg=f'Reboot instances got an error: {e}') tags = module.params['tags'] if module.params['purge_tags']: @@ -988,7 +987,7 @@ def main(): if inst.remove_tags(tags): changed = True except Exception as e: - module.fail_json(msg="{0}".format(e)) + module.fail_json(msg=f"{e}") module.exit_json(changed=changed, instances=get_instances_info(ecs, ids)) if tags: @@ -997,7 +996,7 @@ def main(): if inst.add_tags(tags): changed = True except Exception as e: - module.fail_json(msg="{0}".format(e)) + module.fail_json(msg=f"{e}") module.exit_json(changed=changed, instances=get_instances_info(ecs, ids)) diff --git a/plugins/modules/alternatives.py b/plugins/modules/alternatives.py index ad26d04578..feebdd2b4a 100644 --- a/plugins/modules/alternatives.py +++ b/plugins/modules/alternatives.py @@ -222,7 +222,7 @@ class AlternativesModule(object): def install(self): if not os.path.exists(self.path): - self.module.fail_json(msg="Specified path %s does not exist" % self.path) + self.module.fail_json(msg=f"Specified path {self.path} does not exist") if not self.link: self.module.fail_json(msg='Needed to install the alternative, but unable to do so as we are missing the link') @@ -235,7 +235,7 @@ class AlternativesModule(object): cmd += [item for sublist in subcommands for item in sublist] self.result['changed'] = True - self.messages.append("Install alternative '%s' for '%s'." % (self.path, self.name)) + self.messages.append(f"Install alternative '{self.path}' for '{self.name}'.") if not self.module.check_mode: self.module.run_command(cmd, check_rc=True) @@ -256,7 +256,7 @@ class AlternativesModule(object): def remove(self): cmd = [self.UPDATE_ALTERNATIVES, '--remove', self.name, self.path] self.result['changed'] = True - self.messages.append("Remove alternative '%s' from '%s'." % (self.path, self.name)) + self.messages.append(f"Remove alternative '{self.path}' from '{self.name}'.") if not self.module.check_mode: self.module.run_command(cmd, check_rc=True) @@ -273,7 +273,7 @@ class AlternativesModule(object): cmd = [self.UPDATE_ALTERNATIVES, '--set', self.name, arg] self.result['changed'] = True - self.messages.append("Set alternative '%s' for '%s'." % (arg, self.name)) + self.messages.append(f"Set alternative '{arg}' for '{self.name}'.") if not self.module.check_mode: self.module.run_command(cmd, check_rc=True) @@ -283,7 +283,7 @@ class AlternativesModule(object): def auto(self): cmd = [self.UPDATE_ALTERNATIVES, '--auto', self.name] - self.messages.append("Set alternative to auto for '%s'." % (self.name)) + self.messages.append(f"Set alternative to auto for '{self.name}'.") self.result['changed'] = True if not self.module.check_mode: @@ -340,7 +340,7 @@ class AlternativesModule(object): ) if rc != 0: - self.module.debug("No current alternative found. '%s' exited with %s" % (self.UPDATE_ALTERNATIVES, rc)) + self.module.debug(f"No current alternative found. '{self.UPDATE_ALTERNATIVES}' exited with {rc}") return current_mode_regex = re.compile(r'\s-\s(?:status\sis\s)?(\w*)(?:\smode|.)$', re.MULTILINE) diff --git a/plugins/modules/android_sdk.py b/plugins/modules/android_sdk.py index 35900f39a5..523ea2bbde 100644 --- a/plugins/modules/android_sdk.py +++ b/plugins/modules/android_sdk.py @@ -169,7 +169,7 @@ class AndroidSdk(StateModuleHelper): if not self.check_mode: rc, stdout, stderr = self.sdkmanager.apply_packages_changes(pending_installation, self.vars.accept_licenses) if rc != 0: - self.do_raise("Could not install packages: %s" % stderr) + self.do_raise(f"Could not install packages: {stderr}") def state_absent(self): packages = self._parse_packages() @@ -179,7 +179,7 @@ class AndroidSdk(StateModuleHelper): if not self.check_mode: rc, stdout, stderr = self.sdkmanager.apply_packages_changes(to_be_deleted) if rc != 0: - self.do_raise("Could not uninstall packages: %s" % stderr) + self.do_raise(f"Could not uninstall packages: {stderr}") def state_latest(self): packages = self._parse_packages() @@ -192,7 +192,7 @@ class AndroidSdk(StateModuleHelper): if not self.check_mode: rc, stdout, stderr = self.sdkmanager.apply_packages_changes(to_be_installed, self.vars.accept_licenses) if rc != 0: - self.do_raise("Could not install packages: %s" % stderr) + self.do_raise(f"Could not install packages: {stderr}") @staticmethod def _map_packages_to_names(packages): diff --git a/plugins/modules/ansible_galaxy_install.py b/plugins/modules/ansible_galaxy_install.py index 919dadcd9a..ab9a57afb9 100644 --- a/plugins/modules/ansible_galaxy_install.py +++ b/plugins/modules/ansible_galaxy_install.py @@ -245,7 +245,7 @@ class AnsibleGalaxyInstall(ModuleHelper): line = out.splitlines()[0] match = self._RE_GALAXY_VERSION.match(line) if not match: - self.do_raise("Unable to determine ansible-galaxy version from: {0}".format(line)) + self.do_raise(f"Unable to determine ansible-galaxy version from: {line}") version = match.group("version") return version diff --git a/plugins/modules/apache2_mod_proxy.py b/plugins/modules/apache2_mod_proxy.py index 3b06736898..2bd96307a9 100644 --- a/plugins/modules/apache2_mod_proxy.py +++ b/plugins/modules/apache2_mod_proxy.py @@ -267,12 +267,12 @@ class BalancerMember(object): resp, info = fetch_url(self.module, self.management_url, headers={'Referer': self.management_url}) if info['status'] != 200: - raise ModuleHelperException("Could not get balancer_member_page, check for connectivity! {0}".format(info)) + raise ModuleHelperException(f"Could not get balancer_member_page, check for connectivity! {info}") try: soup = BeautifulSoup(resp) except TypeError as exc: - raise ModuleHelperException("Cannot parse balancer_member_page HTML! {0}".format(exc)) from exc + raise ModuleHelperException(f"Cannot parse balancer_member_page HTML! {exc}") from exc subsoup = find_all(find_all(soup, 'table')[1], 'tr') keys = find_all(subsoup[0], 'th') @@ -299,12 +299,12 @@ class BalancerMember(object): 'ignore_errors': '&w_status_I'} request_body = regexp_extraction(self.management_url, EXPRESSION, 1) - values_url = "".join("{0}={1}".format(url_param, 1 if values[mode] else 0) for mode, url_param in values_mapping.items()) - request_body = "{0}{1}".format(request_body, values_url) + values_url = "".join(f"{url_param}={1 if values[mode] else 0}" for mode, url_param in values_mapping.items()) + request_body = f"{request_body}{values_url}" response, info = fetch_url(self.module, self.management_url, data=request_body, headers={'Referer': self.management_url}) if info['status'] != 200: - raise ModuleHelperException("Could not set the member status! {0} {1}".format(self.host, info['status'])) + raise ModuleHelperException(f"Could not set the member status! {self.host} {info['status']}") attributes = property(get_member_attributes) status = property(get_member_status, set_member_status) @@ -327,8 +327,8 @@ class Balancer(object): def __init__(self, module, host, suffix, tls=False): proto = "https" if tls else "http" - self.base_url = '{0}://{1}'.format(proto, host) - self.url = '{0}://{1}{2}'.format(proto, host, suffix) + self.base_url = f'{proto}://{host}' + self.url = f'{proto}://{host}{suffix}' self.module = module self.page = self.fetch_balancer_page() @@ -336,7 +336,7 @@ class Balancer(object): """ Returns the balancer management html page as a string for later parsing.""" resp, info = fetch_url(self.module, self.url) if info['status'] != 200: - raise ModuleHelperException("Could not get balancer page! HTTP status response: {0}".format(info['status'])) + raise ModuleHelperException(f"Could not get balancer page! HTTP status response: {info['status']}") content = to_text(resp.read()) apache_version = regexp_extraction(content.upper(), APACHE_VERSION_EXPRESSION, 1) @@ -344,7 +344,7 @@ class Balancer(object): raise ModuleHelperException("Could not get the Apache server version from the balancer-manager") if not re.search(pattern=r"2\.4\.[\d]*", string=apache_version): - raise ModuleHelperException("This module only acts on an Apache2 2.4+ instance, current Apache2 version: {0}".format(apache_version)) + raise ModuleHelperException(f"This module only acts on an Apache2 2.4+ instance, current Apache2 version: {apache_version}") return content def get_balancer_members(self): @@ -352,7 +352,7 @@ class Balancer(object): try: soup = BeautifulSoup(self.page) except TypeError as e: - raise ModuleHelperException("Cannot parse balancer page HTML! {0}".format(self.page)) from e + raise ModuleHelperException(f"Cannot parse balancer page HTML! {self.page}") from e elements = find_all(soup, 'a') for element in elements[1::1]: @@ -413,7 +413,7 @@ class ApacheModProxy(ModuleHelper): self.vars.member = member.as_dict() if not member_exists: - self.do_raise(msg='{0} is not a member of the balancer {1}!'.format(self.vars.member_host, self.vars.balancer_vhost)) + self.do_raise(msg=f'{self.vars.member_host} is not a member of the balancer {self.vars.balancer_vhost}!') def main(): diff --git a/plugins/modules/apache2_module.py b/plugins/modules/apache2_module.py index 2421708262..6e3f10203c 100644 --- a/plugins/modules/apache2_module.py +++ b/plugins/modules/apache2_module.py @@ -142,7 +142,7 @@ def _module_is_enabled(module): result, stdout, stderr = module.run_command([control_binary, "-M"]) if result != 0: - error_msg = "Error executing %s: %s" % (control_binary, stderr) + error_msg = f"Error executing {control_binary}: {stderr}" if module.params['ignore_configcheck']: if 'AH00534' in stderr and 'mpm_' in module.params['name']: if module.params['warn_mpm_absent']: @@ -156,7 +156,7 @@ def _module_is_enabled(module): else: module.fail_json(msg=error_msg) - searchstring = ' ' + module.params['identifier'] + searchstring = f" {module.params['identifier']}" return searchstring in stdout @@ -188,11 +188,11 @@ def create_apache_identifier(name): if search in name: try: rematch = reexpr.search(name) - return rematch.group(1) + '_module' + return f"{rematch.group(1)}_module" except AttributeError: pass - return name + '_module' + return f"{name}_module" def _set_state(module, state): @@ -202,7 +202,7 @@ def _set_state(module, state): want_enabled = state == 'present' state_string = {'present': 'enabled', 'absent': 'disabled'}[state] a2mod_binary = {'present': 'a2enmod', 'absent': 'a2dismod'}[state] - success_msg = "Module %s %s" % (name, state_string) + success_msg = f"Module {name} {state_string}" if _module_is_enabled(module) != want_enabled: if module.check_mode: @@ -210,7 +210,7 @@ def _set_state(module, state): a2mod_binary_path = module.get_bin_path(a2mod_binary) if a2mod_binary_path is None: - module.fail_json(msg="%s not found. Perhaps this system does not use %s to manage apache" % (a2mod_binary, a2mod_binary)) + module.fail_json(msg=f"{a2mod_binary} not found. Perhaps this system does not use {a2mod_binary} to manage apache") a2mod_binary_cmd = [a2mod_binary_path] @@ -224,15 +224,10 @@ def _set_state(module, state): module.exit_json(changed=True, result=success_msg) else: msg = ( - 'Failed to set module {name} to {state}:\n' - '{stdout}\n' - 'Maybe the module identifier ({identifier}) was guessed incorrectly.' + f'Failed to set module {name} to {state_string}:\n' + f'{stdout}\n' + f'Maybe the module identifier ({module.params["identifier"]}) was guessed incorrectly.' 'Consider setting the "identifier" option.' - ).format( - name=name, - state=state_string, - stdout=stdout, - identifier=module.params['identifier'] ) module.fail_json(msg=msg, rc=result, diff --git a/plugins/modules/apk.py b/plugins/modules/apk.py index d16635e3b4..b65326094b 100644 --- a/plugins/modules/apk.py +++ b/plugins/modules/apk.py @@ -195,7 +195,7 @@ def update_package_db(module, exit): def query_toplevel(module, name, world): # world contains a list of top-level packages separated by ' ' or \n # packages may contain repository (@) or version (=<>~) separator characters or start with negation ! - regex = re.compile(r'^' + re.escape(name) + r'([@=<>~].+)?$') + regex = re.compile(rf"^{re.escape(name)}([@=<>~].+)?$") with open(world) as f: content = f.read().split() for p in content: @@ -216,7 +216,7 @@ def query_package(module, name): def query_latest(module, name): cmd = APK_PATH + ["version", name] rc, stdout, stderr = module.run_command(cmd, check_rc=False) - search_pattern = r"(%s)-[\d\.\w]+-[\d\w]+\s+(.)\s+[\d\.\w]+-[\d\w]+\s+" % (re.escape(name)) + search_pattern = rf"({re.escape(name)})-[\d\.\w]+-[\d\w]+\s+(.)\s+[\d\.\w]+-[\d\w]+\s+" match = re.search(search_pattern, stdout) if match and match.group(2) == "<": return False @@ -226,7 +226,7 @@ def query_latest(module, name): def query_virtual(module, name): cmd = APK_PATH + ["-v", "info", "--description", name] rc, stdout, stderr = module.run_command(cmd, check_rc=False) - search_pattern = r"^%s: virtual meta package" % (re.escape(name)) + search_pattern = rf"^{re.escape(name)}: virtual meta package" if re.search(search_pattern, stdout): return True return False @@ -293,8 +293,8 @@ def install_packages(module, names, state, world): rc, stdout, stderr = module.run_command(cmd, check_rc=False) packagelist = parse_for_packages(stdout) if rc != 0: - module.fail_json(msg="failed to install %s" % (packages), stdout=stdout, stderr=stderr, packages=packagelist) - module.exit_json(changed=True, msg="installed %s package(s)" % (packages), stdout=stdout, stderr=stderr, packages=packagelist) + module.fail_json(msg=f"failed to install {packages}", stdout=stdout, stderr=stderr, packages=packagelist) + module.exit_json(changed=True, msg=f"installed {packages} package(s)", stdout=stdout, stderr=stderr, packages=packagelist) def remove_packages(module, names): @@ -317,8 +317,8 @@ def remove_packages(module, names): rc = 1 break if rc != 0: - module.fail_json(msg="failed to remove %s package(s)" % (names), stdout=stdout, stderr=stderr, packages=packagelist) - module.exit_json(changed=True, msg="removed %s package(s)" % (names), stdout=stdout, stderr=stderr, packages=packagelist) + module.fail_json(msg=f"failed to remove {names} package(s)", stdout=stdout, stderr=stderr, packages=packagelist) + module.exit_json(changed=True, msg=f"removed {names} package(s)", stdout=stdout, stderr=stderr, packages=packagelist) # ========================================== # Main control flow. diff --git a/plugins/modules/apt_repo.py b/plugins/modules/apt_repo.py index 3d6da796b6..f90631195d 100644 --- a/plugins/modules/apt_repo.py +++ b/plugins/modules/apt_repo.py @@ -85,7 +85,7 @@ def apt_repo(module, *args): rc, out, err = module.run_command([APT_REPO_PATH] + args) if rc != 0: - module.fail_json(msg="'%s' failed: %s" % (' '.join(['apt-repo'] + args), err)) + module.fail_json(msg=f"'{' '.join(['apt-repo'] + args)}' failed: {err}") return out diff --git a/plugins/modules/apt_rpm.py b/plugins/modules/apt_rpm.py index 0c64385b1d..4786ee6e84 100644 --- a/plugins/modules/apt_rpm.py +++ b/plugins/modules/apt_rpm.py @@ -251,12 +251,12 @@ def remove_packages(module, packages): rc, out, err = module.run_command([APT_PATH, "-y", "remove", package], environ_update={"LANG": "C"}) if rc != 0: - module.fail_json(msg="failed to remove %s: %s" % (package, err)) + module.fail_json(msg=f"failed to remove {package}: {err}") remove_c += 1 if remove_c > 0: - return (True, "removed %s package(s)" % remove_c) + return (True, f"removed {remove_c} package(s)") return (False, "package(s) already absent") @@ -282,9 +282,9 @@ def install_packages(module, pkgspec, allow_upgrade=False): # apt-rpm always have 0 for exit code if --force is used if rc or not installed: - module.fail_json(msg="'%s' failed: %s" % (" ".join(command), err)) + module.fail_json(msg=f"'{' '.join(command)}' failed: {err}") else: - return (True, "%s present(s)" % packages) + return (True, f"{packages} present(s)") else: return (False, "Nothing to install") diff --git a/plugins/modules/archive.py b/plugins/modules/archive.py index fe850391c8..710a1c8fa6 100644 --- a/plugins/modules/archive.py +++ b/plugins/modules/archive.py @@ -305,7 +305,7 @@ class Archive(object, metaclass=abc.ABCMeta): if self.contains(_to_native(archive_name)): self.successes.append(path) except Exception as e: - self.errors.append('%s: %s' % (_to_native_ascii(path), _to_native(e))) + self.errors.append(f'{_to_native_ascii(path)}: {e}') def add_single_target(self, path): if self.format in ('zip', 'tar'): @@ -325,7 +325,7 @@ class Archive(object, metaclass=abc.ABCMeta): self.module.fail_json( path=_to_native(path), dest=_to_native(self.destination), - msg='Unable to write to compressed file: %s' % _to_native(e), exception=format_exc() + msg=f'Unable to write to compressed file: {e}', exception=format_exc() ) def add_targets(self): @@ -347,18 +347,16 @@ class Archive(object, metaclass=abc.ABCMeta): if self.format in ('zip', 'tar'): archive_format = self.format else: - archive_format = 'tar.' + self.format + archive_format = f"tar.{self.format}" self.module.fail_json( - msg='Error when writing %s archive at %s: %s' % ( - archive_format, _to_native(self.destination), _to_native(e) - ), + msg=f'Error when writing {archive_format} archive at {_to_native(self.destination)}: {e}', exception=format_exc() ) self.close() if self.errors: self.module.fail_json( - msg='Errors when writing archive at %s: %s' % (_to_native(self.destination), '; '.join(self.errors)) + msg=f"Errors when writing archive at {_to_native(self.destination)}: {'; '.join(self.errors)}" ) def is_different_from_original(self): @@ -400,7 +398,7 @@ class Archive(object, metaclass=abc.ABCMeta): except OSError as e: self.module.fail_json( path=_to_native(path), - msg='Unable to remove source file: %s' % _to_native(e), exception=format_exc() + msg=f'Unable to remove source file: {e}', exception=format_exc() ) def remove_targets(self): @@ -459,7 +457,7 @@ class Archive(object, metaclass=abc.ABCMeta): elif self.format == 'xz': f = lzma.LZMAFile(path, mode) else: - self.module.fail_json(msg="%s is not a valid format" % self.format) + self.module.fail_json(msg=f"{self.format} is not a valid format") return f @@ -536,7 +534,7 @@ class TarArchive(Archive): def open(self): if self.format in ('gz', 'bz2'): - self.file = tarfile.open(_to_native_ascii(self.destination), 'w|' + self.format) + self.file = tarfile.open(_to_native_ascii(self.destination), f"w|{self.format}") # python3 tarfile module allows xz format but for python2 we have to create the tarfile # in memory and then compress it with lzma. elif self.format == 'xz': @@ -545,7 +543,7 @@ class TarArchive(Archive): elif self.format == 'tar': self.file = tarfile.open(_to_native_ascii(self.destination), 'w') else: - self.module.fail_json(msg="%s is not a valid archive format" % self.format) + self.module.fail_json(msg=f"{self.format} is not a valid archive format") def _add(self, path, archive_name): def filter(tarinfo): @@ -563,7 +561,7 @@ class TarArchive(Archive): checksums = set((info.name, info.chksum) for info in archive.getmembers()) archive.close() else: - archive = tarfile.open(_to_native_ascii(path), 'r|' + self.format) + archive = tarfile.open(_to_native_ascii(path), f"r|{self.format}") checksums = set((info.name, info.chksum) for info in archive.getmembers()) archive.close() except (LZMAError, tarfile.ReadError, tarfile.CompressionError): diff --git a/plugins/modules/awall.py b/plugins/modules/awall.py index 37e1e87a1c..6e5b5b1775 100644 --- a/plugins/modules/awall.py +++ b/plugins/modules/awall.py @@ -71,7 +71,7 @@ from ansible.module_utils.basic import AnsibleModule def activate(module): - cmd = "%s activate --force" % (AWALL_PATH) + cmd = f"{AWALL_PATH} activate --force" rc, stdout, stderr = module.run_command(cmd) if rc == 0: return True @@ -80,9 +80,9 @@ def activate(module): def is_policy_enabled(module, name): - cmd = "%s list" % (AWALL_PATH) + cmd = f"{AWALL_PATH} list" rc, stdout, stderr = module.run_command(cmd) - if re.search(r"^%s\s+enabled" % name, stdout, re.MULTILINE): + if re.search(rf"^{name}\s+enabled", stdout, re.MULTILINE): return True return False @@ -96,15 +96,15 @@ def enable_policy(module, names, act): module.exit_json(changed=False, msg="policy(ies) already enabled") names = " ".join(policies) if module.check_mode: - cmd = "%s list" % (AWALL_PATH) + cmd = f"{AWALL_PATH} list" else: - cmd = "%s enable %s" % (AWALL_PATH, names) + cmd = f"{AWALL_PATH} enable {names}" rc, stdout, stderr = module.run_command(cmd) if rc != 0: - module.fail_json(msg="failed to enable %s" % names, stdout=stdout, stderr=stderr) + module.fail_json(msg=f"failed to enable {names}", stdout=stdout, stderr=stderr) if act and not module.check_mode: activate(module) - module.exit_json(changed=True, msg="enabled awall policy(ies): %s" % names) + module.exit_json(changed=True, msg=f"enabled awall policy(ies): {names}") def disable_policy(module, names, act): @@ -116,15 +116,15 @@ def disable_policy(module, names, act): module.exit_json(changed=False, msg="policy(ies) already disabled") names = " ".join(policies) if module.check_mode: - cmd = "%s list" % (AWALL_PATH) + cmd = f"{AWALL_PATH} list" else: - cmd = "%s disable %s" % (AWALL_PATH, names) + cmd = f"{AWALL_PATH} disable {names}" rc, stdout, stderr = module.run_command(cmd) if rc != 0: - module.fail_json(msg="failed to disable %s" % names, stdout=stdout, stderr=stderr) + module.fail_json(msg=f"failed to disable {names}", stdout=stdout, stderr=stderr) if act and not module.check_mode: activate(module) - module.exit_json(changed=True, msg="disabled awall policy(ies): %s" % names) + module.exit_json(changed=True, msg=f"disabled awall policy(ies): {names}") def main():