diff --git a/changelogs/fragments/10975-mod-fstr-r.yml b/changelogs/fragments/10975-mod-fstr-r.yml new file mode 100644 index 0000000000..304316f055 --- /dev/null +++ b/changelogs/fragments/10975-mod-fstr-r.yml @@ -0,0 +1,22 @@ +minor_changes: + - read_csv - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - redfish_command - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - redfish_config - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - redfish_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - redhat_subscription - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - redis - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - redis_data - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - redis_data_incr - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - redis_data_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - redis_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - rhevm - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - rhsm_release - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - rhsm_repository - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - riak - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - rocketchat - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - rollbar_deployment - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - rundeck_acl_policy - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - rundeck_job_executions_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - rundeck_job_run - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - rundeck_project - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). + - runit - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10975). diff --git a/plugins/modules/read_csv.py b/plugins/modules/read_csv.py index e195029d03..8fd5bc4c50 100644 --- a/plugins/modules/read_csv.py +++ b/plugins/modules/read_csv.py @@ -187,12 +187,12 @@ def main(): with open(path, 'rb') as f: data = f.read() except (IOError, OSError) as e: - module.fail_json(msg="Unable to open file: %s" % to_native(e)) + module.fail_json(msg=f"Unable to open file: {e}") reader = read_csv(data, dialect, fieldnames) if key and key not in reader.fieldnames: - module.fail_json(msg="Key '%s' was not found in the CSV header fields: %s" % (key, ', '.join(reader.fieldnames))) + module.fail_json(msg=f"Key '{key}' was not found in the CSV header fields: {', '.join(reader.fieldnames)}") data_dict = dict() data_list = list() @@ -202,15 +202,15 @@ def main(): for row in reader: data_list.append(row) except CSVError as e: - module.fail_json(msg="Unable to process file: %s" % to_native(e)) + module.fail_json(msg=f"Unable to process file: {e}") else: try: for row in reader: if unique and row[key] in data_dict: - module.fail_json(msg="Key '%s' is not unique for value '%s'" % (key, row[key])) + module.fail_json(msg=f"Key '{key}' is not unique for value '{row[key]}'") data_dict[row[key]] = row except CSVError as e: - module.fail_json(msg="Unable to process file: %s" % to_native(e)) + module.fail_json(msg=f"Unable to process file: {e}") module.exit_json(dict=data_dict, list=data_list) diff --git a/plugins/modules/redfish_command.py b/plugins/modules/redfish_command.py index 736d38d6c4..8531acb4fc 100644 --- a/plugins/modules/redfish_command.py +++ b/plugins/modules/redfish_command.py @@ -1003,19 +1003,19 @@ def main(): bios_attributes = module.params['bios_attributes'] # Build root URI - root_uri = "https://" + module.params['baseuri'] + root_uri = f"https://{module.params['baseuri']}" rf_utils = RedfishUtils(creds, root_uri, timeout, module, resource_id=resource_id, data_modification=True, strip_etag_quotes=strip_etag_quotes) # 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 if category == "Accounts": diff --git a/plugins/modules/redfish_config.py b/plugins/modules/redfish_config.py index a804baab8e..269bca2540 100644 --- a/plugins/modules/redfish_config.py +++ b/plugins/modules/redfish_config.py @@ -507,19 +507,19 @@ def main(): power_restore_policy = module.params['power_restore_policy'] # Build root URI - root_uri = "https://" + module.params['baseuri'] + root_uri = f"https://{module.params['baseuri']}" rf_utils = RedfishUtils(creds, root_uri, timeout, module, resource_id=resource_id, data_modification=True, strip_etag_quotes=strip_etag_quotes) # 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 if category == "Systems": diff --git a/plugins/modules/redfish_info.py b/plugins/modules/redfish_info.py index af1b3af319..6823a00ace 100644 --- a/plugins/modules/redfish_info.py +++ b/plugins/modules/redfish_info.py @@ -472,7 +472,7 @@ def main(): manager = module.params['manager'] # Build root URI - root_uri = "https://" + module.params['baseuri'] + root_uri = f"https://{module.params['baseuri']}" rf_utils = RedfishUtils(creds, root_uri, timeout, module) # Build Category list @@ -500,10 +500,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 == "Service": diff --git a/plugins/modules/redhat_subscription.py b/plugins/modules/redhat_subscription.py index c2b76fe8ac..e35dd621ae 100644 --- a/plugins/modules/redhat_subscription.py +++ b/plugins/modules/redhat_subscription.py @@ -292,7 +292,7 @@ class Rhsm(object): self.module = module def update_plugin_conf(self, plugin, enabled=True): - plugin_conf = '/etc/yum/pluginconf.d/%s.conf' % plugin + plugin_conf = f'/etc/yum/pluginconf.d/{plugin}.conf' if isfile(plugin_conf): tmpfd, tmpfile = tempfile.mkstemp() @@ -336,7 +336,7 @@ class Rhsm(object): options = [] for k, v in sorted(kwargs.items()): if re.search(r'^(server|rhsm)_', k) and v is not None: - options.append('--%s=%s' % (k.replace('_', '.', 1), v)) + options.append(f"--{k.replace('_', '.', 1)}={v}") # When there is nothing to configure, then it is not necessary # to run config command, because it only returns current @@ -411,7 +411,7 @@ class Rhsm(object): bus.flush() except dbus.exceptions.DBusException as e: - self.module.debug('Failed to connect to system D-Bus bus, will use CLI: %s' % e) + self.module.debug(f'Failed to connect to system D-Bus bus, will use CLI: {e}') return False self.module.debug('Verified system D-Bus bus as usable') @@ -755,7 +755,7 @@ class Rhsm(object): ''' items = [] if serials is not None and serials: - items = ["--serial=%s" % s for s in serials] + items = [f"--serial={s}" for s in serials] if serials is None: items = ["--all"] @@ -790,7 +790,7 @@ class Rhsm(object): args.extend(['--quantity', to_native(quantity)]) rc, stderr, stdout = self.module.run_command(args, check_rc=True) else: - self.module.fail_json(msg='Pool ID: %s not in list of available pools' % pool_id) + self.module.fail_json(msg=f'Pool ID: {pool_id} not in list of available pools') return pool_ids def update_subscriptions_by_pool_ids(self, pool_ids): @@ -851,7 +851,7 @@ class RhsmPool(object): return int(getattr(self, 'QuantityUsed')) def subscribe(self): - args = "subscription-manager attach --pool %s" % self.get_pool_id() + args = f"subscription-manager attach --pool {self.get_pool_id()}" rc, stdout, stderr = self.module.run_command(args, check_rc=True) if rc == 0: return True @@ -956,8 +956,7 @@ class SysPurpose(object): elif key == 'sync': pass else: - raise KeyError("Attribute: %s not in list of allowed attributes: %s" % - (key, self.ALLOWED_ATTRIBUTES)) + raise KeyError(f"Attribute: {key} not in list of allowed attributes: {self.ALLOWED_ATTRIBUTES}") current_syspurpose = self._read_syspurpose() if current_syspurpose != syspurpose: syspurpose_changed = True @@ -1101,7 +1100,7 @@ def main(): try: syspurpose_changed = SysPurpose().update_syspurpose(syspurpose) except Exception as err: - module.fail_json(msg="Failed to update syspurpose attributes: %s" % to_native(err)) + module.fail_json(msg=f"Failed to update syspurpose attributes: {to_native(err)}") # Ensure system is registered if state == 'present': @@ -1115,12 +1114,12 @@ def main(): try: rhsm.sync_syspurpose() except Exception as e: - module.fail_json(msg="Failed to synchronize syspurpose attributes: %s" % to_native(e)) + module.fail_json(msg=f"Failed to synchronize syspurpose attributes: {to_native(e)}") if pool_ids: try: result = rhsm.update_subscriptions_by_pool_ids(pool_ids) except Exception as e: - module.fail_json(msg="Failed to update subscriptions for '%s': %s" % (server_hostname, to_native(e))) + module.fail_json(msg=f"Failed to update subscriptions for '{server_hostname}': {to_native(e)}") else: module.exit_json(**result) else: @@ -1144,10 +1143,10 @@ def main(): else: subscribed_pool_ids = [] except Exception as e: - module.fail_json(msg="Failed to register with '%s': %s" % (server_hostname, to_native(e))) + module.fail_json(msg=f"Failed to register with '{server_hostname}': {to_native(e)}") else: module.exit_json(changed=True, - msg="System successfully registered to '%s'." % server_hostname, + msg=f"System successfully registered to '{server_hostname}'.", subscribed_pool_ids=subscribed_pool_ids) # Ensure system is *not* registered @@ -1158,9 +1157,9 @@ def main(): try: rhsm.unregister() except Exception as e: - module.fail_json(msg="Failed to unregister: %s" % to_native(e)) + module.fail_json(msg=f"Failed to unregister: {e}") else: - module.exit_json(changed=True, msg="System successfully unregistered from %s." % server_hostname) + module.exit_json(changed=True, msg=f"System successfully unregistered from {server_hostname}.") if __name__ == '__main__': diff --git a/plugins/modules/redis.py b/plugins/modules/redis.py index f442599368..9ef6dc29f2 100644 --- a/plugins/modules/redis.py +++ b/plugins/modules/redis.py @@ -150,7 +150,6 @@ else: from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.common.text.formatters import human_to_bytes -from ansible.module_utils.common.text.converters import to_native from ansible_collections.community.general.plugins.module_utils.redis import ( fail_imports, redis_auth_argument_spec, redis_auth_params) import re @@ -231,7 +230,7 @@ def main(): try: r.ping() except Exception as e: - module.fail_json(msg="unable to connect to database: %s" % to_native(e), exception=traceback.format_exc()) + module.fail_json(msg=f"unable to connect to database: {e}", exception=traceback.format_exc()) # Check if we are already in the mode that we want info = r.info() @@ -282,7 +281,7 @@ def main(): try: r.ping() except Exception as e: - module.fail_json(msg="unable to connect to database: %s" % to_native(e), exception=traceback.format_exc()) + module.fail_json(msg=f"unable to connect to database: {e}", exception=traceback.format_exc()) # Do the stuff # (Check Check_mode before commands so the commands aren't evaluated @@ -297,7 +296,7 @@ def main(): if module.check_mode or flush(r, db): module.exit_json(changed=True, flushed=True, db=db) else: # Flush never fails :) - module.fail_json(msg="Unable to flush '%d' database" % db) + module.fail_json(msg=f"Unable to flush '{db}' database") elif command == 'config': name = module.params['name'] @@ -314,12 +313,12 @@ def main(): try: r.ping() except Exception as e: - module.fail_json(msg="unable to connect to database: %s" % to_native(e), exception=traceback.format_exc()) + module.fail_json(msg=f"unable to connect to database: {e}", exception=traceback.format_exc()) try: old_value = r.config_get(name)[name] except Exception as e: - module.fail_json(msg="unable to read config: %s" % to_native(e), exception=traceback.format_exc()) + module.fail_json(msg=f"unable to read config: {e}", exception=traceback.format_exc()) changed = old_value != value if module.check_mode or not changed: @@ -328,7 +327,7 @@ def main(): try: r.config_set(name, value) except Exception as e: - module.fail_json(msg="unable to write config: %s" % to_native(e), exception=traceback.format_exc()) + module.fail_json(msg=f"unable to write config: {e}", exception=traceback.format_exc()) module.exit_json(changed=changed, name=name, value=value) else: module.fail_json(msg='A valid command must be provided') diff --git a/plugins/modules/redis_data.py b/plugins/modules/redis_data.py index dfca11c898..eb4a7e7ef0 100644 --- a/plugins/modules/redis_data.py +++ b/plugins/modules/redis_data.py @@ -177,35 +177,33 @@ def main(): try: old_value = redis.connection.get(key) except Exception as e: - msg = 'Failed to get value of key: {0} with exception: {1}'.format( - key, str(e)) + msg = f'Failed to get value of key: {key} with exception: {e}' result['msg'] = msg module.fail_json(**result) if state == 'absent': if module.check_mode: if old_value is None: - msg = 'Key: {0} not present'.format(key) + msg = f'Key: {key} not present' result['msg'] = msg module.exit_json(**result) else: - msg = 'Deleted key: {0}'.format(key) + msg = f'Deleted key: {key}' result['msg'] = msg module.exit_json(**result) try: ret = redis.connection.delete(key) if ret == 0: - msg = 'Key: {0} not present'.format(key) + msg = f'Key: {key} not present' result['msg'] = msg module.exit_json(**result) else: - msg = 'Deleted key: {0}'.format(key) + msg = f'Deleted key: {key}' result['msg'] = msg result['changed'] = True module.exit_json(**result) except Exception as e: - msg = 'Failed to delete key: {0} with exception: {1}'.format( - key, str(e)) + msg = f'Failed to delete key: {key} with exception: {e}' result['msg'] = msg module.fail_json(**result) @@ -213,38 +211,36 @@ def main(): try: old_value = redis.connection.get(key) except Exception as e: - msg = 'Failed to get value of key: {0} with exception: {1}'.format( - key, str(e)) + msg = f'Failed to get value of key: {key} with exception: {e}' result['msg'] = msg module.fail_json(**result) result['old_value'] = old_value if old_value == value and keepttl is not False and px is None: - msg = 'Key {0} already has desired value'.format(key) + msg = f'Key {key} already has desired value' result['msg'] = msg result['value'] = value module.exit_json(**result) if module.check_mode: - result['msg'] = 'Set key: {0}'.format(key) + result['msg'] = f'Set key: {key}' result['value'] = value module.exit_json(**result) try: ret = redis.connection.set(**set_args) if ret is None: if nx: - msg = 'Could not set key: {0}. Key already present.'.format( - key) + msg = f'Could not set key: {key}. Key already present.' else: - msg = 'Could not set key: {0}. Key not present.'.format(key) + msg = f'Could not set key: {key}. Key not present.' result['msg'] = msg module.fail_json(**result) - msg = 'Set key: {0}'.format(key) + msg = f'Set key: {key}' result['msg'] = msg result['changed'] = True result['value'] = value module.exit_json(**result) except Exception as e: - msg = 'Failed to set key: {0} with exception: {2}'.format(key, str(e)) + msg = f'Failed to set key: {key} with exception: {e}' result['msg'] = msg module.fail_json(**result) diff --git a/plugins/modules/redis_data_incr.py b/plugins/modules/redis_data_incr.py index f6c1b67401..3a1d4ed158 100644 --- a/plugins/modules/redis_data_incr.py +++ b/plugins/modules/redis_data_incr.py @@ -126,17 +126,14 @@ def main(): if res is not None: value = float(res) except ValueError as e: - msg = 'Value: {0} of key: {1} is not incrementable(int or float)'.format( - res, key) + msg = f'Value: {res} of key: {key} is not incrementable(int or float)' result['msg'] = msg module.fail_json(**result) except Exception as e: - msg = 'Failed to get value of key: {0} with exception: {1}'.format( - key, str(e)) + msg = f'Failed to get value of key: {key} with exception: {e}' result['msg'] = msg module.fail_json(**result) - msg = 'Incremented key: {0} by {1} to {2}'.format( - key, increment, value + increment) + msg = f'Incremented key: {key} by {increment} to {value + increment}' result['msg'] = msg result['value'] = float(value + increment) module.exit_json(**result) @@ -144,42 +141,37 @@ def main(): if increment_float is not None: try: value = redis.connection.incrbyfloat(key, increment) - msg = 'Incremented key: {0} by {1} to {2}'.format( - key, increment, value) + msg = f'Incremented key: {key} by {increment} to {value}' result['msg'] = msg result['value'] = float(value) result['changed'] = True module.exit_json(**result) except Exception as e: - msg = 'Failed to increment key: {0} by {1} with exception: {2}'.format( - key, increment, str(e)) + msg = f'Failed to increment key: {key} by {increment} with exception: {e}' result['msg'] = msg module.fail_json(**result) elif increment_int is not None: try: value = redis.connection.incrby(key, increment) - msg = 'Incremented key: {0} by {1} to {2}'.format( - key, increment, value) + msg = f'Incremented key: {key} by {increment} to {value}' result['msg'] = msg result['value'] = float(value) result['changed'] = True module.exit_json(**result) except Exception as e: - msg = 'Failed to increment key: {0} by {1} with exception: {2}'.format( - key, increment, str(e)) + msg = f'Failed to increment key: {key} by {increment} with exception: {e}' result['msg'] = msg module.fail_json(**result) else: try: value = redis.connection.incr(key) - msg = 'Incremented key: {0} to {1}'.format(key, value) + msg = f'Incremented key: {key} to {value}' result['msg'] = msg result['value'] = float(value) result['changed'] = True module.exit_json(**result) except Exception as e: - msg = 'Failed to increment key: {0} with exception: {1}'.format( - key, str(e)) + msg = f'Failed to increment key: {key} with exception: {e}' result['msg'] = msg module.fail_json(**result) diff --git a/plugins/modules/redis_data_info.py b/plugins/modules/redis_data_info.py index ad0ea943b4..5750e2c2a4 100644 --- a/plugins/modules/redis_data_info.py +++ b/plugins/modules/redis_data_info.py @@ -93,16 +93,15 @@ def main(): try: value = redis.connection.get(key) except Exception as e: - msg = 'Failed to get value of key "{0}" with exception: {1}'.format( - key, str(e)) + msg = f'Failed to get value of key "{key}" with exception: {e}' result['msg'] = msg module.fail_json(**result) if value is None: - msg = 'Key "{0}" does not exist in database'.format(key) + msg = f'Key "{key}" does not exist in database' result['exists'] = False else: - msg = 'Got key "{0}"'.format(key) + msg = f'Got key "{key}"' result['value'] = value result['exists'] = True result['msg'] = msg diff --git a/plugins/modules/redis_info.py b/plugins/modules/redis_info.py index f4327a121f..fd02ebdeec 100644 --- a/plugins/modules/redis_info.py +++ b/plugins/modules/redis_info.py @@ -223,7 +223,6 @@ except ImportError: HAS_REDIS_PACKAGE = False 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.redis import ( fail_imports, redis_auth_argument_spec, redis_auth_params) @@ -253,7 +252,7 @@ def main(): try: client.ping() except Exception as e: - module.fail_json(msg="unable to connect to database: %s" % to_native(e), exception=traceback.format_exc()) + module.fail_json(msg=f"unable to connect to database: {e}", exception=traceback.format_exc()) info = client.info() diff --git a/plugins/modules/rhevm.py b/plugins/modules/rhevm.py index 422d2739d2..647b278574 100644 --- a/plugins/modules/rhevm.py +++ b/plugins/modules/rhevm.py @@ -364,7 +364,7 @@ class RHEVConn(object): port = module.params.get('port') insecure_api = module.params.get('insecure_api') - url = "https://%s:%s" % (server, port) + url = f"https://{server}:{port}" try: api = API(url=url, username=user, password=password, insecure=str(insecure_api)) @@ -432,11 +432,11 @@ class RHEVConn(object): try: VM.disks.add(newdisk) VM.update() - setMsg("Successfully added disk " + diskname) + setMsg(f"Successfully added disk {diskname}") setChanged() except Exception as e: setFailed() - setMsg("Error attaching " + diskname + "disk, please recheck and remove any leftover configuration.") + setMsg(f"Error attaching {diskname}disk, please recheck and remove any leftover configuration.") setMsg(str(e)) return False @@ -446,15 +446,15 @@ class RHEVConn(object): while currentdisk.status.state != 'ok': currentdisk = VM.disks.get(name=diskname) if attempt == 100: - setMsg("Error, disk %s, state %s" % (diskname, str(currentdisk.status.state))) + setMsg(f"Error, disk {diskname}, state {currentdisk.status.state}") raise Exception() else: attempt += 1 time.sleep(2) - setMsg("The disk " + diskname + " is ready.") + setMsg(f"The disk {diskname} is ready.") except Exception as e: setFailed() - setMsg("Error getting the state of " + diskname + ".") + setMsg(f"Error getting the state of {diskname}.") setMsg(str(e)) return False return True @@ -472,11 +472,11 @@ class RHEVConn(object): try: VM.nics.add(newnic) VM.update() - setMsg("Successfully added iface " + nicname) + setMsg(f"Successfully added iface {nicname}") setChanged() except Exception as e: setFailed() - setMsg("Error attaching " + nicname + " iface, please recheck and remove any leftover configuration.") + setMsg(f"Error attaching {nicname} iface, please recheck and remove any leftover configuration.") setMsg(str(e)) return False @@ -486,15 +486,15 @@ class RHEVConn(object): while currentnic.active is not True: currentnic = VM.nics.get(name=nicname) if attempt == 100: - setMsg("Error, iface %s, state %s" % (nicname, str(currentnic.active))) + setMsg(f"Error, iface {nicname}, state {currentnic.active}") raise Exception() else: attempt += 1 time.sleep(2) - setMsg("The iface " + nicname + " is ready.") + setMsg(f"The iface {nicname} is ready.") except Exception as e: setFailed() - setMsg("Error getting the state of " + nicname + ".") + setMsg(f"Error getting the state of {nicname}.") setMsg(str(e)) return False return True @@ -596,7 +596,7 @@ class RHEVConn(object): def set_Disk(self, diskname, disksize, diskinterface, diskboot): DISK = self.get_disk(diskname) - setMsg("Checking disk " + diskname) + setMsg(f"Checking disk {diskname}") if DISK.get_bootable() != diskboot: try: DISK.set_bootable(diskboot) @@ -648,15 +648,15 @@ class RHEVConn(object): checkFail() if NIC.name != newname: NIC.name = newname - setMsg('Updating iface name to ' + newname) + setMsg(f"Updating iface name to {newname}") setChanged() if str(NIC.network.id) != str(NETWORK.id): NIC.set_network(NETWORK) - setMsg('Updating iface network to ' + vlan) + setMsg(f"Updating iface network to {vlan}") setChanged() if NIC.interface != interface: NIC.interface = interface - setMsg('Updating iface interface to ' + interface) + setMsg(f"Updating iface interface to {interface}") setChanged() try: NIC.update() @@ -711,7 +711,7 @@ class RHEVConn(object): try: for iface in ifaces: try: - setMsg('creating host interface ' + iface['name']) + setMsg(f"creating host interface {iface['name']}") if 'management' in iface: manageip = iface['ip'] if 'boot_protocol' not in iface: @@ -742,7 +742,7 @@ class RHEVConn(object): ) ) except Exception as e: - setMsg('Failed to create the bond for ' + iface['name']) + setMsg(f"Failed to create the bond for {iface['name']}") setFailed() setMsg(str(e)) return False @@ -759,9 +759,9 @@ class RHEVConn(object): override_configuration=True, bonding=tmpiface) networklist.append(tmpnetwork) - setMsg('Applying network ' + iface['name']) + setMsg(f"Applying network {iface['name']}") except Exception as e: - setMsg('Failed to set' + iface['name'] + ' as network interface') + setMsg(f"Failed to set{iface['name']} as network interface") setFailed() setMsg(str(e)) return False @@ -776,7 +776,7 @@ class RHEVConn(object): gateway=iface['gateway'] )) networklist.append(tmpnetwork) - setMsg('Applying network ' + iface['name']) + setMsg(f"Applying network {iface['name']}") else: tmpiface = params.HostNIC( name=iface['name'], @@ -789,7 +789,7 @@ class RHEVConn(object): )) ifacelist[iface['name']] = tmpiface except Exception as e: - setMsg('Failed to set ' + iface['name']) + setMsg(f"Failed to set {iface['name']}") setFailed() setMsg(str(e)) return False @@ -824,7 +824,7 @@ class RHEVConn(object): HOST = self.get_Host(host_name) state = HOST.status.state - setMsg('State before setting to maintenance: ' + str(state)) + setMsg(f"State before setting to maintenance: {state}") HOST.deactivate() while state != 'maintenance': HOST = self.get_Host(host_name) @@ -953,7 +953,7 @@ class RHEVConn(object): try: VM.placement_policy.host = HOST VM.update() - setMsg("Set startup host to " + vmhost) + setMsg(f"Set startup host to {vmhost}") setChanged() except Exception as e: setMsg("Failed to set startup host.") @@ -976,7 +976,7 @@ class RHEVConn(object): ), ) setChanged() - setMsg("VM migrated to " + vmhost) + setMsg(f"VM migrated to {vmhost}") except Exception as e: setMsg("Failed to set startup host.") setMsg(str(e)) @@ -1090,7 +1090,7 @@ class RHEV(object): bootselect = True for disk in disks: - diskname = name + "_Disk" + str(counter) + "_" + disk.get('name', '').replace('/', '_') + diskname = f"{name}_Disk{counter}_{disk.get('name', '').replace('/', '_')}" disksize = disk.get('size', 1) diskdomain = disk.get('domain', None) if diskdomain is None: @@ -1207,7 +1207,7 @@ class RHEV(object): return False if state == VM.status.state: - setMsg("VM state was already " + state) + setMsg(f"VM state was already {state}") else: if state == "up": setMsg("VM is going to start") @@ -1222,7 +1222,7 @@ class RHEV(object): checkFail() self.setPower(vmname, "up", timeout) checkFail() - setMsg("the vm state is set to " + state) + setMsg(f"the vm state is set to {state}") return True def setCD(self, vmname, cd_drive): diff --git a/plugins/modules/rhsm_release.py b/plugins/modules/rhsm_release.py index 7034713c04..f42096698f 100644 --- a/plugins/modules/rhsm_release.py +++ b/plugins/modules/rhsm_release.py @@ -117,7 +117,7 @@ def main(): # sanity check: the target release at least looks like a valid release if target_release and not release_matcher.findall(target_release): - module.fail_json(msg='"{0}" does not appear to be a valid release.'.format(target_release)) + module.fail_json(msg=f'"{target_release}" does not appear to be a valid release.') # Will fail with useful error from s-m if system not subscribed current_release = get_release(module) diff --git a/plugins/modules/rhsm_repository.py b/plugins/modules/rhsm_repository.py index b5b4eab4dc..168145a384 100644 --- a/plugins/modules/rhsm_repository.py +++ b/plugins/modules/rhsm_repository.py @@ -109,7 +109,7 @@ class Rhsm(object): if rc == 0 and out == 'This system has no repositories available through subscriptions.\n': self.module.fail_json(msg='This system has no repositories available through subscriptions') elif rc == 1: - self.module.fail_json(msg='subscription-manager failed with the following error: %s' % err) + self.module.fail_json(msg=f'subscription-manager failed with the following error: {err}') else: return rc, out, err @@ -181,22 +181,22 @@ def repository_modify(module, rhsm, state, name, purge=False): for repoid in matched_existing_repo: if len(matched_existing_repo[repoid]) == 0: - results.append("%s is not a valid repository ID" % repoid) - module.fail_json(results=results, msg="%s is not a valid repository ID" % repoid) + results.append(f"{repoid} is not a valid repository ID") + module.fail_json(results=results, msg=f"{repoid} is not a valid repository ID") for repo in matched_existing_repo[repoid]: if state in ['disabled', 'absent']: if repo['enabled']: changed = True - diff_before += "Repository '%s' is enabled for this system\n" % repo['id'] - diff_after += "Repository '%s' is disabled for this system\n" % repo['id'] - results.append("Repository '%s' is disabled for this system" % repo['id']) + diff_before += f"Repository '{repo['id']}' is enabled for this system\n" + diff_after += f"Repository '{repo['id']}' is disabled for this system\n" + results.append(f"Repository '{repo['id']}' is disabled for this system") rhsm_arguments += ['--disable', repo['id']] elif state in ['enabled', 'present']: if not repo['enabled']: changed = True - diff_before += "Repository '%s' is disabled for this system\n" % repo['id'] - diff_after += "Repository '%s' is enabled for this system\n" % repo['id'] - results.append("Repository '%s' is enabled for this system" % repo['id']) + diff_before += f"Repository '{repo['id']}' is disabled for this system\n" + diff_after += f"Repository '{repo['id']}' is enabled for this system\n" + results.append(f"Repository '{repo['id']}' is enabled for this system") rhsm_arguments += ['--enable', repo['id']] # Disable all enabled repos on the system that are not in the task and not @@ -208,9 +208,9 @@ def repository_modify(module, rhsm, state, name, purge=False): if len(difference) > 0: for repoid in difference: changed = True - diff_before.join("Repository '{repoid}'' is enabled for this system\n".format(repoid=repoid)) - diff_after.join("Repository '{repoid}' is disabled for this system\n".format(repoid=repoid)) - results.append("Repository '{repoid}' is disabled for this system".format(repoid=repoid)) + diff_before.join(f"Repository '{repoid}'' is enabled for this system\n") + diff_after.join(f"Repository '{repoid}' is disabled for this system\n") + results.append(f"Repository '{repoid}' is disabled for this system") rhsm_arguments.extend(['--disable', repoid]) for updated_repo in updated_repo_list: if updated_repo['id'] in difference: diff --git a/plugins/modules/riak.py b/plugins/modules/riak.py index 4f3ac14e13..7b1ce92b4f 100644 --- a/plugins/modules/riak.py +++ b/plugins/modules/riak.py @@ -127,7 +127,7 @@ def main(): while True: if time.time() > timeout: module.fail_json(msg='Timeout, could not fetch Riak stats.') - (response, info) = fetch_url(module, 'http://%s/stats' % (http_conn), force=True, timeout=5) + (response, info) = fetch_url(module, f'http://{http_conn}/stats', force=True, timeout=5) if info['status'] == 200: stats_raw = response.read() break @@ -211,7 +211,7 @@ def main(): module.fail_json(msg='Timeout waiting for handoffs.') if wait_for_service: - cmd = riak_admin_bin + ['wait_for_service', 'riak_%s' % wait_for_service, node_name] + cmd = riak_admin_bin + ['wait_for_service', f'riak_{wait_for_service}', node_name] rc, out, err = module.run_command(cmd) result['service'] = out diff --git a/plugins/modules/rocketchat.py b/plugins/modules/rocketchat.py index 8bbc1e153b..0675db61b5 100644 --- a/plugins/modules/rocketchat.py +++ b/plugins/modules/rocketchat.py @@ -174,7 +174,7 @@ def build_payload_for_rocketchat(module, text, channel, username, icon_url, icon if channel[0] == '#' or channel[0] == '@': payload['channel'] = channel else: - payload['channel'] = '#' + channel + payload['channel'] = f"#{channel}" if username is not None: payload['username'] = username if icon_emoji is not None: @@ -196,7 +196,7 @@ def build_payload_for_rocketchat(module, text, channel, username, icon_url, icon payload = module.jsonify(payload) if is_pre740: - payload = "payload=" + payload + payload = f"payload={payload}" return payload @@ -212,7 +212,7 @@ def do_notify_rocketchat(module, domain, token, protocol, payload, is_pre740): headers = {'Content-type': 'application/json'} response, info = fetch_url(module, rocketchat_incoming_webhook, data=payload, headers=headers) if info['status'] != 200: - module.fail_json(msg="failed to send message, return status=%s" % str(info['status'])) + module.fail_json(msg=f"failed to send message, return status={info['status']}") def main(): diff --git a/plugins/modules/rollbar_deployment.py b/plugins/modules/rollbar_deployment.py index 383573d8c7..60930af680 100644 --- a/plugins/modules/rollbar_deployment.py +++ b/plugins/modules/rollbar_deployment.py @@ -88,7 +88,6 @@ import traceback from urllib.parse import urlencode from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.common.text.converters import to_native from ansible.module_utils.urls import fetch_url @@ -132,12 +131,12 @@ def main(): data = urlencode(params) response, info = fetch_url(module, url, data=data, method='POST') except Exception as e: - module.fail_json(msg='Unable to notify Rollbar: %s' % to_native(e), exception=traceback.format_exc()) + module.fail_json(msg=f'Unable to notify Rollbar: {e}', exception=traceback.format_exc()) else: if info['status'] == 200: module.exit_json(changed=True) else: - module.fail_json(msg='HTTP result code: %d connecting to %s' % (info['status'], url)) + module.fail_json(msg=f"HTTP result code: {info['status']} connecting to {url}") if __name__ == '__main__': diff --git a/plugins/modules/rundeck_acl_policy.py b/plugins/modules/rundeck_acl_policy.py index e93363cea2..ed7dc2abbc 100644 --- a/plugins/modules/rundeck_acl_policy.py +++ b/plugins/modules/rundeck_acl_policy.py @@ -128,12 +128,9 @@ class RundeckACLManager: def __init__(self, module): self.module = module if module.params.get("project"): - self.endpoint = "project/%s/acl/%s.aclpolicy" % ( - self.module.params["project"], - self.module.params["name"], - ) + self.endpoint = f"project/{self.module.params['project']}/acl/{self.module.params['name']}.aclpolicy" else: - self.endpoint = "system/acl/%s.aclpolicy" % self.module.params["name"] + self.endpoint = f"system/acl/{self.module.params['name']}.aclpolicy" def get_acl(self): resp, info = api_request( @@ -160,12 +157,11 @@ class RundeckACLManager: if info["status"] == 201: self.module.exit_json(changed=True, before={}, after=self.get_acl()) elif info["status"] == 400: - self.module.fail_json(msg="Unable to validate acl %s. Please ensure it is a valid ACL" % - self.module.params["name"]) + self.module.fail_json(msg=f"Unable to validate acl {self.module.params['name']}. Please ensure it is a valid ACL") elif info["status"] == 409: - self.module.fail_json(msg="ACL %s already exists" % self.module.params["name"]) + self.module.fail_json(msg=f"ACL {self.module.params['name']} already exists") else: - self.module.fail_json(msg="Unhandled HTTP status %d, please report the bug" % info["status"], + self.module.fail_json(msg=f"Unhandled HTTP status {info['status']}, please report the bug", before={}, after=self.get_acl()) else: if facts["contents"] == self.module.params["policy"]: @@ -184,10 +180,9 @@ class RundeckACLManager: if info["status"] == 200: self.module.exit_json(changed=True, before=facts, after=self.get_acl()) elif info["status"] == 400: - self.module.fail_json(msg="Unable to validate acl %s. Please ensure it is a valid ACL" % - self.module.params["name"]) + self.module.fail_json(msg=f"Unable to validate acl {self.module.params['name']}. Please ensure it is a valid ACL") elif info["status"] == 404: - self.module.fail_json(msg="ACL %s doesn't exists. Cannot update." % self.module.params["name"]) + self.module.fail_json(msg=f"ACL {self.module.params['name']} doesn't exists. Cannot update.") def remove_acl(self): facts = self.get_acl() diff --git a/plugins/modules/rundeck_job_executions_info.py b/plugins/modules/rundeck_job_executions_info.py index 4c4bd85d09..dbc3adad20 100644 --- a/plugins/modules/rundeck_job_executions_info.py +++ b/plugins/modules/rundeck_job_executions_info.py @@ -149,8 +149,7 @@ class RundeckJobExecutionsInfo(object): def job_executions(self): response, info = api_request( module=self.module, - endpoint="job/%s/executions?offset=%s&max=%s&status=%s" - % (quote(self.job_id), self.offset, self.max, self.status), + endpoint=f"job/{quote(self.job_id)}/executions?offset={self.offset}&max={self.max}&status={self.status}", method="GET" ) diff --git a/plugins/modules/rundeck_job_run.py b/plugins/modules/rundeck_job_run.py index 768e67967a..2c95346920 100644 --- a/plugins/modules/rundeck_job_run.py +++ b/plugins/modules/rundeck_job_run.py @@ -207,7 +207,7 @@ class RundeckJobRun(object): for k, v in self.job_options.items(): if not isinstance(v, str): self.module.exit_json( - msg="Job option '%s' value must be a string" % k, + msg=f"Job option '{k}' value must be a string", execution_info={} ) @@ -217,17 +217,17 @@ class RundeckJobRun(object): due = datetime.now() + timedelta(seconds=self.wait_execution_timeout) while not timeout: - endpoint = "execution/%d" % execution_id + endpoint = f"execution/{execution_id}" response = api_request(module=self.module, endpoint=endpoint)[0] output = api_request(module=self.module, - endpoint="execution/%d/output" % execution_id) + endpoint=f"execution/{execution_id}/output") log_output = "\n".join([x["log"] for x in output[0]["entries"]]) response.update({"output": log_output}) if response["status"] == "aborted": break elif response["status"] == "scheduled": - self.module.exit_json(msg="Job scheduled to run at %s" % self.run_at_time, + self.module.exit_json(msg=f"Job scheduled to run at {self.run_at_time}", execution_info=response, changed=True) elif response["status"] == "failed": @@ -250,7 +250,7 @@ class RundeckJobRun(object): def job_run(self): response, info = api_request( module=self.module, - endpoint="job/%s/run" % quote(self.job_id), + endpoint=f"job/{quote(self.job_id)}/run", method="POST", data={ "loglevel": self.loglevel, @@ -273,7 +273,7 @@ class RundeckJobRun(object): if self.abort_on_timeout: api_request( module=self.module, - endpoint="execution/%s/abort" % response['id'], + endpoint=f"execution/{response['id']}/abort", method="GET" ) diff --git a/plugins/modules/rundeck_project.py b/plugins/modules/rundeck_project.py index 47db41a744..ce67614987 100644 --- a/plugins/modules/rundeck_project.py +++ b/plugins/modules/rundeck_project.py @@ -112,7 +112,7 @@ class RundeckProjectManager(object): def get_project_facts(self): resp, info = api_request( module=self.module, - endpoint="project/%s" % self.module.params["name"], + endpoint=f"project/{self.module.params['name']}", ) return resp @@ -144,7 +144,7 @@ class RundeckProjectManager(object): if info["status"] == 201: self.module.exit_json(changed=True, before={}, after=self.get_project_facts()) else: - self.module.fail_json(msg="Unhandled HTTP status %d, please report the bug" % info["status"], + self.module.fail_json(msg=f"Unhandled HTTP status {info['status']}, please report the bug", before={}, after=self.get_project_facts()) else: self.module.exit_json(changed=False, before=facts, after=facts) @@ -158,7 +158,7 @@ class RundeckProjectManager(object): if not self.module.check_mode: api_request( module=self.module, - endpoint="project/%s" % self.module.params["name"], + endpoint=f"project/{self.module.params['name']}", method="DELETE", ) diff --git a/plugins/modules/runit.py b/plugins/modules/runit.py index d5acba36d3..917b0bc395 100644 --- a/plugins/modules/runit.py +++ b/plugins/modules/runit.py @@ -87,7 +87,6 @@ import os import re from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.common.text.converters import to_native class Sv(object): @@ -113,8 +112,8 @@ class Sv(object): self.svc_cmd = module.get_bin_path('sv', opt_dirs=self.extra_paths, required=True) self.svstat_cmd = module.get_bin_path('sv', opt_dirs=self.extra_paths) - self.svc_full = '/'.join([self.service_dir, self.name]) - self.src_full = '/'.join([self.service_src, self.name]) + self.svc_full = f"{self.service_dir}/{self.name}" + self.src_full = f"{self.service_src}/{self.name}" self.enabled = os.path.lexists(self.svc_full) if self.enabled: @@ -127,16 +126,16 @@ class Sv(object): try: os.symlink(self.src_full, self.svc_full) except OSError as e: - self.module.fail_json(path=self.src_full, msg='Error while linking: %s' % to_native(e)) + self.module.fail_json(path=self.src_full, msg=f'Error while linking: {e}') else: - self.module.fail_json(msg="Could not find source for service to enable (%s)." % self.src_full) + self.module.fail_json(msg=f"Could not find source for service to enable ({self.src_full}).") def disable(self): self.execute_command([self.svc_cmd, 'force-stop', self.src_full]) try: os.unlink(self.svc_full) except OSError as e: - self.module.fail_json(path=self.svc_full, msg='Error while unlinking: %s' % to_native(e)) + self.module.fail_json(path=self.svc_full, msg=f'Error while unlinking: {e}') def get_status(self): (rc, out, err) = self.execute_command([self.svstat_cmd, 'status', self.svc_full]) @@ -203,7 +202,7 @@ class Sv(object): try: (rc, out, err) = self.module.run_command(cmd) except Exception as e: - self.module.fail_json(msg="failed to execute: %s" % to_native(e)) + self.module.fail_json(msg=f"failed to execute: {e}") return rc, out, err def report(self): @@ -243,7 +242,7 @@ def main(): else: sv.disable() except (OSError, IOError) as e: - module.fail_json(msg="Could not change service link: %s" % to_native(e)) + module.fail_json(msg=f"Could not change service link: {e}") if state is not None and state != sv.state: changed = True