diff --git a/changelogs/fragments/10947-mod-fstr-def.yml b/changelogs/fragments/10947-mod-fstr-def.yml new file mode 100644 index 0000000000..666ad442bd --- /dev/null +++ b/changelogs/fragments/10947-mod-fstr-def.yml @@ -0,0 +1,23 @@ +minor_changes: + - datadog_downtime - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - datadog_monitor - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - dconf - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - decompress - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - deploy_helper - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - discord - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - django_manage - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - dnf_config_manager - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - dnf_versionlock - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - dnsimple - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - dnsimple_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - dnsmadeeasy - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - dpkg_divert - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - easy_install - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - ejabberd_user - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - elasticsearch_plugin - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - emc_vnx_sg_member - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - etcd3 - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - filesize - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - filesystem - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - flatpak - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). + - flatpak_remote - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10947). diff --git a/plugins/modules/datadog_downtime.py b/plugins/modules/datadog_downtime.py index 82365ff06a..d7264dce08 100644 --- a/plugins/modules/datadog_downtime.py +++ b/plugins/modules/datadog_downtime.py @@ -200,16 +200,14 @@ def main(): } ) with ApiClient(configuration) as api_client: - api_client.user_agent = "ansible_collection/community_general (module_name datadog_downtime) {0}".format( - api_client.user_agent - ) + api_client.user_agent = f"ansible_collection/community_general (module_name datadog_downtime) {api_client.user_agent}" api_instance = DowntimesApi(api_client) # Validate api and app keys try: api_instance.list_downtimes(current_only=True) except ApiException as e: - module.fail_json(msg="Failed to connect Datadog server using given app_key and api_key: {0}".format(e)) + module.fail_json(msg=f"Failed to connect Datadog server using given app_key and api_key: {e}") if module.params["state"] == "present": schedule_downtime(module, api_client) @@ -224,7 +222,7 @@ def _get_downtime(module, api_client): try: downtime = api.get_downtime(module.params["id"]) except ApiException as e: - module.fail_json(msg="Failed to retrieve downtime with id {0}: {1}".format(module.params["id"], e)) + module.fail_json(msg=f"Failed to retrieve downtime with id {module.params['id']}: {e}") return downtime @@ -260,7 +258,7 @@ def _post_downtime(module, api_client): module.params["id"] = resp.id module.exit_json(changed=True, downtime=resp.to_dict()) except ApiException as e: - module.fail_json(msg="Failed to create downtime: {0}".format(e)) + module.fail_json(msg=f"Failed to create downtime: {e}") def _equal_dicts(a, b, ignore_keys): @@ -286,7 +284,7 @@ def _update_downtime(module, current_downtime, api_client): else: module.exit_json(changed=True, downtime=resp.to_dict()) except ApiException as e: - module.fail_json(msg="Failed to update downtime: {0}".format(e)) + module.fail_json(msg=f"Failed to update downtime: {e}") def schedule_downtime(module, api_client): @@ -305,7 +303,7 @@ def cancel_downtime(module, api_client): try: api.cancel_downtime(downtime["id"]) except ApiException as e: - module.fail_json(msg="Failed to create downtime: {0}".format(e)) + module.fail_json(msg=f"Failed to create downtime: {e}") module.exit_json(changed=True) diff --git a/plugins/modules/datadog_monitor.py b/plugins/modules/datadog_monitor.py index 2b84d7dbd8..e9fe852d56 100644 --- a/plugins/modules/datadog_monitor.py +++ b/plugins/modules/datadog_monitor.py @@ -306,7 +306,7 @@ def main(): if isinstance(response, dict): msg = response.get('errors', None) if msg: - module.fail_json(msg="Failed to connect Datadog server using given app_key and api_key : {0}".format(msg[0])) + module.fail_json(msg=f"Failed to connect Datadog server using given app_key and api_key : {msg[0]}") if module.params['state'] == 'present': install_monitor(module) @@ -328,7 +328,7 @@ def _get_monitor(module): if module.params['id'] is not None: monitor = api.Monitor.get(module.params['id']) if 'errors' in monitor: - module.fail_json(msg="Failed to retrieve monitor with id %s, errors are %s" % (module.params['id'], str(monitor['errors']))) + module.fail_json(msg=f"Failed to retrieve monitor with id {module.params['id']}, errors are {monitor['errors']}") return monitor else: monitors = api.Monitor.get_all() @@ -430,7 +430,7 @@ def delete_monitor(module): def mute_monitor(module): monitor = _get_monitor(module) if not monitor: - module.fail_json(msg="Monitor %s not found!" % module.params['name']) + module.fail_json(msg=f"Monitor {module.params['name']} not found!") elif monitor['options']['silenced']: module.fail_json(msg="Monitor is already muted. Datadog does not allow to modify muted alerts, consider unmuting it first.") elif module.params['silenced'] is not None and len(set(monitor['options']['silenced']) ^ set(module.params['silenced'])) == 0: @@ -448,7 +448,7 @@ def mute_monitor(module): def unmute_monitor(module): monitor = _get_monitor(module) if not monitor: - module.fail_json(msg="Monitor %s not found!" % module.params['name']) + module.fail_json(msg=f"Monitor {module.params['name']} not found!") elif not monitor['options']['silenced']: module.exit_json(changed=False) try: diff --git a/plugins/modules/dconf.py b/plugins/modules/dconf.py index e9e9d82514..e456288ae5 100644 --- a/plugins/modules/dconf.py +++ b/plugins/modules/dconf.py @@ -193,7 +193,7 @@ class DBusWrapper(object): # Go through all the pids for this user, try to extract the D-Bus # session bus address from environment, and ensure it is possible to # connect to it. - self.module.debug("Trying to detect existing D-Bus user session for user: %d" % uid) + self.module.debug(f"Trying to detect existing D-Bus user session for user: {int(uid)}") for pid in psutil.pids(): try: @@ -201,13 +201,13 @@ class DBusWrapper(object): process_real_uid, dummy, dummy = process.uids() if process_real_uid == uid and 'DBUS_SESSION_BUS_ADDRESS' in process.environ(): dbus_session_bus_address_candidate = process.environ()['DBUS_SESSION_BUS_ADDRESS'] - self.module.debug("Found D-Bus user session candidate at address: %s" % dbus_session_bus_address_candidate) + self.module.debug(f"Found D-Bus user session candidate at address: {dbus_session_bus_address_candidate}") dbus_send_cmd = self.module.get_bin_path('dbus-send', required=True) - command = [dbus_send_cmd, '--address=%s' % dbus_session_bus_address_candidate, '--type=signal', '/', 'com.example.test'] + command = [dbus_send_cmd, f'--address={dbus_session_bus_address_candidate}', '--type=signal', '/', 'com.example.test'] rc, dummy, dummy = self.module.run_command(command) if rc == 0: - self.module.debug("Verified D-Bus user session candidate as usable at address: %s" % dbus_session_bus_address_candidate) + self.module.debug(f"Verified D-Bus user session candidate as usable at address: {dbus_session_bus_address_candidate}") return dbus_session_bus_address_candidate @@ -240,7 +240,7 @@ class DBusWrapper(object): rc, out, err = self.module.run_command(command) if self.dbus_session_bus_address is None and rc == 127: - self.module.fail_json(msg="Failed to run passed-in command, dbus-run-session faced an internal error: %s" % err) + self.module.fail_json(msg=f"Failed to run passed-in command, dbus-run-session faced an internal error: {err}") else: extra_environment = {'DBUS_SESSION_BUS_ADDRESS': self.dbus_session_bus_address} rc, out, err = self.module.run_command(command, environ_update=extra_environment) @@ -302,7 +302,7 @@ class DconfPreference(object): rc, out, err = self.module.run_command(command) if rc != 0: - self.module.fail_json(msg='dconf failed while reading the value with error: %s' % err, + self.module.fail_json(msg=f'dconf failed while reading the value with error: {err}', out=out, err=err) @@ -343,7 +343,7 @@ class DconfPreference(object): rc, out, err = dbus_wrapper.run_command(command) if rc != 0: - self.module.fail_json(msg='dconf failed while writing key %s, value %s with error: %s' % (key, value, err), + self.module.fail_json(msg=f'dconf failed while writing key {key}, value {value} with error: {err}', out=out, err=err) @@ -381,7 +381,7 @@ class DconfPreference(object): rc, out, err = dbus_wrapper.run_command(command) if rc != 0: - self.module.fail_json(msg='dconf failed while resetting the value with error: %s' % err, + self.module.fail_json(msg=f'dconf failed while resetting the value with error: {err}', out=out, err=err) @@ -416,8 +416,7 @@ def main(): if has_respawned(): # This shouldn't be possible; short-circuit early if it happens. module.fail_json( - msg="%s must be installed and visible from %s." % - (glib_module_name, sys.executable)) + msg=f"{glib_module_name} must be installed and visible from {sys.executable}.") interpreters = ['/usr/bin/python3', '/usr/bin/python'] diff --git a/plugins/modules/decompress.py b/plugins/modules/decompress.py index 3746810ca9..2321497a7b 100644 --- a/plugins/modules/decompress.py +++ b/plugins/modules/decompress.py @@ -94,7 +94,7 @@ import shutil import tempfile from ansible_collections.community.general.plugins.module_utils.mh.module_helper import ModuleHelper -from ansible.module_utils.common.text.converters import to_native, to_bytes +from ansible.module_utils.common.text.converters import to_bytes from ansible_collections.community.general.plugins.module_utils import deps with deps.declare("lzma"): @@ -148,11 +148,11 @@ class Decompress(ModuleHelper): if self.vars.remove and os.path.exists(b_dest): self.module.exit_json(changed=False) else: - self.do_raise(msg="Path does not exist: '%s'" % b_src) + self.do_raise(msg=f"Path does not exist: '{b_src}'") if os.path.isdir(b_src): - self.do_raise(msg="Cannot decompress directory '%s'" % b_src) + self.do_raise(msg=f"Cannot decompress directory '{b_src}'") if os.path.isdir(b_dest): - self.do_raise(msg="Destination is a directory, cannot decompress: '%s'" % b_dest) + self.do_raise(msg=f"Destination is a directory, cannot decompress: '{b_dest}'") def __run__(self): b_dest = to_bytes(self.vars.dest, errors='surrogate_or_strict') @@ -166,7 +166,7 @@ class Decompress(ModuleHelper): b_temppath = to_bytes(temppath, errors='surrogate_or_strict') decompress(b_src, b_temppath, handler) except OSError as e: - self.do_raise(msg="Unable to create temporary file '%s'" % to_native(e)) + self.do_raise(msg=f"Unable to create temporary file '{e}'") if os.path.exists(b_dest): self.changed = not filecmp.cmp(b_temppath, b_dest, shallow=False) @@ -177,7 +177,7 @@ class Decompress(ModuleHelper): try: self.module.atomic_move(b_temppath, b_dest) except OSError: - self.do_raise(msg="Unable to move temporary file '%s' to '%s'" % (b_temppath, self.vars.dest)) + self.do_raise(msg=f"Unable to move temporary file '{b_temppath}' to '{self.vars.dest}'") if self.vars.remove and not self.check_mode: os.remove(b_src) @@ -185,7 +185,7 @@ class Decompress(ModuleHelper): def get_destination_filename(self): src = self.vars.src - fmt_extension = ".%s" % self.vars.format + fmt_extension = f".{self.vars.format}" if src.endswith(fmt_extension) and len(src) > len(fmt_extension): filename = src[:-len(fmt_extension)] else: diff --git a/plugins/modules/deploy_helper.py b/plugins/modules/deploy_helper.py index d9380d36f4..f99f514e6e 100644 --- a/plugins/modules/deploy_helper.py +++ b/plugins/modules/deploy_helper.py @@ -269,7 +269,6 @@ import time import traceback from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.common.text.converters import to_native class DeployHelper(object): @@ -323,13 +322,13 @@ class DeployHelper(object): return False if not os.path.isdir(path): - self.module.fail_json(msg="%s exists but is not a directory" % path) + self.module.fail_json(msg=f"{path} exists but is not a directory") if not self.module.check_mode: try: shutil.rmtree(path, ignore_errors=False) except Exception as e: - self.module.fail_json(msg="rmtree failed: %s" % to_native(e), exception=traceback.format_exc()) + self.module.fail_json(msg=f"rmtree failed: {e}", exception=traceback.format_exc()) return True @@ -342,7 +341,7 @@ class DeployHelper(object): os.makedirs(path) elif not os.path.isdir(path): - self.module.fail_json(msg="%s exists but is not a directory" % path) + self.module.fail_json(msg=f"{path} exists but is not a directory") changed += self.module.set_directory_attributes_if_different(self._get_file_args(path), changed) @@ -351,7 +350,7 @@ class DeployHelper(object): def check_link(self, path): if os.path.lexists(path): if not os.path.islink(path): - self.module.fail_json(msg="%s exists but is not a symbolic link" % path) + self.module.fail_json(msg=f"{path} exists but is not a symbolic link") def create_link(self, source, link_name): if os.path.islink(link_name): @@ -363,8 +362,8 @@ class DeployHelper(object): changed = True if not self.module.check_mode: if not os.path.lexists(source): - self.module.fail_json(msg="the symlink target %s doesn't exists" % source) - tmp_link_name = link_name + '.' + self.unfinished_filename + self.module.fail_json(msg=f"the symlink target {source} doesn't exists") + tmp_link_name = f"{link_name}.{self.unfinished_filename}" if os.path.islink(tmp_link_name): os.unlink(tmp_link_name) os.symlink(source, tmp_link_name) @@ -404,7 +403,7 @@ class DeployHelper(object): if not self.release: return changed - tmp_link_name = os.path.join(path, self.release + '.' + self.unfinished_filename) + tmp_link_name = os.path.join(path, f"{self.release}.{self.unfinished_filename}") if not self.module.check_mode and os.path.exists(tmp_link_name): changed = True os.remove(tmp_link_name) diff --git a/plugins/modules/discord.py b/plugins/modules/discord.py index 9cb732eb02..d694ee64bf 100644 --- a/plugins/modules/discord.py +++ b/plugins/modules/discord.py @@ -138,8 +138,7 @@ def discord_check_mode(module): 'content-type': 'application/json' } - url = "https://discord.com/api/webhooks/%s/%s" % ( - webhook_id, webhook_token) + url = f"https://discord.com/api/webhooks/{webhook_id}/{webhook_token}" response, info = fetch_url(module, url, method='GET', headers=headers) return response, info @@ -159,8 +158,7 @@ def discord_text_msg(module): 'content-type': 'application/json' } - url = "https://discord.com/api/webhooks/%s/%s" % ( - webhook_id, webhook_token) + url = f"https://discord.com/api/webhooks/{webhook_id}/{webhook_token}" payload = { 'content': content, diff --git a/plugins/modules/django_manage.py b/plugins/modules/django_manage.py index ddda99849e..257808df2c 100644 --- a/plugins/modules/django_manage.py +++ b/plugins/modules/django_manage.py @@ -191,9 +191,9 @@ from ansible.module_utils.basic import AnsibleModule def _fail(module, cmd, out, err, **kwargs): msg = '' if out: - msg += "stdout: %s" % (out, ) + msg += f"stdout: {out}" if err: - msg += "\n:stderr: %s" % (err, ) + msg += f"\n:stderr: {err}" module.fail_json(cmd=cmd, msg=msg, **kwargs) @@ -207,9 +207,9 @@ def _ensure_virtualenv(module): activate = os.path.join(vbin, 'activate') if not os.path.exists(activate): - module.fail_json(msg='%s does not point to a valid virtual environment' % venv_param) + module.fail_json(msg=f'{venv_param} does not point to a valid virtual environment') - os.environ["PATH"] = "%s:%s" % (vbin, os.environ["PATH"]) + os.environ["PATH"] = f"{vbin}:{os.environ['PATH']}" os.environ["VIRTUAL_ENV"] = venv_param @@ -294,11 +294,11 @@ def main(): for param in specific_params: value = module.params[param] if value and param not in command_allowed_param_map[command_bin]: - module.fail_json(msg='%s param is incompatible with command=%s' % (param, command_bin)) + module.fail_json(msg=f'{param} param is incompatible with command={command_bin}') for param in command_required_param_map.get(command_bin, ()): if not module.params[param]: - module.fail_json(msg='%s param is required for command=%s' % (param, command_bin)) + module.fail_json(msg=f'{param} param is required for command={command_bin}') _ensure_virtualenv(module) @@ -309,11 +309,11 @@ def main(): for param in general_params: if module.params[param]: - run_cmd_args.append('--%s=%s' % (param, module.params[param])) + run_cmd_args.append(f'--{param}={module.params[param]}') for param in specific_boolean_params: if module.params[param]: - run_cmd_args.append('--%s' % param) + run_cmd_args.append(f'--{param}') # these params always get tacked on the end of the command for param in end_of_command_params: @@ -329,18 +329,18 @@ def main(): out = 'already exists.' else: if "Unknown command:" in err: - _fail(module, run_cmd_args, err, "Unknown django command: %s" % command_bin) + _fail(module, run_cmd_args, err, f"Unknown django command: {command_bin}") _fail(module, run_cmd_args, out, err, path=os.environ["PATH"], syspath=sys.path) changed = False lines = out.split('\n') - filt = globals().get(command_bin + "_filter_output", None) + filt = globals().get(f"{command_bin}_filter_output", None) if filt: filtered_output = list(filter(filt, lines)) if len(filtered_output): changed = True - check_changed = globals().get("{0}_check_changed".format(command_bin), None) + check_changed = globals().get(f"{command_bin}_check_changed", None) if check_changed: changed = check_changed(out) diff --git a/plugins/modules/dnf_config_manager.py b/plugins/modules/dnf_config_manager.py index 847e912115..69a985b828 100644 --- a/plugins/modules/dnf_config_manager.py +++ b/plugins/modules/dnf_config_manager.py @@ -152,7 +152,7 @@ def get_repo_states(module): def set_repo_states(module, repo_ids, state): - module.run_command([DNF_BIN, 'config-manager', '--assumeyes', '--set-{0}'.format(state)] + repo_ids, check_rc=True) + module.run_command([DNF_BIN, 'config-manager', '--assumeyes', f'--set-{state}'] + repo_ids, check_rc=True) def pack_repo_states_for_return(states): @@ -188,7 +188,7 @@ def main(): module.run_command_environ_update = dict(LANGUAGE='C', LC_ALL='C') if not os.path.exists(DNF_BIN): - module.fail_json(msg="%s was not found" % DNF_BIN) + module.fail_json(msg=f"{DNF_BIN} was not found") repo_states = get_repo_states(module) result['repo_states_pre'] = pack_repo_states_for_return(repo_states) @@ -199,7 +199,7 @@ def main(): to_change = [] for repo_id in names: if repo_id not in repo_states: - module.fail_json(msg="did not find repo with ID '{0}' in dnf repolist --all --verbose".format(repo_id)) + module.fail_json(msg=f"did not find repo with ID '{repo_id}' in dnf repolist --all --verbose") if repo_states[repo_id] != desired_repo_state: to_change.append(repo_id) result['changed'] = len(to_change) > 0 @@ -216,7 +216,7 @@ def main(): for repo_id in to_change: if repo_states_post[repo_id] != desired_repo_state: - module.fail_json(msg="dnf config-manager failed to make '{0}' {1}".format(repo_id, desired_repo_state)) + module.fail_json(msg=f"dnf config-manager failed to make '{repo_id}' {desired_repo_state}") module.exit_json(**result) diff --git a/plugins/modules/dnf_versionlock.py b/plugins/modules/dnf_versionlock.py index e6fa546107..b54062f1ea 100644 --- a/plugins/modules/dnf_versionlock.py +++ b/plugins/modules/dnf_versionlock.py @@ -179,17 +179,15 @@ def match(entry, pattern): return False # indexing a match object with [] is a Python 3.6+ construct for name in ( - '%s' % m["name"], - '%s.%s' % (m["name"], m["arch"]), - '%s-%s' % (m["name"], m["version"]), - '%s-%s-%s' % (m["name"], m["version"], m["release"]), - '%s-%s:%s' % (m["name"], m["epoch"], m["version"]), - '%s-%s-%s.%s' % (m["name"], m["version"], m["release"], m["arch"]), - '%s-%s:%s-%s' % (m["name"], m["epoch"], m["version"], m["release"]), - '%s:%s-%s-%s.%s' % (m["epoch"], m["name"], m["version"], m["release"], - m["arch"]), - '%s-%s:%s-%s.%s' % (m["name"], m["epoch"], m["version"], m["release"], - m["arch"]) + f"{m['name']}", + f"{m['name']}.{m['arch']}", + f"{m['name']}-{m['version']}", + f"{m['name']}-{m['version']}-{m['release']}", + f"{m['name']}-{m['epoch']}:{m['version']}", + f"{m['name']}-{m['version']}-{m['release']}.{m['arch']}", + f"{m['name']}-{m['epoch']}:{m['version']}-{m['release']}", + f"{m['epoch']}:{m['name']}-{m['version']}-{m['release']}.{m['arch']}", + f"{m['name']}-{m['epoch']}:{m['version']}-{m['release']}.{m['arch']}" ): if fnmatch.fnmatch(name, pattern): return True @@ -209,12 +207,10 @@ def get_packages(module, patterns, only_installed=False): m = NEVRA_RE.match(p) if not m: module.fail_json( - msg="failed to parse nevra for %s" % p, + msg=f"failed to parse nevra for {p}", rc=rc, out=out, err=err) - evr = "%s:%s-%s" % (m["epoch"], - m["version"], - m["release"]) + evr = f"{m['epoch']}:{m['version']}-{m['release']}" packages_available_map_name_evrs.setdefault(m["name"], set()) packages_available_map_name_evrs[m["name"]].add(evr) @@ -245,7 +241,7 @@ def get_package_list(module, package_mgr="dnf"): dummy, name = line.split(":", 1) name = name.strip() pkg_name = get_packages(module, patterns=[name]) - package_name = "%s-%s.*" % (name, pkg_name[name].pop()) + package_name = f"{name}-{pkg_name[name].pop()}.*" if package_name and package_name not in package_list: package_list.append(package_name) if line.startswith("evr"): @@ -286,7 +282,7 @@ def main(): if state == "clean" and patterns: module.fail_json(msg="clean state is incompatible with a name list") if state != "clean" and not patterns: - module.fail_json(msg="name list is required for %s state" % state) + module.fail_json(msg=f"name list is required for {state} state") locklist_pre = get_package_list(module, package_mgr=package_mgr) @@ -298,7 +294,7 @@ def main(): if raw: # Add raw patterns as specs to add. for p in patterns: - if (p if state == "present" else "!" + p) not in locklist_pre: + if (p if state == "present" else f"!{p}") not in locklist_pre: specs_toadd.append(p) else: # Get available packages that match the patterns. @@ -320,9 +316,9 @@ def main(): packages_map_name_evrs.update(packages_installed_map_name_evrs) for name in packages_map_name_evrs: for evr in packages_map_name_evrs[name]: - locklist_entry = "%s-%s.*" % (name, evr) + locklist_entry = f"{name}-{evr}.*" - if (locklist_entry if state == "present" else "!%s" % locklist_entry) not in locklist_pre: + if (locklist_entry if state == "present" else f"!{locklist_entry}") not in locklist_pre: specs_toadd.append(locklist_entry) if specs_toadd and not module.check_mode: diff --git a/plugins/modules/dnsimple.py b/plugins/modules/dnsimple.py index 1e9fc8f317..8d0305c18b 100644 --- a/plugins/modules/dnsimple.py +++ b/plugins/modules/dnsimple.py @@ -421,7 +421,7 @@ def main(): if state == 'present': difference = list(set(wanted_record_ids) - set(current_record_ids)) if difference: - module.fail_json(msg="Missing the following records: %s" % difference) + module.fail_json(msg=f"Missing the following records: {difference}") else: module.exit_json(changed=False) # state is absent @@ -437,9 +437,9 @@ def main(): except DNSimpleException as e: if DNSIMPLE_MAJOR_VERSION > 1: - module.fail_json(msg="DNSimple exception: %s" % e.message) + module.fail_json(msg=f"DNSimple exception: {e.message}") else: - module.fail_json(msg="DNSimple exception: %s" % str(e.args[0]['message'])) + module.fail_json(msg=f"DNSimple exception: {e.args[0]['message']}") module.fail_json(msg="Unknown what you wanted me to do") diff --git a/plugins/modules/dnsimple_info.py b/plugins/modules/dnsimple_info.py index 64cc4527a6..cdec8e4dda 100644 --- a/plugins/modules/dnsimple_info.py +++ b/plugins/modules/dnsimple_info.py @@ -236,9 +236,9 @@ with deps.declare("requests"): def build_url(account, key, is_sandbox): headers = {'Accept': 'application/json', - 'Authorization': 'Bearer {0}'.format(key)} + 'Authorization': f'Bearer {key}'} sandbox = '.sandbox' if is_sandbox else '' - url = 'https://api{sandbox}.dnsimple.com/v2/{account}'.format(sandbox=sandbox, account=account) + url = f'https://api{sandbox}.dnsimple.com/v2/{account}' req = Request(url=url, headers=headers) prepped_request = req.prepare() return prepped_request @@ -256,7 +256,7 @@ def iterate_data(module, request_object): while page < total_pages: page = page + 1 - request_object.url = '{url}&page={page}'.format(url=base_url, page=page) + request_object.url = f'{base_url}&page={page}' new_results = Session().send(request_object) data = data + new_results.json()['data'] @@ -264,17 +264,17 @@ def iterate_data(module, request_object): def record_info(dnsimple_mod, req_obj): - req_obj.url, req_obj.method = req_obj.url + '/zones/' + dnsimple_mod.params["name"] + '/records?name=' + dnsimple_mod.params["record"], 'GET' + req_obj.url, req_obj.method = f"{req_obj.url}/zones/{dnsimple_mod.params['name']}/records?name={dnsimple_mod.params['record']}", 'GET' return iterate_data(dnsimple_mod, req_obj) def domain_info(dnsimple_mod, req_obj): - req_obj.url, req_obj.method = req_obj.url + '/zones/' + dnsimple_mod.params["name"] + '/records?per_page=100', 'GET' + req_obj.url, req_obj.method = f"{req_obj.url}/zones/{dnsimple_mod.params['name']}/records?per_page=100", 'GET' return iterate_data(dnsimple_mod, req_obj) def account_info(dnsimple_mod, req_obj): - req_obj.url, req_obj.method = req_obj.url + '/zones/?per_page=100', 'GET' + req_obj.url, req_obj.method = f"{req_obj.url}/zones/?per_page=100", 'GET' return iterate_data(dnsimple_mod, req_obj) diff --git a/plugins/modules/dnsmadeeasy.py b/plugins/modules/dnsmadeeasy.py index e74e8a547b..c2106f77af 100644 --- a/plugins/modules/dnsmadeeasy.py +++ b/plugins/modules/dnsmadeeasy.py @@ -377,7 +377,7 @@ class DME2(object): if sandbox: self.baseurl = 'https://api.sandbox.dnsmadeeasy.com/V2.0/' - self.module.warn(warning="Sandbox is enabled. All actions are made against the URL %s" % self.baseurl) + self.module.warn(warning=f"Sandbox is enabled. All actions are made against the URL {self.baseurl}") else: self.baseurl = 'https://api.dnsmadeeasy.com/V2.0/' @@ -392,7 +392,7 @@ class DME2(object): if not self.domain.isdigit(): self.domain = self.getDomainByName(self.domain)['id'] - self.record_url = 'dns/managed/' + str(self.domain) + '/records' + self.record_url = f"dns/managed/{self.domain}/records" self.monitor_url = 'monitor' self.contactList_url = 'contactList' @@ -419,7 +419,7 @@ class DME2(object): response, info = fetch_url(self.module, url, data=data, method=method, headers=self._headers()) if info['status'] not in (200, 201, 204): - self.module.fail_json(msg="%s returned %s, with body: %s" % (url, info['status'], info['msg'])) + self.module.fail_json(msg=f"{url} returned {info['status']}, with body: {info['msg']}") try: return json.load(response) @@ -468,7 +468,7 @@ class DME2(object): value = record_value.split(" ")[1] # Note that TXT records are surrounded by quotes in the API response. elif record_type == "TXT": - value = '"{0}"'.format(record_value) + value = f'"{record_value}"' elif record_type == "SRV": value = record_value.split(" ")[3] else: @@ -488,14 +488,14 @@ class DME2(object): results = {} # iterate over e.g. self.getDomains() || self.getRecords() - for result in getattr(self, 'get' + type.title() + 's')(): + for result in getattr(self, f"get{type.title()}s")(): map[result['name']] = result['id'] results[result['id']] = result # e.g. self.domain_map || self.record_map - setattr(self, type + '_map', map) - setattr(self, type + 's', results) # e.g. self.domains || self.records + setattr(self, f"{type}_map", map) + setattr(self, f"{type}s", results) # e.g. self.domains || self.records def prepareRecord(self, data): return json.dumps(data, separators=(',', ':')) @@ -506,17 +506,17 @@ class DME2(object): def updateRecord(self, record_id, data): # @TODO update the cache w/ resultant record + id when implemented - return self.query(self.record_url + '/' + str(record_id), 'PUT', data) + return self.query(f"{self.record_url}/{record_id}", 'PUT', data) def deleteRecord(self, record_id): # @TODO remove record from the cache when implemented - return self.query(self.record_url + '/' + str(record_id), 'DELETE') + return self.query(f"{self.record_url}/{record_id}", 'DELETE') def getMonitor(self, record_id): - return self.query(self.monitor_url + '/' + str(record_id), 'GET') + return self.query(f"{self.monitor_url}/{record_id}", 'GET') def updateMonitor(self, record_id, data): - return self.query(self.monitor_url + '/' + str(record_id), 'PUT', data) + return self.query(f"{self.monitor_url}/{record_id}", 'PUT', data) def prepareMonitor(self, data): return json.dumps(data, separators=(',', ':')) @@ -642,7 +642,7 @@ def main(): if not contact_list_id.isdigit() and contact_list_id != '': contact_list = DME.getContactListByName(contact_list_id) if not contact_list: - module.fail_json(msg="Contact list {0} does not exist".format(contact_list_id)) + module.fail_json(msg=f"Contact list {contact_list_id} does not exist") contact_list_id = contact_list.get('id', '') new_monitor['contactListId'] = contact_list_id else: @@ -671,7 +671,7 @@ def main(): if "value" not in new_record: if not current_record: module.fail_json( - msg="A record with name '%s' does not exist for domain '%s.'" % (record_name, module.params['domain'])) + msg=f"A record with name '{record_name}' does not exist for domain '{module.params['domain']}.'") module.exit_json(changed=False, result=dict(record=current_record, monitor=current_monitor)) # create record and monitor as the record does not exist @@ -709,7 +709,7 @@ def main(): else: module.fail_json( - msg="'%s' is an unknown value for the state argument" % state) + msg=f"'{state}' is an unknown value for the state argument") if __name__ == '__main__': diff --git a/plugins/modules/dpkg_divert.py b/plugins/modules/dpkg_divert.py index 7f37a47de4..12af06089c 100644 --- a/plugins/modules/dpkg_divert.py +++ b/plugins/modules/dpkg_divert.py @@ -144,7 +144,7 @@ import re import os from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.common.text.converters import to_bytes, to_native +from ansible.module_utils.common.text.converters import to_bytes from ansible_collections.community.general.plugins.module_utils.version import LooseVersion @@ -224,7 +224,7 @@ def main(): MAINCOMMAND.extend(['--divert', divert]) target = divert else: - target = '%s.distrib' % path + target = f'{path}.distrib' MAINCOMMAND.extend(['--add', path]) diversion_wanted['divert'] = target @@ -282,7 +282,7 @@ def main(): b_remove = to_bytes(to_remove, errors='surrogate_or_strict') os.unlink(b_remove) except OSError as e: - msg = 'Failed to remove %s: %s' % (to_remove, to_native(e)) + msg = f'Failed to remove {to_remove}: {e}' module.fail_json(changed=changed, cmd=maincommand, rc=rc, msg=msg, stderr=stderr, stdout=stdout, diversion=diversion) rc, stdout, stderr = module.run_command(MAINCOMMAND, check_rc=True) diff --git a/plugins/modules/easy_install.py b/plugins/modules/easy_install.py index d533da899f..cef29751ee 100644 --- a/plugins/modules/easy_install.py +++ b/plugins/modules/easy_install.py @@ -115,7 +115,7 @@ def _get_easy_install(module, env=None, executable=None): opt_dirs = [] else: # Try easy_install with the virtualenv directory first. - opt_dirs = ['%s/bin' % env] + opt_dirs = [f'{env}/bin'] for basename in candidate_easy_inst_basenames: easy_install = module.get_bin_path(basename, False, opt_dirs) if easy_install is not None: @@ -161,7 +161,7 @@ def main(): if not os.path.exists(os.path.join(env, 'bin', 'activate')): if module.check_mode: module.exit_json(changed=True) - command = '%s %s' % (virtualenv, env) + command = f'{virtualenv} {env}' if site_packages: command += ' --system-site-packages' cwd = tempfile.gettempdir() diff --git a/plugins/modules/ejabberd_user.py b/plugins/modules/ejabberd_user.py index d60a5d4f4a..6e3337c0b2 100644 --- a/plugins/modules/ejabberd_user.py +++ b/plugins/modules/ejabberd_user.py @@ -126,9 +126,9 @@ class EjabberdUser(object): if process is None: process = _proc - with self.runner("cmd " + options, output_process=process) as ctx: + with self.runner(f"cmd {options}", output_process=process) as ctx: res = ctx.run(cmd=cmd, host=self.host, user=self.user, pwd=self.pwd) - self.log('command: %s' % " ".join(ctx.run_info['cmd'])) + self.log(f"command: {' '.join(ctx.run_info['cmd'])}") return res def update(self): diff --git a/plugins/modules/elasticsearch_plugin.py b/plugins/modules/elasticsearch_plugin.py index 7d49ebded1..d494988df3 100644 --- a/plugins/modules/elasticsearch_plugin.py +++ b/plugins/modules/elasticsearch_plugin.py @@ -171,14 +171,14 @@ def install_plugin(module, plugin_bin, plugin_name, version, src, url, proxy_hos cmd.append(timeout) if version: - plugin_name = plugin_name + '/' + version + plugin_name = f"{plugin_name}/{version}" cmd[2] = plugin_name if proxy_host and proxy_port: - java_opts = ["-Dhttp.proxyHost=%s" % proxy_host, - "-Dhttp.proxyPort=%s" % proxy_port, - "-Dhttps.proxyHost=%s" % proxy_host, - "-Dhttps.proxyPort=%s" % proxy_port] + java_opts = [f"-Dhttp.proxyHost={proxy_host}", + f"-Dhttp.proxyPort={proxy_port}", + f"-Dhttps.proxyHost={proxy_host}", + f"-Dhttps.proxyPort={proxy_port}"] module.run_command_environ_update = dict(CLI_JAVA_OPTS=" ".join(java_opts), # Elasticsearch 8.x ES_JAVA_OPTS=" ".join(java_opts)) # Older Elasticsearch versions @@ -201,7 +201,7 @@ def install_plugin(module, plugin_bin, plugin_name, version, src, url, proxy_hos if rc != 0: reason = parse_error(out) - module.fail_json(msg="Installing plugin '%s' failed: %s" % (plugin_name, reason), err=err) + module.fail_json(msg=f"Installing plugin '{plugin_name}' failed: {reason}", err=err) return True, cmd, out, err @@ -216,7 +216,7 @@ def remove_plugin(module, plugin_bin, plugin_name): if rc != 0: reason = parse_error(out) - module.fail_json(msg="Removing plugin '%s' failed: %s" % (plugin_name, reason), err=err) + module.fail_json(msg=f"Removing plugin '{plugin_name}' failed: {reason}", err=err) return True, cmd, out, err @@ -247,7 +247,7 @@ def get_plugin_bin(module, plugin_bin=None): break if not valid_plugin_bin: - module.fail_json(msg='%s does not exist and no other valid plugin installers were found. Make sure Elasticsearch is installed.' % plugin_bin) + module.fail_json(msg=f'{plugin_bin} does not exist and no other valid plugin installers were found. Make sure Elasticsearch is installed.') return valid_plugin_bin diff --git a/plugins/modules/emc_vnx_sg_member.py b/plugins/modules/emc_vnx_sg_member.py index fce2c59c32..f2c47aef2d 100644 --- a/plugins/modules/emc_vnx_sg_member.py +++ b/plugins/modules/emc_vnx_sg_member.py @@ -81,7 +81,6 @@ hluid: import traceback from ansible.module_utils.basic import AnsibleModule, missing_required_lib -from ansible.module_utils.common.text.converters import to_native from ansible_collections.community.general.plugins.module_utils.storage.emc.emc_vnx import emc_vnx_argument_spec LIB_IMP_ERR = None @@ -141,8 +140,7 @@ def run_module(): except VNXAluAlreadyAttachedError: result['hluid'] = sg.get_hlu(alu) except (VNXAttachAluError, VNXStorageGroupError) as e: - module.fail_json(msg='Error attaching {0}: ' - '{1} '.format(alu, to_native(e)), + module.fail_json(msg=f'Error attaching {alu}: {e} ', **result) else: result['hluid'] = sg.get_hlu(alu) @@ -154,15 +152,13 @@ def run_module(): # being not attached when using absent is OK pass except VNXStorageGroupError as e: - module.fail_json(msg='Error detaching alu {0}: ' - '{1} '.format(alu, to_native(e)), + module.fail_json(msg=f'Error detaching alu {alu}: {e} ', **result) else: - module.fail_json(msg='No such storage group named ' - '{0}'.format(module.params['name']), + module.fail_json(msg=f"No such storage group named {module.params['name']}", **result) except VNXCredentialError as e: - module.fail_json(msg='{0}'.format(to_native(e)), **result) + module.fail_json(msg=f'{e}', **result) module.exit_json(**result) diff --git a/plugins/modules/etcd3.py b/plugins/modules/etcd3.py index 397bb1d767..10e59be839 100644 --- a/plugins/modules/etcd3.py +++ b/plugins/modules/etcd3.py @@ -195,13 +195,11 @@ def run_module(): try: etcd = etcd3.client(**client_params) except Exception as exp: - module.fail_json(msg='Cannot connect to etcd cluster: %s' % (to_native(exp)), - exception=traceback.format_exc()) + module.fail_json(msg=f'Cannot connect to etcd cluster: {exp}', exception=traceback.format_exc()) try: cluster_value = etcd.get(module.params['key']) except Exception as exp: - module.fail_json(msg='Cannot reach data: %s' % (to_native(exp)), - exception=traceback.format_exc()) + module.fail_json(msg=f'Cannot reach data: {exp}', exception=traceback.format_exc()) # Make the cluster_value[0] a string for string comparisons result['old_value'] = to_native(cluster_value[0]) @@ -214,8 +212,7 @@ def run_module(): try: etcd.delete(module.params['key']) except Exception as exp: - module.fail_json(msg='Cannot delete %s: %s' % (module.params['key'], to_native(exp)), - exception=traceback.format_exc()) + module.fail_json(msg=f"Cannot delete {module.params['key']}: {exp}", exception=traceback.format_exc()) else: result['changed'] = True elif module.params['state'] == 'present': @@ -226,8 +223,7 @@ def run_module(): try: etcd.put(module.params['key'], module.params['value']) except Exception as exp: - module.fail_json(msg='Cannot add or edit key %s: %s' % (module.params['key'], to_native(exp)), - exception=traceback.format_exc()) + module.fail_json(msg=f"Cannot add or edit key {module.params['key']}: {exp}", exception=traceback.format_exc()) else: result['changed'] = True else: diff --git a/plugins/modules/filesize.py b/plugins/modules/filesize.py index b0ef189143..59275ccb2e 100644 --- a/plugins/modules/filesize.py +++ b/plugins/modules/filesize.py @@ -262,7 +262,7 @@ def bytes_to_human(size, iec=False): if unit == 'KB': unit = 'kB' - return '%s %s' % (str(hsize), unit) + return f'{hsize} {unit}' def smart_blocksize(size, unit, product, bsize): @@ -312,8 +312,7 @@ def split_size_unit(string, isint=False): product = int(round(value)) else: if unit not in SIZE_UNITS.keys(): - raise AssertionError("invalid size unit (%s): unit must be one of %s, or none." % - (unit, ', '.join(sorted(SIZE_UNITS, key=SIZE_UNITS.get)))) + raise AssertionError(f"invalid size unit ({unit}): unit must be one of {', '.join(sorted(SIZE_UNITS, key=SIZE_UNITS.get))}, or none.") product = int(round(value * SIZE_UNITS[unit])) return value, unit, product @@ -323,7 +322,7 @@ def size_string(value): or a string itself. """ if not isinstance(value, (int, float, str)): - raise AssertionError("invalid value type (%s): size must be integer, float or string" % type(value)) + raise AssertionError(f"invalid value type ({type(value)}): size must be integer, float or string") return str(value) @@ -354,7 +353,7 @@ def current_size(args): path = args['path'] if os.path.exists(path): if not os.path.isfile(path): - raise AssertionError("%s exists but is not a regular file" % path) + raise AssertionError(f"{path} exists but is not a regular file") args['file_size'] = os.stat(path).st_size else: args['file_size'] = None @@ -382,7 +381,7 @@ def complete_dd_cmdline(args, dd_cmd): seek = int(args['file_size'] / bs) count = args['size_spec']['blocks'] - seek - dd_cmd += ['bs=%s' % str(bs), 'seek=%s' % str(seek), 'count=%s' % str(count)] + dd_cmd += [f'bs={bs}', f'seek={seek}', f'count={count}'] return dd_cmd @@ -431,7 +430,7 @@ def main(): filesize=size_descriptors) dd_bin = module.get_bin_path('dd', True) - dd_cmd = [dd_bin, 'if=%s' % args['source'], 'of=%s' % args['path']] + dd_cmd = [dd_bin, f"if={args['source']}", f"of={args['path']}"] if expected_filesize != initial_filesize or args['force']: result['cmd'] = ' '.join(complete_dd_cmdline(args, dd_cmd)) @@ -447,12 +446,11 @@ def main(): result['changed'] = result_filesize != initial_filesize if result['rc']: - msg = "dd error while creating file %s with size %s from source %s: see stderr for details" % ( - args['path'], args['size'], args['source']) + msg = f"dd error while creating file {args['path']} with size {args['size']} from source {args['source']}: see stderr for details" module.fail_json(msg=msg, **result) if result_filesize != expected_filesize: - msg = "module error while creating file %s with size %s from source %s: file is %s bytes long" % ( - args['path'], args['size'], args['source'], result_filesize) + msg = (f"module error while creating file {args['path']} with size {args['size']} " + f"from source {args['source']}: file is {result_filesize} bytes long") module.fail_json(msg=msg, **result) # dd follows symlinks, and so does this module, while file module doesn't. diff --git a/plugins/modules/filesystem.py b/plugins/modules/filesystem.py index 1477925de3..91448666a0 100644 --- a/plugins/modules/filesystem.py +++ b/plugins/modules/filesystem.py @@ -154,7 +154,6 @@ import re import stat from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.common.text.converters import to_native from ansible_collections.community.general.plugins.module_utils.version import LooseVersion @@ -178,7 +177,7 @@ class Device(object): elif os.path.isfile(self.path): devsize_in_bytes = os.path.getsize(self.path) else: - self.module.fail_json(changed=False, msg="Target device not supported: %s" % self) + self.module.fail_json(changed=False, msg=f"Target device not supported: {self}") return devsize_in_bytes @@ -271,20 +270,20 @@ class Filesystem(object): try: fssize_in_bytes = self.get_fs_size(dev) except NotImplementedError: - self.module.fail_json(msg="module does not support resizing %s filesystem yet" % self.fstype) + self.module.fail_json(msg=f"module does not support resizing {self.fstype} filesystem yet") except ValueError as err: - self.module.warn("unable to process %s output '%s'" % (self.INFO, to_native(err))) - self.module.fail_json(msg="unable to process %s output for %s" % (self.INFO, dev)) + self.module.warn(f"unable to process {self.INFO} output '{err}'") + self.module.fail_json(msg=f"unable to process {self.INFO} output for {dev}") if not fssize_in_bytes < devsize_in_bytes: - self.module.exit_json(changed=False, msg="%s filesystem is using the whole device %s" % (self.fstype, dev)) + self.module.exit_json(changed=False, msg=f"{self.fstype} filesystem is using the whole device {dev}") elif self.module.check_mode: - self.module.exit_json(changed=True, msg="resizing filesystem %s on device %s" % (self.fstype, dev)) + self.module.exit_json(changed=True, msg=f"resizing filesystem {self.fstype} on device {dev}") if self.GROW_MOUNTPOINT_ONLY: mountpoint = dev.get_mountpoint() if not mountpoint: - self.module.fail_json(msg="%s needs to be mounted for %s operations" % (dev, self.fstype)) + self.module.fail_json(msg=f"{dev} needs to be mounted for {self.fstype} operations") grow_target = mountpoint else: grow_target = str(dev) @@ -304,7 +303,7 @@ class Filesystem(object): def change_uuid(self, new_uuid, dev): """Change filesystem UUID. Returns stdout of used command""" if self.module.check_mode: - self.module.exit_json(change=True, msg='Changing %s filesystem UUID on device %s' % (self.fstype, dev)) + self.module.exit_json(change=True, msg=f'Changing {self.fstype} filesystem UUID on device {dev}') dummy, out, dummy = self.module.run_command(self.change_uuid_cmd(new_uuid=new_uuid, target=str(dev)), check_rc=True) return out @@ -459,13 +458,13 @@ class Btrfs(Filesystem): else: # assume version is greater or equal to 3.12 self.MKFS_FORCE_FLAGS = ['-f'] - self.module.warn('Unable to identify mkfs.btrfs version (%r, %r)' % (stdout, stderr)) + self.module.warn(f'Unable to identify mkfs.btrfs version ({stdout!r}, {stderr!r})') def get_fs_size(self, dev): """Return size in bytes of filesystem on device (integer).""" mountpoint = dev.get_mountpoint() if not mountpoint: - self.module.fail_json(msg="%s needs to be mounted for %s operations" % (dev, self.fstype)) + self.module.fail_json(msg=f"{dev} needs to be mounted for {self.fstype} operations") dummy, stdout, dummy = self.module.run_command([self.module.get_bin_path(self.INFO), 'filesystem', 'usage', '-b', mountpoint], check_rc=True) @@ -658,7 +657,7 @@ def main(): changed = False if not os.path.exists(dev): - msg = "Device %s not found." % dev + msg = f"Device {dev} not found." if state == "present": module.fail_json(msg=msg) else: @@ -684,12 +683,12 @@ def main(): try: klass = FILESYSTEMS[fstype] except KeyError: - module.fail_json(changed=False, msg="module does not support this filesystem (%s) yet." % fstype) + module.fail_json(changed=False, msg=f"module does not support this filesystem ({fstype}) yet.") filesystem = klass(module) if uuid and not (filesystem.CHANGE_UUID or filesystem.MKFS_SET_UUID_OPTIONS): - module.fail_json(changed=False, msg="module does not support UUID option for this filesystem (%s) yet." % fstype) + module.fail_json(changed=False, msg=f"module does not support UUID option for this filesystem ({fstype}) yet.") same_fs = fs and FILESYSTEMS.get(fs) == FILESYSTEMS[fstype] if same_fs and not resizefs and not uuid and not force: @@ -697,7 +696,7 @@ def main(): elif same_fs: if resizefs: if not filesystem.GROW: - module.fail_json(changed=False, msg="module does not support resizing %s filesystem yet." % fstype) + module.fail_json(changed=False, msg=f"module does not support resizing {fstype} filesystem yet.") out = filesystem.grow(dev) @@ -708,7 +707,7 @@ def main(): module.exit_json(changed=True, msg=out) elif fs and not force: - module.fail_json(msg="'%s' is already used as %s, use force=true to overwrite" % (dev, fs), rc=rc, err=err) + module.fail_json(msg=f"'{dev}' is already used as {fs}, use force=true to overwrite", rc=rc, err=err) # create fs filesystem.create(opts=mkfs_opts, dev=dev, uuid=uuid) diff --git a/plugins/modules/flatpak.py b/plugins/modules/flatpak.py index 3fab8f820b..c4168c15b7 100644 --- a/plugins/modules/flatpak.py +++ b/plugins/modules/flatpak.py @@ -190,7 +190,7 @@ def install_flat(module, binary, remote, names, method, no_dependencies): uri_names.append(name) else: id_names.append(name) - base_command = [binary, "install", "--{0}".format(method)] + base_command = [binary, "install", f"--{method}"] flatpak_version = _flatpak_version(module, binary) if LooseVersion(flatpak_version) < LooseVersion('1.1.3'): base_command += ["-y"] @@ -214,7 +214,7 @@ def update_flat(module, binary, names, method, no_dependencies): _match_installed_flat_name(module, binary, name, method) for name in names ] - command = [binary, "update", "--{0}".format(method)] + command = [binary, "update", f"--{method}"] flatpak_version = _flatpak_version(module, binary) if LooseVersion(flatpak_version) < LooseVersion('1.1.3'): command += ["-y"] @@ -242,14 +242,14 @@ def uninstall_flat(module, binary, names, method): command += ["-y"] else: command += ["--noninteractive"] - command += ["--{0}".format(method)] + installed_flat_names + command += [f"--{method}"] + installed_flat_names _flatpak_command(module, module.check_mode, command) result['changed'] = True def flatpak_exists(module, binary, names, method): """Check if the flatpaks are installed.""" - command = [binary, "list", "--{0}".format(method)] + command = [binary, "list", f"--{method}"] output = _flatpak_command(module, False, command) installed = [] not_installed = [] @@ -269,7 +269,7 @@ def _match_installed_flat_name(module, binary, name, method): global result # pylint: disable=global-variable-not-assigned parsed_name = _parse_flatpak_name(name) # Try running flatpak list with columns feature - command = [binary, "list", "--{0}".format(method), "--app", "--columns=application"] + command = [binary, "list", f"--{method}", "--app", "--columns=application"] _flatpak_command(module, False, command, ignore_failure=True) if result['rc'] != 0 and OUTDATED_FLATPAK_VERSION_ERROR_MESSAGE in result['stderr']: # Probably flatpak before 1.2 @@ -283,15 +283,17 @@ def _match_installed_flat_name(module, binary, name, method): if matched_flatpak_name: return matched_flatpak_name else: - result['msg'] = "Flatpak removal failed: Could not match any installed flatpaks to " +\ - "the name `{0}`. ".format(_parse_flatpak_name(name)) +\ + result['msg'] = ( + "Flatpak removal failed: Could not match any installed flatpaks to " + f"the name `{_parse_flatpak_name(name)}`. " "If you used a URL, try using the reverse DNS name of the flatpak" + ) module.fail_json(**result) def _match_flat_using_outdated_flatpak_format(module, binary, parsed_name, method): global result # pylint: disable=global-variable-not-assigned - command = [binary, "list", "--{0}".format(method), "--app", "--columns=application"] + command = [binary, "list", f"--{method}", "--app", "--columns=application"] output = _flatpak_command(module, False, command) for row in output.split('\n'): if parsed_name.lower() == row.lower(): @@ -300,7 +302,7 @@ def _match_flat_using_outdated_flatpak_format(module, binary, parsed_name, metho def _match_flat_using_flatpak_column_feature(module, binary, parsed_name, method): global result # pylint: disable=global-variable-not-assigned - command = [binary, "list", "--{0}".format(method), "--app"] + command = [binary, "list", f"--{method}", "--app"] output = _flatpak_command(module, False, command) for row in output.split('\n'): if parsed_name.lower() in row.lower(): @@ -395,7 +397,7 @@ def main(): # If the binary was not found, fail the operation if not binary: - module.fail_json(msg="Executable '%s' was not found on the system." % executable, **result) + module.fail_json(msg=f"Executable '{executable}' was not found on the system.", **result) module.run_command_environ_update = dict(LANGUAGE='C', LC_ALL='C') diff --git a/plugins/modules/flatpak_remote.py b/plugins/modules/flatpak_remote.py index 891942143d..a035d6808f 100644 --- a/plugins/modules/flatpak_remote.py +++ b/plugins/modules/flatpak_remote.py @@ -119,7 +119,7 @@ from ansible.module_utils.common.text.converters import to_bytes, to_native def add_remote(module, binary, name, flatpakrepo_url, method): """Add a new remote.""" global result # pylint: disable=global-variable-not-assigned - command = [binary, "remote-add", "--{0}".format(method), name, flatpakrepo_url] + command = [binary, "remote-add", f"--{method}", name, flatpakrepo_url] _flatpak_command(module, module.check_mode, command) result['changed'] = True @@ -127,14 +127,14 @@ def add_remote(module, binary, name, flatpakrepo_url, method): def remove_remote(module, binary, name, method): """Remove an existing remote.""" global result # pylint: disable=global-variable-not-assigned - command = [binary, "remote-delete", "--{0}".format(method), "--force", name] + command = [binary, "remote-delete", f"--{method}", "--force", name] _flatpak_command(module, module.check_mode, command) result['changed'] = True def remote_exists(module, binary, name, method): """Check if the remote exists.""" - command = [binary, "remote-list", "--show-disabled", "--{0}".format(method)] + command = [binary, "remote-list", "--show-disabled", f"--{method}"] # The query operation for the remote needs to be run even in check mode output = _flatpak_command(module, False, command) for line in output.splitlines(): @@ -149,7 +149,7 @@ def remote_exists(module, binary, name, method): def enable_remote(module, binary, name, method): """Enable a remote.""" global result # pylint: disable=global-variable-not-assigned - command = [binary, "remote-modify", "--enable", "--{0}".format(method), name] + command = [binary, "remote-modify", "--enable", f"--{method}", name] _flatpak_command(module, module.check_mode, command) result['changed'] = True @@ -157,14 +157,14 @@ def enable_remote(module, binary, name, method): def disable_remote(module, binary, name, method): """Disable a remote.""" global result # pylint: disable=global-variable-not-assigned - command = [binary, "remote-modify", "--disable", "--{0}".format(method), name] + command = [binary, "remote-modify", "--disable", f"--{method}", name] _flatpak_command(module, module.check_mode, command) result['changed'] = True def remote_enabled(module, binary, name, method): """Check if the remote is enabled.""" - command = [binary, "remote-list", "--show-disabled", "--{0}".format(method)] + command = [binary, "remote-list", "--show-disabled", f"--{method}"] # The query operation for the remote needs to be run even in check mode output = _flatpak_command(module, False, command) for line in output.splitlines(): @@ -223,7 +223,7 @@ def main(): # If the binary was not found, fail the operation if not binary: - module.fail_json(msg="Executable '%s' was not found on the system." % executable, **result) + module.fail_json(msg=f"Executable '{executable}' was not found on the system.", **result) remote_already_exists = remote_exists(module, binary, to_bytes(name), method)