diff --git a/changelogs/fragments/10969-mod-fstr-i.yml b/changelogs/fragments/10969-mod-fstr-i.yml new file mode 100644 index 0000000000..5d21033f82 --- /dev/null +++ b/changelogs/fragments/10969-mod-fstr-i.yml @@ -0,0 +1,21 @@ +minor_changes: + - ibm_sa_domain - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - icinga2_feature - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - icinga2_host - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - idrac_redfish_command - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - idrac_redfish_config - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - idrac_redfish_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - ilo_redfish_command - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - ilo_redfish_config - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - ilo_redfish_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - imc_rest - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - imgadm - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - infinity - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - influxdb_retention_policy - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - ini_file - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - installp - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - interfaces_file - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - irc - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - iso_create - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - iso_customize - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). + - iso_extract - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10969). diff --git a/plugins/modules/ibm_sa_domain.py b/plugins/modules/ibm_sa_domain.py index f377bce761..db204a1a1e 100644 --- a/plugins/modules/ibm_sa_domain.py +++ b/plugins/modules/ibm_sa_domain.py @@ -151,7 +151,7 @@ def main(): state = module.params['state'] state_changed = False - msg = 'Domain \'{0}\''.format(module.params['domain']) + msg = f"Domain '{module.params['domain']}'" if state == 'present' and not domain: state_changed = execute_pyxcli_command( module, 'domain_create', xcli_client) diff --git a/plugins/modules/icinga2_feature.py b/plugins/modules/icinga2_feature.py index 6899fe2e23..5e6abedd0c 100644 --- a/plugins/modules/icinga2_feature.py +++ b/plugins/modules/icinga2_feature.py @@ -81,8 +81,8 @@ class Icinga2FeatureHelper: "Ensure icinga2 is installed and present in binary path.") # If feature is already in good state, just exit - if (re.search("Disabled features:.* %s[ \n]" % self.feature_name, out) and self.state == "absent") or \ - (re.search("Enabled features:.* %s[ \n]" % self.feature_name, out) and self.state == "present"): + if (re.search(f"Disabled features:.* {self.feature_name}[ \n]", out) and self.state == "absent") or \ + (re.search(f"Enabled features:.* {self.feature_name}[ \n]", out) and self.state == "present"): self.module.exit_json(changed=False) if self.module.check_mode: @@ -95,10 +95,7 @@ class Icinga2FeatureHelper: change_applied = False if self.state == "present": if rc != 0: - self.module.fail_json(msg="Failed to %s feature %s." - " icinga2 command returned %s" % (feature_enable_str, - self.feature_name, - out)) + self.module.fail_json(msg=f"Failed to {feature_enable_str} feature {self.feature_name}. icinga2 command returned {out}") if re.search("already enabled", out) is None: change_applied = True @@ -106,10 +103,10 @@ class Icinga2FeatureHelper: if rc == 0: change_applied = True # RC is not 0 for this already disabled feature, handle it as no change applied - elif re.search("Cannot disable feature '%s'. Target file .* does not exist" % self.feature_name, out): + elif re.search(f"Cannot disable feature '{self.feature_name}'. Target file .* does not exist", out): change_applied = False else: - self.module.fail_json(msg="Failed to disable feature. Command returns %s" % out) + self.module.fail_json(msg=f"Failed to disable feature. Command returns {out}") self.module.exit_json(changed=change_applied) diff --git a/plugins/modules/icinga2_host.py b/plugins/modules/icinga2_host.py index 39a7b48a6d..f5599ad86d 100644 --- a/plugins/modules/icinga2_host.py +++ b/plugins/modules/icinga2_host.py @@ -154,7 +154,7 @@ class icinga2_api: 'Accept': 'application/json', 'X-HTTP-Method-Override': method, } - url = self.module.params.get("url") + "/" + path + url = f"{self.module.params.get('url')}/{path}" rsp, info = fetch_url(module=self.module, url=url, data=data, headers=headers, method=method, use_proxy=self.module.params['use_proxy']) body = '' if rsp: @@ -171,7 +171,7 @@ class icinga2_api: def exists(self, hostname): data = { - "filter": "match(\"" + hostname + "\", host.name)", + "filter": f"match(\"{hostname}\", host.name)", } ret = self.call_url( path="v1/objects/hosts", @@ -184,7 +184,7 @@ class icinga2_api: def create(self, hostname, data): ret = self.call_url( - path="v1/objects/hosts/" + hostname, + path=f"v1/objects/hosts/{hostname}", data=self.module.jsonify(data), method="PUT" ) @@ -193,7 +193,7 @@ class icinga2_api: def delete(self, hostname): data = {"cascade": 1} ret = self.call_url( - path="v1/objects/hosts/" + hostname, + path=f"v1/objects/hosts/{hostname}", data=self.module.jsonify(data), method="DELETE" ) @@ -201,7 +201,7 @@ class icinga2_api: def modify(self, hostname, data): ret = self.call_url( - path="v1/objects/hosts/" + hostname, + path=f"v1/objects/hosts/{hostname}", data=self.module.jsonify(data), method="POST" ) @@ -209,7 +209,7 @@ class icinga2_api: def diff(self, hostname, data): ret = self.call_url( - path="v1/objects/hosts/" + hostname, + path=f"v1/objects/hosts/{hostname}", method="GET" ) changed = False @@ -263,7 +263,7 @@ def main(): icinga = icinga2_api(module=module) icinga.check_connection() except Exception as e: - module.fail_json(msg="unable to connect to Icinga. Exception message: %s" % (e)) + module.fail_json(msg=f"unable to connect to Icinga. Exception message: {e}") data = { 'templates': template, @@ -275,7 +275,7 @@ def main(): 'vars.made_by': "ansible" } } - data['attrs'].update({'vars.' + key: value for key, value in variables.items()}) + data['attrs'].update({f"vars.{key}": value for key, value in variables.items()}) changed = False if icinga.exists(name): @@ -288,9 +288,9 @@ def main(): if ret['code'] == 200: changed = True else: - module.fail_json(msg="bad return code (%s) deleting host: '%s'" % (ret['code'], ret['data'])) + module.fail_json(msg=f"bad return code ({ret['code']}) deleting host: '{ret['data']}'") except Exception as e: - module.fail_json(msg="exception deleting host: " + str(e)) + module.fail_json(msg=f"exception deleting host: {e}") elif icinga.diff(name, data): if module.check_mode: @@ -304,7 +304,7 @@ def main(): if ret['code'] == 200: changed = True else: - module.fail_json(msg="bad return code (%s) modifying host: '%s'" % (ret['code'], ret['data'])) + module.fail_json(msg=f"bad return code ({ret['code']}) modifying host: '{ret['data']}'") else: if state == "present": @@ -316,9 +316,9 @@ def main(): if ret['code'] == 200: changed = True else: - module.fail_json(msg="bad return code (%s) creating host: '%s'" % (ret['code'], ret['data'])) + module.fail_json(msg=f"bad return code ({ret['code']}) creating host: '{ret['data']}'") except Exception as e: - module.fail_json(msg="exception creating host: " + str(e)) + module.fail_json(msg=f"exception creating host: {e}") module.exit_json(changed=changed, name=name, data=data) diff --git a/plugins/modules/idrac_redfish_command.py b/plugins/modules/idrac_redfish_command.py index b60126764a..1c569e1281 100644 --- a/plugins/modules/idrac_redfish_command.py +++ b/plugins/modules/idrac_redfish_command.py @@ -117,7 +117,7 @@ class IdracRedfishUtils(RedfishUtils): data = response['data'] if key not in data: - return {'ret': False, 'msg': "Key %s not found" % key} + return {'ret': False, 'msg': f"Key {key} not found"} bios_uri = data[key]["@odata.id"] @@ -132,14 +132,14 @@ class IdracRedfishUtils(RedfishUtils): payload = {"TargetSettingsURI": set_bios_attr_uri} response = self.post_request( - self.root_uri + self.manager_uri + "/" + jobs, payload) + f"{self.root_uri}{self.manager_uri}/{jobs}", payload) if response['ret'] is False: return response response_output = response['resp'].__dict__ job_id_full = response_output["headers"]["Location"] job_id = re.search("JID_.+", job_id_full).group() - return {'ret': True, 'msg': "Config job %s created" % job_id, 'job_id': job_id_full} + return {'ret': True, 'msg': f"Config job {job_id} created", 'job_id': job_id_full} CATEGORY_COMMANDS_ALL = { @@ -192,19 +192,19 @@ def main(): resource_id = module.params['resource_id'] # Build root URI - root_uri = "https://" + module.params['baseuri'] + root_uri = f"https://{module.params['baseuri']}" rf_utils = IdracRedfishUtils(creds, root_uri, timeout, module, resource_id=resource_id, data_modification=True) # Check that Category is valid if category not in CATEGORY_COMMANDS_ALL: - module.fail_json(msg=to_native("Invalid Category '%s'. Valid Categories = %s" % (category, list(CATEGORY_COMMANDS_ALL.keys())))) + module.fail_json(msg=to_native(f"Invalid Category '{category}'. Valid Categories = {list(CATEGORY_COMMANDS_ALL.keys())}")) # Check that all commands are valid for cmd in command_list: # Fail if even one command given is invalid if cmd not in CATEGORY_COMMANDS_ALL[category]: - module.fail_json(msg=to_native("Invalid Command '%s'. Valid Commands = %s" % (cmd, CATEGORY_COMMANDS_ALL[category]))) + module.fail_json(msg=to_native(f"Invalid Command '{cmd}'. Valid Commands = {CATEGORY_COMMANDS_ALL[category]}")) # Organize by Categories / Commands diff --git a/plugins/modules/idrac_redfish_config.py b/plugins/modules/idrac_redfish_config.py index e7d6250624..7eec4d0ce6 100644 --- a/plugins/modules/idrac_redfish_config.py +++ b/plugins/modules/idrac_redfish_config.py @@ -192,7 +192,7 @@ class IdracRedfishUtils(RedfishUtils): attrs_bad = {} # Store attrs which were not found in the system # Search for key entry and extract URI from it - response = self.get_request(self.root_uri + manager_uri + "/" + key) + response = self.get_request(f"{self.root_uri}{manager_uri}/{key}") if response['ret'] is False: return response result['ret'] = True @@ -200,7 +200,7 @@ class IdracRedfishUtils(RedfishUtils): if key not in data: return {'ret': False, - 'msg': "%s: Key %s not found" % (command, key), + 'msg': f"{command}: Key {key} not found", 'warning': ""} for attr_name, attr_value in attributes.items(): @@ -219,7 +219,7 @@ class IdracRedfishUtils(RedfishUtils): warning = "" if attrs_bad: - warning = "Incorrect attributes %s" % (attrs_bad) + warning = f"Incorrect attributes {attrs_bad}" if not attrs_to_patch: return {'ret': True, 'changed': False, @@ -227,12 +227,12 @@ class IdracRedfishUtils(RedfishUtils): 'warning': warning} payload = {"Attributes": attrs_to_patch} - response = self.patch_request(self.root_uri + manager_uri + "/" + key, payload) + response = self.patch_request(f"{self.root_uri}{manager_uri}/{key}", payload) if response['ret'] is False: return response return {'ret': True, 'changed': True, - 'msg': "%s: Modified Manager attributes %s" % (command, attrs_to_patch), + 'msg': f"{command}: Modified Manager attributes {attrs_to_patch}", 'warning': warning} @@ -292,19 +292,19 @@ def main(): resource_id = module.params['resource_id'] # Build root URI - root_uri = "https://" + module.params['baseuri'] + root_uri = f"https://{module.params['baseuri']}" rf_utils = IdracRedfishUtils(creds, root_uri, timeout, module, resource_id=resource_id, data_modification=True) # Check that Category is valid if category not in CATEGORY_COMMANDS_ALL: - module.fail_json(msg=to_native("Invalid Category '%s'. Valid Categories = %s" % (category, list(CATEGORY_COMMANDS_ALL.keys())))) + module.fail_json(msg=to_native(f"Invalid Category '{category}'. Valid Categories = {list(CATEGORY_COMMANDS_ALL.keys())}")) # Check that all commands are valid for cmd in command_list: # Fail if even one command given is invalid if cmd not in CATEGORY_COMMANDS_ALL[category]: - module.fail_json(msg=to_native("Invalid Command '%s'. Valid Commands = %s" % (cmd, CATEGORY_COMMANDS_ALL[category]))) + module.fail_json(msg=to_native(f"Invalid Command '{cmd}'. Valid Commands = {CATEGORY_COMMANDS_ALL[category]}")) # check for mutually exclusive commands try: diff --git a/plugins/modules/idrac_redfish_info.py b/plugins/modules/idrac_redfish_info.py index 309cefc15f..6e589255c7 100644 --- a/plugins/modules/idrac_redfish_info.py +++ b/plugins/modules/idrac_redfish_info.py @@ -169,7 +169,7 @@ class IdracRedfishUtils(RedfishUtils): except (AttributeError, KeyError) as e: result['ret'] = False - result['msg'] = "Failed to find attribute/key: " + str(e) + result['msg'] = f"Failed to find attribute/key: {e}" result["entries"] = manager_attributes return result @@ -218,18 +218,18 @@ def main(): timeout = module.params['timeout'] # Build root URI - root_uri = "https://" + module.params['baseuri'] + root_uri = f"https://{module.params['baseuri']}" rf_utils = IdracRedfishUtils(creds, root_uri, timeout, module) # Check that Category is valid if category not in CATEGORY_COMMANDS_ALL: - module.fail_json(msg=to_native("Invalid Category '%s'. Valid Categories = %s" % (category, list(CATEGORY_COMMANDS_ALL.keys())))) + module.fail_json(msg=to_native(f"Invalid Category '{category}'. Valid Categories = {list(CATEGORY_COMMANDS_ALL.keys())}")) # Check that all commands are valid for cmd in command_list: # Fail if even one command given is invalid if cmd not in CATEGORY_COMMANDS_ALL[category]: - module.fail_json(msg=to_native("Invalid Command '%s'. Valid Commands = %s" % (cmd, CATEGORY_COMMANDS_ALL[category]))) + module.fail_json(msg=to_native(f"Invalid Command '{cmd}'. Valid Commands = {CATEGORY_COMMANDS_ALL[category]}")) # Organize by Categories / Commands diff --git a/plugins/modules/ilo_redfish_command.py b/plugins/modules/ilo_redfish_command.py index 7f20a45631..1792a1aa8f 100644 --- a/plugins/modules/ilo_redfish_command.py +++ b/plugins/modules/ilo_redfish_command.py @@ -143,20 +143,20 @@ def main(): timeout = module.params['timeout'] # Build root URI - root_uri = "https://" + module.params['baseuri'] + root_uri = f"https://{module.params['baseuri']}" rf_utils = iLORedfishUtils(creds, root_uri, timeout, module) # Check that Category is valid if category not in CATEGORY_COMMANDS_ALL: module.fail_json(msg=to_native( - "Invalid Category '%s'. Valid Categories = %s" % (category, list(CATEGORY_COMMANDS_ALL.keys())))) + f"Invalid Category '{category}'. Valid Categories = {list(CATEGORY_COMMANDS_ALL.keys())}")) # Check that all commands are valid for cmd in command_list: # Fail if even one command given is invalid if cmd not in CATEGORY_COMMANDS_ALL[category]: module.fail_json( - msg=to_native("Invalid Command '%s'. Valid Commands = %s" % (cmd, CATEGORY_COMMANDS_ALL[category]))) + msg=to_native(f"Invalid Command '{cmd}'. Valid Commands = {CATEGORY_COMMANDS_ALL[category]}")) if category == "Systems": # execute only if we find a System resource diff --git a/plugins/modules/ilo_redfish_config.py b/plugins/modules/ilo_redfish_config.py index 5cd441827f..ed61c7ffd6 100644 --- a/plugins/modules/ilo_redfish_config.py +++ b/plugins/modules/ilo_redfish_config.py @@ -161,7 +161,7 @@ def main(): timeout = module.params['timeout'] - root_uri = "https://" + module.params['baseuri'] + root_uri = f"https://{module.params['baseuri']}" rf_utils = iLORedfishUtils(creds, root_uri, timeout, module) mgr_attributes = {'mgr_attr_name': module.params['attribute_name'], 'mgr_attr_value': module.params['attribute_value']} @@ -171,8 +171,7 @@ def main(): cmd for cmd in command_list if cmd not in CATEGORY_COMMANDS_ALL[category]] if offending: - module.fail_json(msg=to_native("Invalid Command(s): '%s'. Allowed Commands = %s" % ( - offending, CATEGORY_COMMANDS_ALL[category]))) + module.fail_json(msg=to_native(f"Invalid Command(s): '{offending}'. Allowed Commands = {CATEGORY_COMMANDS_ALL[category]}")) if category == "Manager": resource = rf_utils._find_managers_resource() diff --git a/plugins/modules/ilo_redfish_info.py b/plugins/modules/ilo_redfish_info.py index 6eb7d7b3f4..9fa7c36853 100644 --- a/plugins/modules/ilo_redfish_info.py +++ b/plugins/modules/ilo_redfish_info.py @@ -149,7 +149,7 @@ def main(): timeout = module.params['timeout'] - root_uri = "https://" + module.params['baseuri'] + root_uri = f"https://{module.params['baseuri']}" rf_utils = iLORedfishUtils(creds, root_uri, timeout, module) # Build Category list @@ -177,10 +177,10 @@ def main(): for cmd in command_list: # Fail if even one command given is invalid if cmd not in CATEGORY_COMMANDS_ALL[category]: - module.fail_json(msg="Invalid Command: %s" % cmd) + module.fail_json(msg=f"Invalid Command: {cmd}") else: # Fail if even one category given is invalid - module.fail_json(msg="Invalid Category: %s" % category) + module.fail_json(msg=f"Invalid Category: {category}") # Organize by Categories / Commands if category == "Sessions": diff --git a/plugins/modules/imc_rest.py b/plugins/modules/imc_rest.py index ef543c62e0..bcef41da3f 100644 --- a/plugins/modules/imc_rest.py +++ b/plugins/modules/imc_rest.py @@ -304,14 +304,14 @@ def imc_response(module, rawoutput, rawinput=''): result['output'] = rawoutput result['error_code'] = xmloutput.get('errorCode') result['error_text'] = xmloutput.get('errorDescr') - module.fail_json(msg='Request failed: %(error_text)s' % result, **result) + module.fail_json(msg=f"Request failed: {result['error_text']}", **result) return result def logout(module, url, cookie, timeout): ''' Perform a logout, if needed ''' - data = '' % (cookie, cookie) + data = f'' resp, auth = fetch_url(module, url, data=data, method="POST", timeout=timeout) @@ -371,17 +371,17 @@ def main(): if os.path.isfile(path): file_exists = True else: - module.fail_json(msg='Cannot find/access path:\n%s' % path) + module.fail_json(msg=f'Cannot find/access path:\n{path}') start = now() # Perform login first - url = '%s://%s/nuova' % (protocol, hostname) - data = '' % (username, password) + url = f'{protocol}://{hostname}/nuova' + data = f'' resp, auth = fetch_url(module, url, data=data, method='POST', timeout=timeout) if resp is None or auth['status'] != 200: result['elapsed'] = (now() - start).seconds - module.fail_json(msg='Task failed with error %(status)s: %(msg)s' % auth, **result) + module.fail_json(msg=f"Task failed with error {auth['status']}: {auth['msg']}", **result) result.update(imc_response(module, resp.read())) # Store cookie for future requests @@ -414,7 +414,7 @@ def main(): resp, info = fetch_url(module, url, data=data, method='POST', timeout=timeout) if resp is None or info['status'] != 200: result['elapsed'] = (now() - start).seconds - module.fail_json(msg='Task failed with error %(status)s: %(msg)s' % info, **result) + module.fail_json(msg=f"Task failed with error {info['status']}: {info['msg']}", **result) # Merge results with previous results rawoutput = resp.read() diff --git a/plugins/modules/imgadm.py b/plugins/modules/imgadm.py index da016f8597..e92ac2b089 100644 --- a/plugins/modules/imgadm.py +++ b/plugins/modules/imgadm.py @@ -163,7 +163,7 @@ class Imgadm(object): (rc, stdout, stderr) = self.module.run_command(cmd) if rc != 0: - self.module.fail_json(msg='Failed to update images: {0}'.format(self.errmsg(stderr))) + self.module.fail_json(msg=f'Failed to update images: {self.errmsg(stderr)}') # There is no feedback from imgadm(1M) to determine if anything # was actually changed. So treat this as an 'always-changes' operation. @@ -185,32 +185,32 @@ class Imgadm(object): (rc, stdout, stderr) = self.module.run_command(cmd) if rc != 0: - self.module.fail_json(msg='Failed to add source: {0}'.format(self.errmsg(stderr))) + self.module.fail_json(msg=f'Failed to add source: {self.errmsg(stderr)}') # Check the various responses. # Note that trying to add a source with the wrong type is handled # above as it results in a non-zero status. - regex = 'Already have "{0}" image source "{1}", no change'.format(imgtype, source) + regex = f'Already have "{imgtype}" image source "{source}", no change' if re.match(regex, stdout): self.changed = False - regex = 'Added "%s" image source "%s"' % (imgtype, source) + regex = f'Added "{imgtype}" image source "{source}"' if re.match(regex, stdout): self.changed = True else: # Type is ignored by imgadm(1M) here - cmd += ' -d %s' % source + cmd += f' -d {source}' (rc, stdout, stderr) = self.module.run_command(cmd) if rc != 0: - self.module.fail_json(msg='Failed to remove source: {0}'.format(self.errmsg(stderr))) + self.module.fail_json(msg=f'Failed to remove source: {self.errmsg(stderr)}') - regex = 'Do not have image source "%s", no change' % source + regex = f'Do not have image source "{source}", no change' if re.match(regex, stdout): self.changed = False - regex = 'Deleted ".*" image source "%s"' % source + regex = f'Deleted ".*" image source "{source}"' if re.match(regex, stdout): self.changed = True @@ -225,7 +225,7 @@ class Imgadm(object): (rc, stdout, stderr) = self.module.run_command(cmd) if rc != 0: - self.module.fail_json(msg='Failed to vacuum images: {0}'.format(self.errmsg(stderr))) + self.module.fail_json(msg=f'Failed to vacuum images: {self.errmsg(stderr)}') else: if stdout == '': self.changed = False @@ -236,9 +236,9 @@ class Imgadm(object): (rc, stdout, stderr) = self.module.run_command(cmd) if rc != 0: - self.module.fail_json(msg='Failed to import image: {0}'.format(self.errmsg(stderr))) + self.module.fail_json(msg=f'Failed to import image: {self.errmsg(stderr)}') - regex = r'Image {0} \(.*\) is already installed, skipping'.format(self.uuid) + regex = rf'Image {self.uuid} \(.*\) is already installed, skipping' if re.match(regex, stdout): self.changed = False @@ -246,7 +246,7 @@ class Imgadm(object): if re.match(regex, stderr): self.changed = False - regex = 'Imported image {0}.*'.format(self.uuid) + regex = f'Imported image {self.uuid}.*' if re.match(regex, stdout.splitlines()[-1]): self.changed = True else: @@ -259,7 +259,7 @@ class Imgadm(object): # in order to determine if there was a change. self.changed = False - regex = 'Deleted image {0}'.format(self.uuid) + regex = f'Deleted image {self.uuid}' if re.match(regex, stdout): self.changed = True diff --git a/plugins/modules/infinity.py b/plugins/modules/infinity.py index 7f568faa0d..68d43f845a 100644 --- a/plugins/modules/infinity.py +++ b/plugins/modules/infinity.py @@ -156,7 +156,7 @@ class Infinity(object): self.module = module self.auth_user = username self.auth_pass = password - self.base_url = "https://%s/rest/v1/" % (str(server_ip)) + self.base_url = f"https://{server_ip}/rest/v1/" def _get_api_call_ansible_handler( self, @@ -193,8 +193,7 @@ class Infinity(object): if response_raw.code not in stat_codes: self.module.exit_json( changed=False, - meta=" openurl response_raw.code show error and error code is %r" % - (response_raw.code)) + meta=f" openurl response_raw.code show error and error code is {response_raw.code!r}") else: if isinstance(response, str) and len(response) > 0: payload = response @@ -224,7 +223,7 @@ class Infinity(object): params = {} response = None if network_id: - resource_url = "networks/" + str(network_id) + resource_url = f"networks/{network_id}" response = self._get_api_call_ansible_handler(method, resource_url) if network_id is None and network_name: method = "get" @@ -283,7 +282,7 @@ class Infinity(object): self.module.exit_json( msg="You must specify the option 'network_id'.") if network_id: - resource_url = "networks/" + str(network_id) + "/reserve_ip" + resource_url = f"networks/{network_id}/reserve_ip" response = self._get_api_call_ansible_handler(method, resource_url) if response and response.find( "[") >= 0 and response.find("]") >= 0: @@ -306,12 +305,11 @@ class Infinity(object): self.module.exit_json( msg="You must specify those two options: 'network_id' and 'ip_address'.") - resource_url = "networks/" + str(network_id) + "/children" + resource_url = f"networks/{network_id}/children" response = self._get_api_call_ansible_handler(method, resource_url) if not response: self.module.exit_json( - msg="There is an error in release ip %s from network %s." % - (ip_address, network_id)) + msg=f"There is an error in release ip {ip_address} from network {network_id}.") ip_list = json.loads(response) ip_idlist = [] @@ -321,7 +319,7 @@ class Infinity(object): deleted_ip_id = '' for ip_id in ip_idlist: ip_response = '' - resource_url = "ip_addresses/" + str(ip_id) + resource_url = f"ip_addresses/{ip_id}" ip_response = self._get_api_call_ansible_handler( method, resource_url, @@ -332,13 +330,12 @@ class Infinity(object): break if deleted_ip_id: method = 'delete' - resource_url = "ip_addresses/" + str(deleted_ip_id) + resource_url = f"ip_addresses/{deleted_ip_id}" response = self._get_api_call_ansible_handler( method, resource_url, stat_codes=[204]) else: self.module.exit_json( - msg=" When release ip, could not find the ip address %r from the given network %r' ." % - (ip_address, network_id)) + msg=f" When release ip, could not find the ip address {ip_address} from the given network {network_id}' .") return response @@ -358,7 +355,7 @@ class Infinity(object): if network_id is None and network_name: network_id = self.get_network_id(network_name=network_name) if network_id: - resource_url = "networks/" + str(network_id) + resource_url = f"networks/{network_id}" response = self._get_api_call_ansible_handler( method, resource_url, stat_codes=[204]) return response @@ -386,7 +383,7 @@ class Infinity(object): self.module.exit_json( msg="You must specify those options: 'network_id', 'reserved_network_name' and 'reserved_network_size'") if network_id: - resource_url = "networks/" + str(network_id) + "/reserve_network" + resource_url = f"networks/{network_id}/reserve_network" if not reserved_network_family: reserved_network_family = '4' if not reserved_network_type: @@ -423,12 +420,11 @@ class Infinity(object): self.module.exit_json( msg="You must specify those options 'network_id', 'reserved_network_name' and 'reserved_network_size'") matched_network_id = "" - resource_url = "networks/" + str(network_id) + "/children" + resource_url = f"networks/{network_id}/children" response = self._get_api_call_ansible_handler(method, resource_url) if not response: self.module.exit_json( - msg=" there is an error in releasing network %r from network %s." % - (network_id, released_network_name)) + msg=f" there is an error in releasing network {network_id} from network {released_network_name}.") if response: response = json.loads(response) for child_net in response: @@ -438,13 +434,12 @@ class Infinity(object): response = None if matched_network_id: method = 'delete' - resource_url = "networks/" + str(matched_network_id) + resource_url = f"networks/{matched_network_id}" response = self._get_api_call_ansible_handler( method, resource_url, stat_codes=[204]) else: self.module.exit_json( - msg=" When release network , could not find the network %r from the given superent %r' " % - (released_network_name, network_id)) + msg=f" When release network , could not find the network {released_network_name} from the given superent {network_id} ") return response diff --git a/plugins/modules/influxdb_retention_policy.py b/plugins/modules/influxdb_retention_policy.py index c1848a4694..b49aa1c21f 100644 --- a/plugins/modules/influxdb_retention_policy.py +++ b/plugins/modules/influxdb_retention_policy.py @@ -144,7 +144,6 @@ except ImportError: from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.general.plugins.module_utils.influxdb import InfluxDb -from ansible.module_utils.common.text.converters import to_native VALID_DURATION_REGEX = re.compile(r'^(INF|(\d+(ns|u|ยต|ms|s|m|h|d|w)))+$') @@ -201,7 +200,7 @@ def find_retention_policy(module, client): retention_policy = policy break except requests.exceptions.ConnectionError as e: - module.fail_json(msg="Cannot connect to database %s on %s : %s" % (database_name, hostname, to_native(e))) + module.fail_json(msg=f"Cannot connect to database {database_name} on {hostname} : {e}") if retention_policy is not None: retention_policy["duration"] = parse_duration_literal(retention_policy["duration"], extended=True) diff --git a/plugins/modules/ini_file.py b/plugins/modules/ini_file.py index 27b55c3bf4..3170071b69 100644 --- a/plugins/modules/ini_file.py +++ b/plugins/modules/ini_file.py @@ -266,12 +266,12 @@ from ansible.module_utils.common.text.converters import to_bytes, to_text def match_opt(option, line): option = re.escape(option) - return re.match('( |\t)*([#;]?)( |\t)*(%s)( |\t)*(=|$)( |\t)*(.*)' % option, line) + return re.match(f'( |\t)*([#;]?)( |\t)*({option})( |\t)*(=|$)( |\t)*(.*)', line) def match_active_opt(option, line): option = re.escape(option) - return re.match('()()( |\t)*(%s)( |\t)*(=|$)( |\t)*(.*)' % option, line) + return re.match(f'()()( |\t)*({option})( |\t)*(=|$)( |\t)*(.*)', line) def update_section_line(option, changed, section_lines, index, changed_lines, ignore_spaces, newline, msg): @@ -321,8 +321,8 @@ def do_ini(module, filename, section=None, section_has_values=None, option=None, diff = dict( before='', after='', - before_header='%s (content)' % filename, - after_header='%s (content)' % filename, + before_header=f'{filename} (content)', + after_header=f'{filename} (content)', ) if follow and os.path.islink(filename): @@ -332,7 +332,7 @@ def do_ini(module, filename, section=None, section_has_values=None, option=None, if not os.path.exists(target_filename): if not create: - module.fail_json(rc=257, msg='Destination %s does not exist!' % target_filename) + module.fail_json(rc=257, msg=f'Destination {target_filename} does not exist!') destpath = os.path.dirname(target_filename) if not os.path.exists(destpath) and not module.check_mode: os.makedirs(destpath) @@ -362,7 +362,7 @@ def do_ini(module, filename, section=None, section_has_values=None, option=None, fake_section_name = "ad01e11446efb704fcdbdb21f2c43757423d91c5" # Insert it at the beginning - ini_lines.insert(0, '[%s]' % fake_section_name) + ini_lines.insert(0, f'[{fake_section_name}]') # At bottom: ini_lines.append('[') @@ -386,7 +386,7 @@ def do_ini(module, filename, section=None, section_has_values=None, option=None, before = after = [] section_lines = [] - section_pattern = re.compile(to_text(r'^\[\s*%s\s*]' % re.escape(section.strip()))) + section_pattern = re.compile(to_text(rf'^\[\s*{re.escape(section.strip())}\s*]')) for index, line in enumerate(ini_lines): # end of section: @@ -434,7 +434,7 @@ def do_ini(module, filename, section=None, section_has_values=None, option=None, matched_value = match.group(8) if not matched_value and allow_no_value: # replace existing option with no value line(s) - newline = '%s\n' % option + newline = f'{option}\n' option_no_value_present = True else: # replace existing option=value line(s) @@ -443,7 +443,7 @@ def do_ini(module, filename, section=None, section_has_values=None, option=None, values.remove(matched_value) elif not values and allow_no_value: # replace existing option with no value line(s) - newline = '%s\n' % option + newline = f'{option}\n' (changed, msg) = update_section_line(option, changed, section_lines, index, changed_lines, ignore_spaces, newline, msg) option_no_value_present = True break @@ -482,12 +482,12 @@ def do_ini(module, filename, section=None, section_has_values=None, option=None, changed = True elif element is None and allow_no_value: # insert option with no value line - section_lines.insert(index, '%s\n' % option) + section_lines.insert(index, f'{option}\n') msg = 'option added' changed = True elif option and not values and allow_no_value and not option_no_value_present: # insert option with no value line(s) - section_lines.insert(index, '%s\n' % option) + section_lines.insert(index, f'{option}\n') msg = 'option added' changed = True break @@ -523,7 +523,7 @@ def do_ini(module, filename, section=None, section_has_values=None, option=None, del ini_lines[-1:] if not within_section and state == 'present': - ini_lines.append('[%s]\n' % section) + ini_lines.append(f'[{section}]\n') msg = 'section and option added' if section_has_values: for condition in section_has_values: @@ -532,7 +532,7 @@ def do_ini(module, filename, section=None, section_has_values=None, option=None, for value in condition['values']: ini_lines.append(assignment_format % (condition['option'], value)) elif allow_no_value: - ini_lines.append('%s\n' % condition['option']) + ini_lines.append(f"{condition['option']}\n") elif not exclusive: for value in condition['values']: if value not in values: @@ -541,7 +541,7 @@ def do_ini(module, filename, section=None, section_has_values=None, option=None, for value in values: ini_lines.append(assignment_format % (option, value)) elif option and not values and allow_no_value: - ini_lines.append('%s\n' % option) + ini_lines.append(f'{option}\n') else: msg = 'only section added' changed = True @@ -566,8 +566,7 @@ def do_ini(module, filename, section=None, section_has_values=None, option=None, try: module.atomic_move(tmpfile, os.path.abspath(target_filename)) except IOError: - module.ansible.fail_json(msg='Unable to move temporary \ - file %s to %s, IOError' % (tmpfile, target_filename), traceback=traceback.format_exc()) + module.ansible.fail_json(msg=f'Unable to move temporary file {tmpfile} to {target_filename}, IOError', traceback=traceback.format_exc()) return (changed, backup_file, diff, msg) diff --git a/plugins/modules/installp.py b/plugins/modules/installp.py index 57f70db687..27f723f4b9 100644 --- a/plugins/modules/installp.py +++ b/plugins/modules/installp.py @@ -124,7 +124,7 @@ def _check_new_pkg(module, package, repository_path): return False, None else: - module.fail_json(msg="Repository path %s is not valid." % repository_path) + module.fail_json(msg=f"Repository path {repository_path} is not valid.") def _check_installed_pkg(module, package, repository_path): @@ -139,7 +139,7 @@ def _check_installed_pkg(module, package, repository_path): """ lslpp_cmd = module.get_bin_path('lslpp', True) - rc, lslpp_result, err = module.run_command([lslpp_cmd, "-lcq", "%s*" % (package, )]) + rc, lslpp_result, err = module.run_command([lslpp_cmd, "-lcq", f"{package}*"]) if rc == 1: package_state = ' '.join(err.split()[-2:]) @@ -184,11 +184,11 @@ def remove(module, installp_cmd, packages): not_found_pkg.insert(0, "Package(s) not found: ") changed = True - msg = "Packages removed: %s. %s " % (' '.join(removed_pkgs), ' '.join(not_found_pkg)) + msg = f"Packages removed: {' '.join(removed_pkgs)}. {' '.join(not_found_pkg)} " else: changed = False - msg = ("No packages removed, all packages not found: %s" % ' '.join(not_found_pkg)) + msg = f"No packages removed, all packages not found: {' '.join(not_found_pkg)}" return changed, msg @@ -237,26 +237,26 @@ def install(module, installp_cmd, packages, repository_path, accept_license): not_found_pkgs.append(package) if len(installed_pkgs) > 0: - installed_msg = (" Installed: %s." % ' '.join(installed_pkgs)) + installed_msg = f" Installed: {' '.join(installed_pkgs)}." else: installed_msg = '' if len(not_found_pkgs) > 0: - not_found_msg = (" Not found: %s." % ' '.join(not_found_pkgs)) + not_found_msg = f" Not found: {' '.join(not_found_pkgs)}." else: not_found_msg = '' if len(already_installed_pkgs) > 0: - already_installed_msg = (" Already installed: %s." % already_installed_pkgs) + already_installed_msg = f" Already installed: {already_installed_pkgs}." else: already_installed_msg = '' if len(installed_pkgs) > 0: changed = True - msg = ("%s%s%s" % (installed_msg, not_found_msg, already_installed_msg)) + msg = f"{installed_msg}{not_found_msg}{already_installed_msg}" else: changed = False - msg = ("No packages installed.%s%s%s" % (installed_msg, not_found_msg, already_installed_msg)) + msg = f"No packages installed.{installed_msg}{not_found_msg}{already_installed_msg}" return changed, msg diff --git a/plugins/modules/interfaces_file.py b/plugins/modules/interfaces_file.py index c7038d1008..facc5b8821 100644 --- a/plugins/modules/interfaces_file.py +++ b/plugins/modules/interfaces_file.py @@ -253,7 +253,7 @@ def read_interfaces_lines(module, line_strings): elif currently_processing == "NONE": lines.append(lineDict(line)) else: - module.fail_json(msg="misplaced option %s in line %d" % (line, i)) + module.fail_json(msg=f"misplaced option {line} in line {i}") return None, None return lines, ifaces @@ -289,7 +289,7 @@ def set_interface_option(module, lines, iface, option, raw_value, state, address if len(iface_lines) < 1: # interface not found - module.fail_json(msg="Error: interface %s not found" % iface) + module.fail_json(msg=f"Error: interface {iface} not found") return changed, None iface_options = get_interface_options(iface_lines) @@ -325,7 +325,7 @@ def set_interface_option(module, lines, iface, option, raw_value, state, address for target_option in target_options: lines = [ln for ln in lines if ln != target_option] else: - module.fail_json(msg="Error: unsupported state %s, has to be either present or absent" % state) + module.fail_json(msg=f"Error: unsupported state {state}, has to be either present or absent") return changed, lines @@ -339,7 +339,7 @@ def addOptionAfterLine(option, value, iface, lines, last_line_dict, iface_option if address_family is not None and ln.get('address_family') != address_family: continue changed = True - ln['line'] = re.sub(ln.get('params', {}).get('method', '') + '$', value, ln.get('line')) + ln['line'] = re.sub(f"{ln.get('params', {}).get('method', '')}$", value, ln.get('line')) ln['params']['method'] = value return changed, lines @@ -352,7 +352,7 @@ def addOptionAfterLine(option, value, iface, lines, last_line_dict, iface_option # interface has no options, ident prefix += " " - line = prefix + "%s %s" % (option, value) + last_line[suffix_start:] + line = f"{prefix}{option} {value}{last_line[suffix_start:]}" option_dict = optionDict(line, iface, option, value, address_family) index = len(lines) - lines[::-1].index(last_line_dict) lines.insert(index, option_dict) diff --git a/plugins/modules/irc.py b/plugins/modules/irc.py index 537b26e0bc..f808007218 100644 --- a/plugins/modules/irc.py +++ b/plugins/modules/irc.py @@ -222,7 +222,7 @@ def send_msg(msg, server='localhost', port='6667', channel=None, nick_to=None, k try: colornumber = colornumbers[color] - colortext = "\x03" + colornumber + colortext = f"\x03{colornumber}" except Exception: colortext = "" @@ -241,9 +241,9 @@ def send_msg(msg, server='localhost', port='6667', channel=None, nick_to=None, k irc.connect((server, int(port))) if passwd: - irc.send(to_bytes('PASS %s\r\n' % passwd)) - irc.send(to_bytes('NICK %s\r\n' % nick)) - irc.send(to_bytes('USER %s %s %s :ansible IRC\r\n' % (nick, nick, nick))) + irc.send(to_bytes(f'PASS {passwd}\r\n')) + irc.send(to_bytes(f'NICK {nick}\r\n')) + irc.send(to_bytes(f'USER {nick} {nick} {nick} :ansible IRC\r\n')) motd = '' start = time.time() while 1: @@ -260,33 +260,33 @@ def send_msg(msg, server='localhost', port='6667', channel=None, nick_to=None, k if channel: if key: - irc.send(to_bytes('JOIN %s %s\r\n' % (channel, key))) + irc.send(to_bytes(f'JOIN {channel} {key}\r\n')) else: - irc.send(to_bytes('JOIN %s\r\n' % channel)) + irc.send(to_bytes(f'JOIN {channel}\r\n')) join = '' start = time.time() while 1: join += to_native(irc.recv(1024)) - if re.search(r'^:\S+ 366 %s %s :' % (nick, channel), join, flags=re.M | re.I): + if re.search(rf'^:\S+ 366 {nick} {channel} :', join, flags=re.M | re.I): break elif time.time() - start > timeout: raise Exception('Timeout waiting for IRC JOIN response') time.sleep(0.5) if topic is not None: - irc.send(to_bytes('TOPIC %s :%s\r\n' % (channel, topic))) + irc.send(to_bytes(f'TOPIC {channel} :{topic}\r\n')) time.sleep(1) if nick_to: for nick in nick_to: - irc.send(to_bytes('PRIVMSG %s :%s\r\n' % (nick, message))) + irc.send(to_bytes(f'PRIVMSG {nick} :{message}\r\n')) if channel: - irc.send(to_bytes('PRIVMSG %s :%s\r\n' % (channel, message))) + irc.send(to_bytes(f'PRIVMSG {channel} :{message}\r\n')) time.sleep(1) if part: if channel: - irc.send(to_bytes('PART %s\r\n' % channel)) + irc.send(to_bytes(f'PART {channel}\r\n')) irc.send(to_bytes('QUIT\r\n')) time.sleep(1) irc.close() @@ -345,7 +345,7 @@ def main(): try: send_msg(msg, server, port, channel, nick_to, key, topic, nick, color, passwd, timeout, use_tls, validate_certs, part, style) except Exception as e: - module.fail_json(msg="unable to send to IRC: %s" % to_native(e), exception=traceback.format_exc()) + module.fail_json(msg=f"unable to send to IRC: {e}", exception=traceback.format_exc()) module.exit_json(changed=False, channel=channel, nick=nick, msg=msg) diff --git a/plugins/modules/iso_create.py b/plugins/modules/iso_create.py index 8d11bb2248..0d1a847686 100644 --- a/plugins/modules/iso_create.py +++ b/plugins/modules/iso_create.py @@ -159,7 +159,6 @@ except ImportError: HAS_PYCDLIB = False from ansible.module_utils.basic import AnsibleModule, missing_required_lib -from ansible.module_utils.common.text.converters import to_native def add_file(module, iso_file=None, src_file=None, file_path=None, rock_ridge=None, use_joliet=None, use_udf=None): @@ -170,9 +169,9 @@ def add_file(module, iso_file=None, src_file=None, file_path=None, rock_ridge=No # followed by a maximum 3 character extension, followed by a semicolon and a version file_name = os.path.basename(file_path) if '.' not in file_name: - file_in_iso_path = file_path.upper() + '.;1' + file_in_iso_path = f"{file_path.upper()}.;1" else: - file_in_iso_path = file_path.upper() + ';1' + file_in_iso_path = f"{file_path.upper()};1" if rock_ridge: rr_name = file_name if use_joliet: @@ -182,7 +181,7 @@ def add_file(module, iso_file=None, src_file=None, file_path=None, rock_ridge=No try: iso_file.add_file(src_file, iso_path=file_in_iso_path, rr_name=rr_name, joliet_path=joliet_path, udf_path=udf_path) except Exception as err: - module.fail_json(msg="Failed to add file %s to ISO file due to %s" % (src_file, to_native(err))) + module.fail_json(msg=f"Failed to add file {src_file} to ISO file due to {err}") def add_directory(module, iso_file=None, dir_path=None, rock_ridge=None, use_joliet=None, use_udf=None): @@ -199,7 +198,7 @@ def add_directory(module, iso_file=None, dir_path=None, rock_ridge=None, use_jol try: iso_file.add_directory(iso_path=iso_dir_path, rr_name=rr_name, joliet_path=joliet_path, udf_path=udf_path) except Exception as err: - module.fail_json(msg="Failed to directory %s to ISO file due to %s" % (dir_path, to_native(err))) + module.fail_json(msg=f"Failed to directory {dir_path} to ISO file due to {err}") def main(): @@ -224,7 +223,7 @@ def main(): module.fail_json(msg='Please specify source file and/or directory list using src_files parameter.') for src_file in src_file_list: if not os.path.exists(src_file): - module.fail_json(msg="Specified source file/directory path does not exist on local machine, %s" % src_file) + module.fail_json(msg=f"Specified source file/directory path does not exist on local machine, {src_file}") dest_iso = module.params.get('dest_iso') if dest_iso and len(dest_iso) == 0: @@ -236,7 +235,7 @@ def main(): try: os.makedirs(dest_iso_dir) except OSError as err: - module.fail_json(msg='Exception caught when creating folder %s, with error %s' % (dest_iso_dir, to_native(err))) + module.fail_json(msg=f'Exception caught when creating folder {dest_iso_dir}, with error {err}') volume_id = module.params.get('vol_ident') if volume_id is None: @@ -269,7 +268,7 @@ def main(): file_list = [] src_file = src_file.rstrip('/') dir_name = os.path.basename(src_file) - add_directory(module, iso_file=iso_file, dir_path='/' + dir_name, rock_ridge=rock_ridge, + add_directory(module, iso_file=iso_file, dir_path=f"/{dir_name}", rock_ridge=rock_ridge, use_joliet=use_joliet, use_udf=use_udf) # get dir list and file list @@ -287,7 +286,7 @@ def main(): use_joliet=use_joliet, use_udf=use_udf) # if specify a file then add this file directly to the '/' path in ISO else: - add_file(module, iso_file=iso_file, src_file=src_file, file_path='/' + os.path.basename(src_file), + add_file(module, iso_file=iso_file, src_file=src_file, file_path=f"/{os.path.basename(src_file)}", rock_ridge=rock_ridge, use_joliet=use_joliet, use_udf=use_udf) iso_file.write(dest_iso) diff --git a/plugins/modules/iso_customize.py b/plugins/modules/iso_customize.py index 7e64f949bd..169e301dee 100644 --- a/plugins/modules/iso_customize.py +++ b/plugins/modules/iso_customize.py @@ -123,9 +123,9 @@ def iso_add_dir(module, opened_iso, iso_type, dir_path): return if parent_dir == "/": - current_dirpath = "/%s" % check_dirname + current_dirpath = f"/{check_dirname}" else: - current_dirpath = "%s/%s" % (parent_dir, check_dirname) + current_dirpath = f"{parent_dir}/{check_dirname}" current_dirpath_upper = current_dirpath.upper() try: @@ -138,7 +138,7 @@ def iso_add_dir(module, opened_iso, iso_type, dir_path): elif iso_type == "udf": opened_iso.add_directory(current_dirpath_upper, udf_path=current_dirpath) except Exception as err: - msg = "Failed to create dir %s with error: %s" % (current_dirpath, to_native(err)) + msg = f"Failed to create dir {current_dirpath} with error: {err}" module.fail_json(msg=msg) @@ -150,9 +150,9 @@ def iso_add_dirs(module, opened_iso, iso_type, dir_path): if not item.strip(): continue if current_dirpath == "/": - current_dirpath = "/%s" % item + current_dirpath = f"/{item}" else: - current_dirpath = "%s/%s" % (current_dirpath, item) + current_dirpath = f"{current_dirpath}/{item}" iso_add_dir(module, opened_iso, iso_type, current_dirpath) @@ -175,14 +175,14 @@ def iso_check_file_exists(opened_iso, dest_file): return False if parent_dir == "/": - parent_dir = "/%s" % item + parent_dir = f"/{item}" else: - parent_dir = "%s/%s" % (parent_dir, item) + parent_dir = f"{parent_dir}/{item}" if '.' not in file_name: - file_in_iso_path = file_name.upper() + '.;1' + file_in_iso_path = f"{file_name.upper()}.;1" else: - file_in_iso_path = file_name.upper() + ';1' + file_in_iso_path = f"{file_name.upper()};1" for dirname, dummy_dirlist, filelist in opened_iso.walk(iso_path=parent_dir.upper()): if dirname != parent_dir.upper(): @@ -194,16 +194,16 @@ def iso_check_file_exists(opened_iso, dest_file): def iso_add_file(module, opened_iso, iso_type, src_file, dest_file): dest_file = dest_file.strip() if dest_file[0] != "/": - dest_file = "/%s" % dest_file + dest_file = f"/{dest_file}" file_local = src_file.strip() file_dir = os.path.dirname(dest_file).strip() file_name = os.path.basename(dest_file) if '.' not in file_name: - file_in_iso_path = dest_file.upper() + '.;1' + file_in_iso_path = f"{dest_file.upper()}.;1" else: - file_in_iso_path = dest_file.upper() + ';1' + file_in_iso_path = f"{dest_file.upper()};1" if file_dir and file_dir != "/": iso_add_dirs(module, opened_iso, iso_type, file_dir) @@ -226,23 +226,23 @@ def iso_add_file(module, opened_iso, iso_type, src_file, dest_file): opened_iso.rm_file(udf_path=dest_file) opened_iso.add_file(file_local, iso_path=file_in_iso_path, udf_path=dest_file) except Exception as err: - msg = "Failed to add local file %s to ISO with error: %s" % (file_local, to_native(err)) + msg = f"Failed to add local file {file_local} to ISO with error: {err}" module.fail_json(msg=msg) def iso_delete_file(module, opened_iso, iso_type, dest_file): dest_file = dest_file.strip() if dest_file[0] != "/": - dest_file = "/%s" % dest_file + dest_file = f"/{dest_file}" file_name = os.path.basename(dest_file) if not iso_check_file_exists(opened_iso, dest_file): - module.fail_json(msg="The file %s does not exist." % dest_file) + module.fail_json(msg=f"The file {dest_file} does not exist.") if '.' not in file_name: - file_in_iso_path = dest_file.upper() + '.;1' + file_in_iso_path = f"{dest_file.upper()}.;1" else: - file_in_iso_path = dest_file.upper() + ';1' + file_in_iso_path = f"{dest_file.upper()};1" try: if iso_type == "iso9660": @@ -254,7 +254,7 @@ def iso_delete_file(module, opened_iso, iso_type, dest_file): elif iso_type == "udf": opened_iso.rm_file(udf_path=dest_file) except Exception as err: - msg = "Failed to delete iso file %s with error: %s" % (dest_file, to_native(err)) + msg = f"Failed to delete iso file {dest_file} with error: {err}" module.fail_json(msg=msg) @@ -280,7 +280,7 @@ def iso_rebuild(module, src_iso, dest_iso, delete_files_list, add_files_list): iso.write(dest_iso) except Exception as err: - msg = "Failed to rebuild ISO %s with error: %s" % (src_iso, to_native(err)) + msg = f"Failed to rebuild ISO {src_iso} with error: {to_native(err)}" module.fail_json(msg=msg) finally: if iso: @@ -309,19 +309,19 @@ def main(): src_iso = module.params['src_iso'] if not os.path.exists(src_iso): - module.fail_json(msg="ISO file %s does not exist." % src_iso) + module.fail_json(msg=f"ISO file {src_iso} does not exist.") dest_iso = module.params['dest_iso'] dest_iso_dir = os.path.dirname(dest_iso) if dest_iso_dir and not os.path.exists(dest_iso_dir): - module.fail_json(msg="The dest directory %s does not exist" % dest_iso_dir) + module.fail_json(msg=f"The dest directory {dest_iso_dir} does not exist") delete_files_list = [s.strip() for s in module.params['delete_files']] add_files_list = module.params['add_files'] if add_files_list: for item in add_files_list: if not os.path.exists(item['src_file']): - module.fail_json(msg="The file %s does not exist." % item['src_file']) + module.fail_json(msg=f"The file {item['src_file']} does not exist.") result = dict( src_iso=src_iso, diff --git a/plugins/modules/iso_extract.py b/plugins/modules/iso_extract.py index 11897744a8..347775c4c6 100644 --- a/plugins/modules/iso_extract.py +++ b/plugins/modules/iso_extract.py @@ -129,13 +129,13 @@ def main(): # When executable was provided and binary not found, warn user ! if module.params['executable'] is not None and not binary: - module.warn("Executable '%s' is not found on the system, trying to mount ISO instead." % executable) + module.warn(f"Executable '{executable}' is not found on the system, trying to mount ISO instead.") if not os.path.exists(dest): - module.fail_json(msg="Directory '%s' does not exist" % dest) + module.fail_json(msg=f"Directory '{dest}' does not exist") if not os.path.exists(os.path.dirname(image)): - module.fail_json(msg="ISO image '%s' does not exist" % image) + module.fail_json(msg=f"ISO image '{image}' does not exist") result['files'] = [] extract_files = list(files) @@ -159,9 +159,9 @@ def main(): # Use 7zip when we have a binary, otherwise try to mount if binary: - cmd = [binary, 'x', image, '-o%s' % tmp_dir] + cmd = [binary, 'x', image, f'-o{tmp_dir}'] if password: - cmd += ["-p%s" % password] + cmd += [f"-p{password}"] cmd += extract_files else: cmd = [module.get_bin_path('mount'), '-o', 'loop,ro', image, tmp_dir] @@ -177,15 +177,15 @@ def main(): shutil.rmtree(tmp_dir) if binary: - module.fail_json(msg="Failed to extract from ISO image '%s' to '%s'" % (image, tmp_dir), **result) + module.fail_json(msg=f"Failed to extract from ISO image '{image}' to '{tmp_dir}'", **result) else: - module.fail_json(msg="Failed to mount ISO image '%s' to '%s', and we could not find executable '%s'." % (image, tmp_dir, executable), **result) + module.fail_json(msg=f"Failed to mount ISO image '{image}' to '{tmp_dir}', and we could not find executable '{executable}'.", **result) try: for f in extract_files: tmp_src = os.path.join(tmp_dir, f) if not os.path.exists(tmp_src): - module.fail_json(msg="Failed to extract '%s' from ISO image" % f, **result) + module.fail_json(msg=f"Failed to extract '{f}' from ISO image", **result) src_checksum = module.sha1(tmp_src)