modules a*: use f-strings (#10942)

* modules a*: use f-strings

* add changelog frag

* add changelog frag

* rename chglof frag file
This commit is contained in:
Alexei Znamensky 2025-10-23 17:50:32 +13:00 committed by GitHub
commit d86340b9d3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 219 additions and 214 deletions

View file

@ -0,0 +1,22 @@
minor_changes:
- hwc_utils module_utils plugin - adjust f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- manageiq module_utils plugin - adjust f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- aerospike_migrations - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- airbrake_deployment - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- aix_devices - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- aix_filesystem - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- aix_inittab - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- aix_lvg - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- aix_lvol - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- alerta_customer - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- ali_instance - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- alternatives - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- android_sdk - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- ansible_galaxy_install - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- apache2_mod_proxy - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- apache2_module - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- apk - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- apt_repo - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- apt_rpm - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- archive - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).
- awall - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10942).

View file

@ -41,7 +41,7 @@ class HwcClientException(Exception):
self._message = message self._message = message
def __str__(self): def __str__(self):
msg = f" code={self._code!s}," if self._code != 0 else "" msg = f" code={self._code}," if self._code != 0 else ""
return f"[HwcClientException]{msg} message={self._message}" return f"[HwcClientException]{msg} message={self._message}"

View file

@ -151,7 +151,7 @@ class ManageIQ(object):
if resource: if resource:
return resource return resource
else: else:
msg = f"{collection_name} where {params!s} does not exist in manageiq" msg = f"{collection_name} where {params} does not exist in manageiq"
self.module.fail_json(msg=msg) self.module.fail_json(msg=msg)
def policies(self, resource_id, resource_type, resource_name): def policies(self, resource_id, resource_type, resource_name):

View file

@ -217,7 +217,7 @@ def run_module():
if has_migrations: if has_migrations:
module.fail_json(msg="Failed.", skip_reason=skip_reason) module.fail_json(msg="Failed.", skip_reason=skip_reason)
except Exception as e: except Exception as e:
module.fail_json(msg="Error: {0}".format(e)) module.fail_json(msg=f"Error: {e}")
module.exit_json(**result) module.exit_json(**result)
@ -263,8 +263,7 @@ class Migrations:
data = data.split("\t") data = data.split("\t")
if len(data) != 1 and len(data) != 2: if len(data) != 1 and len(data) != 2:
self.module.fail_json( self.module.fail_json(
msg="Unexpected number of values returned in info command: " + msg=f"Unexpected number of values returned in info command: {len(data)}"
str(len(data))
) )
# data will be in format 'command\touput' # data will be in format 'command\touput'
data = data[-1] data = data[-1]
@ -329,7 +328,7 @@ class Migrations:
"""returns a True or False. """returns a True or False.
Does the namespace have migrations for the node passed? Does the namespace have migrations for the node passed?
If no node passed, uses the local node or the first one in the list""" If no node passed, uses the local node or the first one in the list"""
namespace_stats = self._info_cmd_helper("namespace/" + namespace, node) namespace_stats = self._info_cmd_helper(f"namespace/{namespace}", node)
try: try:
namespace_tx = \ namespace_tx = \
int(namespace_stats[self.module.params['migrate_tx_key']]) int(namespace_stats[self.module.params['migrate_tx_key']])
@ -337,13 +336,10 @@ class Migrations:
int(namespace_stats[self.module.params['migrate_rx_key']]) int(namespace_stats[self.module.params['migrate_rx_key']])
except KeyError: except KeyError:
self.module.fail_json( self.module.fail_json(
msg="Did not find partition remaining key:" + msg=(
self.module.params['migrate_tx_key'] + f"Did not find partition remaining key:{self.module.params['migrate_tx_key']} "
" or key:" + f"or key:{self.module.params['migrate_rx_key']} in 'namespace/{namespace}' output."
self.module.params['migrate_rx_key'] + )
" in 'namespace/" +
namespace +
"' output."
) )
except TypeError: except TypeError:
self.module.fail_json( self.module.fail_json(
@ -433,7 +429,7 @@ class Migrations:
cmd = "cluster-stable:" cmd = "cluster-stable:"
target_cluster_size = self.module.params['target_cluster_size'] target_cluster_size = self.module.params['target_cluster_size']
if target_cluster_size is not None: if target_cluster_size is not None:
cmd = cmd + "size=" + str(target_cluster_size) + ";" cmd = f"{cmd}size={target_cluster_size};"
for node in self._nodes: for node in self._nodes:
try: try:
cluster_key.add(self._info_cmd_helper(cmd, node)) cluster_key.add(self._info_cmd_helper(cmd, node))
@ -475,8 +471,7 @@ class Migrations:
stable, reason = self._cluster_good_state() stable, reason = self._cluster_good_state()
if stable is not True: if stable is not True:
skip_reason.append( skip_reason.append(
"Skipping on try#" + str(try_num) + f"Skipping on try#{try_num} for reason:{reason}"
" for reason:" + reason
) )
else: else:
if self._can_use_cluster_stable(): if self._can_use_cluster_stable():
@ -485,14 +480,12 @@ class Migrations:
else: else:
consecutive_good = 0 consecutive_good = 0
skip_reason.append( skip_reason.append(
"Skipping on try#" + str(try_num) + f"Skipping on try#{try_num} for reason: cluster_stable"
" for reason:" + " cluster_stable"
) )
elif self._has_migs(local): elif self._has_migs(local):
# print("_has_migs") # print("_has_migs")
skip_reason.append( skip_reason.append(
"Skipping on try#" + str(try_num) + f"Skipping on try#{try_num} for reason: migrations"
" for reason:" + " migrations"
) )
consecutive_good = 0 consecutive_good = 0
else: else:

View file

@ -146,7 +146,7 @@ def main():
params["version"] = module.params["version"] params["version"] = module.params["version"]
# Build deploy url # Build deploy url
url = module.params.get('url') + module.params["project_id"] + '/deploys?key=' + module.params["project_key"] url = f"{module.params.get('url')}{module.params['project_id']}/deploys?key={module.params['project_key']}"
json_body = module.jsonify(params) json_body = module.jsonify(params)
# Build header # Build header
@ -159,7 +159,7 @@ def main():
if info['status'] == 200 or info['status'] == 201: if info['status'] == 200 or info['status'] == 201:
module.exit_json(changed=True) module.exit_json(changed=True)
else: 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__': if __name__ == '__main__':

View file

@ -141,7 +141,7 @@ def _check_device(module, device):
""" """
lsdev_cmd = module.get_bin_path('lsdev', True) lsdev_cmd = module.get_bin_path('lsdev', True)
rc, lsdev_out, err = module.run_command(["%s" % lsdev_cmd, '-C', '-l', "%s" % device]) rc, lsdev_out, err = module.run_command([lsdev_cmd, '-C', '-l', device])
if rc != 0: if rc != 0:
module.fail_json(msg="Failed to run lsdev", rc=rc, err=err) module.fail_json(msg="Failed to run lsdev", rc=rc, err=err)
@ -166,7 +166,7 @@ def _check_device_attr(module, device, attr):
""" """
lsattr_cmd = module.get_bin_path('lsattr', True) lsattr_cmd = module.get_bin_path('lsattr', True)
rc, lsattr_out, err = module.run_command(["%s" % lsattr_cmd, '-El', "%s" % device, '-a', "%s" % attr]) rc, lsattr_out, err = module.run_command([lsattr_cmd, '-El', device, '-a', f"{attr}"])
hidden_attrs = ['delalias4', 'delalias6'] hidden_attrs = ['delalias4', 'delalias6']
@ -180,7 +180,7 @@ def _check_device_attr(module, device, attr):
return current_param return current_param
elif rc != 0: elif rc != 0:
module.fail_json(msg="Failed to run lsattr: %s" % err, rc=rc, err=err) module.fail_json(msg=f"Failed to run lsattr: {err}", rc=rc, err=err)
current_param = lsattr_out.split()[1] current_param = lsattr_out.split()[1]
return current_param return current_param
@ -191,7 +191,7 @@ def discover_device(module, device):
cfgmgr_cmd = module.get_bin_path('cfgmgr', True) cfgmgr_cmd = module.get_bin_path('cfgmgr', True)
if device is not None: if device is not None:
device = "-l %s" % device device = f"-l {device}"
else: else:
device = '' device = ''
@ -199,7 +199,7 @@ def discover_device(module, device):
changed = True changed = True
msg = '' msg = ''
if not module.check_mode: if not module.check_mode:
rc, cfgmgr_out, err = module.run_command(["%s" % cfgmgr_cmd, "%s" % device]) rc, cfgmgr_out, err = module.run_command([cfgmgr_cmd, device])
changed = True changed = True
msg = cfgmgr_out msg = cfgmgr_out
@ -223,9 +223,9 @@ def change_device_attr(module, attributes, device, force):
elif current_param != new_param: elif current_param != new_param:
if force: if force:
cmd = ["%s" % chdev_cmd, '-l', "%s" % device, '-a', "%s=%s" % (attr, attributes[attr]), "%s" % force] cmd = [chdev_cmd, '-l', device, '-a', f"{attr}={attributes[attr]}", f"{force}"]
else: else:
cmd = ["%s" % chdev_cmd, '-l', "%s" % device, '-a', "%s=%s" % (attr, attributes[attr])] cmd = [chdev_cmd, '-l', device, '-a', f"{attr}={attributes[attr]}"]
if not module.check_mode: if not module.check_mode:
rc, chdev_out, err = module.run_command(cmd) rc, chdev_out, err = module.run_command(cmd)
@ -238,22 +238,22 @@ def change_device_attr(module, attributes, device, force):
if len(attr_changed) > 0: if len(attr_changed) > 0:
changed = True changed = True
attr_changed_msg = "Attributes changed: %s. " % ','.join(attr_changed) attr_changed_msg = f"Attributes changed: {','.join(attr_changed)}. "
else: else:
changed = False changed = False
attr_changed_msg = '' attr_changed_msg = ''
if len(attr_not_changed) > 0: if len(attr_not_changed) > 0:
attr_not_changed_msg = "Attributes already set: %s. " % ','.join(attr_not_changed) attr_not_changed_msg = f"Attributes already set: {','.join(attr_not_changed)}. "
else: else:
attr_not_changed_msg = '' attr_not_changed_msg = ''
if len(attr_invalid) > 0: if len(attr_invalid) > 0:
attr_invalid_msg = "Invalid attributes: %s " % ', '.join(attr_invalid) attr_invalid_msg = f"Invalid attributes: {', '.join(attr_invalid)} "
else: else:
attr_invalid_msg = '' attr_invalid_msg = ''
msg = "%s%s%s" % (attr_changed_msg, attr_not_changed_msg, attr_invalid_msg) msg = f"{attr_changed_msg}{attr_not_changed_msg}{attr_invalid_msg}"
return changed, msg return changed, msg
@ -281,9 +281,9 @@ def remove_device(module, device, force, recursive, state):
if not module.check_mode: if not module.check_mode:
if state: if state:
rc, rmdev_out, err = module.run_command(["%s" % rmdev_cmd, "-l", "%s" % device, "%s" % recursive, "%s" % force]) rc, rmdev_out, err = module.run_command([rmdev_cmd, "-l", device, f"{recursive}", f"{force}"])
else: else:
rc, rmdev_out, err = module.run_command(["%s" % rmdev_cmd, "-l", "%s" % device, "%s" % recursive]) rc, rmdev_out, err = module.run_command([rmdev_cmd, "-l", device, f"{recursive}"])
if rc != 0: if rc != 0:
module.fail_json(msg="Failed to run rmdev", rc=rc, err=err) module.fail_json(msg="Failed to run rmdev", rc=rc, err=err)
@ -329,7 +329,7 @@ def main():
if device_status: if device_status:
result['changed'], result['msg'] = change_device_attr(module, attributes, device, force) result['changed'], result['msg'] = change_device_attr(module, attributes, device, force)
else: else:
result['msg'] = "Device %s does not exist." % device result['msg'] = f"Device {device} does not exist."
else: else:
# discovery devices (cfgmgr) # discovery devices (cfgmgr)
@ -340,7 +340,7 @@ def main():
result['changed'], result['msg'] = discover_device(module, device) result['changed'], result['msg'] = discover_device(module, device)
else: else:
result['msg'] = "Device %s does not exist." % device result['msg'] = f"Device {device} does not exist."
else: else:
result['changed'], result['msg'] = discover_device(module, device) result['changed'], result['msg'] = discover_device(module, device)
@ -355,16 +355,16 @@ def main():
if check_device: if check_device:
if state == 'defined' and device_state == 'Defined': if state == 'defined' and device_state == 'Defined':
result['changed'] = False result['changed'] = False
result['msg'] = 'Device %s already in Defined' % device result['msg'] = f'Device {device} already in Defined'
else: else:
result['changed'], result['msg'] = remove_device(module, device, force, recursive, state) result['changed'], result['msg'] = remove_device(module, device, force, recursive, state)
else: else:
result['msg'] = "Device %s does not exist." % device result['msg'] = f"Device {device} does not exist."
else: else:
result['msg'] = "Unexpected state %s." % state result['msg'] = f"Unexpected state {state}."
module.fail_json(**result) module.fail_json(**result)
module.exit_json(**result) module.exit_json(**result)

View file

@ -184,7 +184,7 @@ def _fs_exists(module, filesystem):
return False return False
else: else:
module.fail_json(msg="Failed to run lsfs. Error message: %s" % err) module.fail_json(msg=f"Failed to run lsfs. Error message: {err}")
else: else:
@ -203,7 +203,7 @@ def _check_nfs_device(module, nfs_host, device):
showmount_cmd = module.get_bin_path('showmount', True) showmount_cmd = module.get_bin_path('showmount', True)
rc, showmount_out, err = module.run_command([showmount_cmd, "-a", nfs_host]) rc, showmount_out, err = module.run_command([showmount_cmd, "-a", nfs_host])
if rc != 0: if rc != 0:
module.fail_json(msg="Failed to run showmount. Error message: %s" % err) module.fail_json(msg=f"Failed to run showmount. Error message: {err}")
else: else:
showmount_data = showmount_out.splitlines() showmount_data = showmount_out.splitlines()
for line in showmount_data: for line in showmount_data:
@ -225,20 +225,20 @@ def _validate_vg(module, vg):
lsvg_cmd = module.get_bin_path('lsvg', True) lsvg_cmd = module.get_bin_path('lsvg', True)
rc, current_active_vgs, err = module.run_command([lsvg_cmd, "-o"]) rc, current_active_vgs, err = module.run_command([lsvg_cmd, "-o"])
if rc != 0: if rc != 0:
module.fail_json(msg="Failed executing %s command." % lsvg_cmd) module.fail_json(msg=f"Failed executing {lsvg_cmd} command.")
rc, current_all_vgs, err = module.run_command([lsvg_cmd]) rc, current_all_vgs, err = module.run_command([lsvg_cmd])
if rc != 0: if rc != 0:
module.fail_json(msg="Failed executing %s command." % lsvg_cmd) module.fail_json(msg=f"Failed executing {lsvg_cmd} command.")
if vg in current_all_vgs and vg not in current_active_vgs: if vg in current_all_vgs and vg not in current_active_vgs:
msg = "Volume group %s is in varyoff state." % vg msg = f"Volume group {vg} is in varyoff state."
return False, msg return False, msg
elif vg in current_active_vgs: elif vg in current_active_vgs:
msg = "Volume group %s is in varyon state." % vg msg = f"Volume group {vg} is in varyon state."
return True, msg return True, msg
else: else:
msg = "Volume group %s does not exist." % vg msg = f"Volume group {vg} does not exist."
return None, msg return None, msg
@ -247,7 +247,7 @@ def resize_fs(module, filesystem, size):
chfs_cmd = module.get_bin_path('chfs', True) chfs_cmd = module.get_bin_path('chfs', True)
if not module.check_mode: if not module.check_mode:
rc, chfs_out, err = module.run_command([chfs_cmd, "-a", "size=%s" % size, filesystem]) rc, chfs_out, err = module.run_command([chfs_cmd, "-a", f"size={size}", filesystem])
if rc == 28: if rc == 28:
changed = False changed = False
@ -257,7 +257,7 @@ def resize_fs(module, filesystem, size):
changed = False changed = False
return changed, err return changed, err
else: else:
module.fail_json(msg="Failed to run chfs. Error message: %s" % err) module.fail_json(msg=f"Failed to run chfs. Error message: {err}")
else: else:
if re.findall('The filesystem size is already', chfs_out): if re.findall('The filesystem size is already', chfs_out):
@ -301,19 +301,19 @@ def create_fs(
if size is None: if size is None:
size = '' size = ''
else: else:
size = "-a size=%s" % size size = f"-a size={size}"
if device is None: if device is None:
device = '' device = ''
else: else:
device = "-d %s" % device device = f"-d {device}"
if vg is None: if vg is None:
vg = '' vg = ''
else: else:
vg_state, msg = _validate_vg(module, vg) vg_state, msg = _validate_vg(module, vg)
if vg_state: if vg_state:
vg = "-g %s" % vg vg = f"-g {vg}"
else: else:
changed = False changed = False
@ -323,7 +323,7 @@ def create_fs(
mount_group = '' mount_group = ''
else: else:
mount_group = "-u %s" % mount_group mount_group = f"-u {mount_group}"
auto_mount = auto_mount_opt[auto_mount] auto_mount = auto_mount_opt[auto_mount]
account_subsystem = account_subsys_opt[account_subsystem] account_subsystem = account_subsys_opt[account_subsystem]
@ -334,10 +334,10 @@ def create_fs(
if not module.check_mode: if not module.check_mode:
rc, mknfsmnt_out, err = module.run_command([mknfsmnt_cmd, "-f", filesystem, device, "-h", nfs_server, "-t", permissions, auto_mount, "-w", "bg"]) rc, mknfsmnt_out, err = module.run_command([mknfsmnt_cmd, "-f", filesystem, device, "-h", nfs_server, "-t", permissions, auto_mount, "-w", "bg"])
if rc != 0: if rc != 0:
module.fail_json(msg="Failed to run mknfsmnt. Error message: %s" % err) module.fail_json(msg=f"Failed to run mknfsmnt. Error message: {err}")
else: else:
changed = True changed = True
msg = "NFS file system %s created." % filesystem msg = f"NFS file system {filesystem} created."
return changed, msg return changed, msg
else: else:
@ -401,11 +401,10 @@ def create_fs(
if rc == 10: if rc == 10:
module.exit_json( module.exit_json(
msg="Using a existent previously defined logical volume, " msg=f"Using a existent previously defined logical volume, volume group needs to be empty. {err}")
"volume group needs to be empty. %s" % err)
elif rc != 0: elif rc != 0:
module.fail_json(msg="Failed to run %s. Error message: %s" % (cmd, err)) module.fail_json(msg=f"Failed to run {cmd}. Error message: {err}")
else: else:
changed = True changed = True
@ -433,12 +432,12 @@ def remove_fs(module, filesystem, rm_mount_point):
cmd = [rmfs_cmd, "-r", rm_mount_point, filesystem] cmd = [rmfs_cmd, "-r", rm_mount_point, filesystem]
rc, rmfs_out, err = module.run_command(cmd) rc, rmfs_out, err = module.run_command(cmd)
if rc != 0: if rc != 0:
module.fail_json(msg="Failed to run %s. Error message: %s" % (cmd, err)) module.fail_json(msg=f"Failed to run {cmd}. Error message: {err}")
else: else:
changed = True changed = True
msg = rmfs_out msg = rmfs_out
if not rmfs_out: if not rmfs_out:
msg = "File system %s removed." % filesystem msg = f"File system {filesystem} removed."
return changed, msg return changed, msg
else: else:
@ -455,10 +454,10 @@ def mount_fs(module, filesystem):
if not module.check_mode: if not module.check_mode:
rc, mount_out, err = module.run_command([mount_cmd, filesystem]) rc, mount_out, err = module.run_command([mount_cmd, filesystem])
if rc != 0: if rc != 0:
module.fail_json(msg="Failed to run mount. Error message: %s" % err) module.fail_json(msg=f"Failed to run mount. Error message: {err}")
else: else:
changed = True changed = True
msg = "File system %s mounted." % filesystem msg = f"File system {filesystem} mounted."
return changed, msg return changed, msg
else: else:
@ -475,10 +474,10 @@ def unmount_fs(module, filesystem):
if not module.check_mode: if not module.check_mode:
rc, unmount_out, err = module.run_command([unmount_cmd, filesystem]) rc, unmount_out, err = module.run_command([unmount_cmd, filesystem])
if rc != 0: if rc != 0:
module.fail_json(msg="Failed to run unmount. Error message: %s" % err) module.fail_json(msg=f"Failed to run unmount. Error message: {err}")
else: else:
changed = True changed = True
msg = "File system %s unmounted." % filesystem msg = f"File system {filesystem} unmounted."
return changed, msg return changed, msg
else: else:
@ -533,7 +532,7 @@ def main():
# Check if fs is mounted or exists. # Check if fs is mounted or exists.
if fs_mounted or fs_exists: if fs_mounted or fs_exists:
result['msg'] = "File system %s already exists." % filesystem result['msg'] = f"File system {filesystem} already exists."
result['changed'] = False result['changed'] = False
# If parameter size was passed, resize fs. # If parameter size was passed, resize fs.
@ -569,32 +568,32 @@ def main():
elif state == 'absent': elif state == 'absent':
if ismount(filesystem): if ismount(filesystem):
result['msg'] = "File system %s mounted." % filesystem result['msg'] = f"File system {filesystem} mounted."
else: else:
fs_status = _fs_exists(module, filesystem) fs_status = _fs_exists(module, filesystem)
if not fs_status: if not fs_status:
result['msg'] = "File system %s does not exist." % filesystem result['msg'] = f"File system {filesystem} does not exist."
else: else:
result['changed'], result['msg'] = remove_fs(module, filesystem, rm_mount_point) result['changed'], result['msg'] = remove_fs(module, filesystem, rm_mount_point)
elif state == 'mounted': elif state == 'mounted':
if ismount(filesystem): if ismount(filesystem):
result['changed'] = False result['changed'] = False
result['msg'] = "File system %s already mounted." % filesystem result['msg'] = f"File system {filesystem} already mounted."
else: else:
result['changed'], result['msg'] = mount_fs(module, filesystem) result['changed'], result['msg'] = mount_fs(module, filesystem)
elif state == 'unmounted': elif state == 'unmounted':
if not ismount(filesystem): if not ismount(filesystem):
result['changed'] = False result['changed'] = False
result['msg'] = "File system %s already unmounted." % filesystem result['msg'] = f"File system {filesystem} already unmounted."
else: else:
result['changed'], result['msg'] = unmount_fs(module, filesystem) result['changed'], result['msg'] = unmount_fs(module, filesystem)
else: else:
# Unreachable codeblock # Unreachable codeblock
result['msg'] = "Unexpected state %s." % state result['msg'] = f"Unexpected state {state}."
module.fail_json(**result) module.fail_json(**result)
module.exit_json(**result) module.exit_json(**result)

View file

@ -182,8 +182,7 @@ def main():
if module.params['state'] == 'present': if module.params['state'] == 'present':
# create new entry string # create new entry string
new_entry = module.params['name'] + ":" + module.params['runlevel'] + \ new_entry = f"{module.params['name']}:{module.params['runlevel']}:{module.params['action']}:{module.params['command']}"
":" + module.params['action'] + ":" + module.params['command']
# If current entry exists or fields are different(if the entry does not # If current entry exists or fields are different(if the entry does not
# exists, then the entry will be created # exists, then the entry will be created
@ -199,7 +198,7 @@ def main():
if rc != 0: if rc != 0:
module.fail_json( module.fail_json(
msg="could not change inittab", rc=rc, err=err) msg="could not change inittab", rc=rc, err=err)
result['msg'] = "changed inittab entry" + " " + current_entry['name'] result['msg'] = f"changed inittab entry {current_entry['name']}"
result['changed'] = True result['changed'] = True
# If the entry does not exist create the entry # If the entry does not exist create the entry
@ -215,7 +214,7 @@ def main():
if rc != 0: if rc != 0:
module.fail_json(msg="could not adjust inittab", rc=rc, err=err) module.fail_json(msg="could not adjust inittab", rc=rc, err=err)
result['msg'] = "add inittab entry" + " " + module.params['name'] result['msg'] = f"add inittab entry {module.params['name']}"
result['changed'] = True result['changed'] = True
elif module.params['state'] == 'absent': elif module.params['state'] == 'absent':
@ -227,7 +226,7 @@ def main():
if rc != 0: if rc != 0:
module.fail_json( module.fail_json(
msg="could not remove entry from inittab)", rc=rc, err=err) msg="could not remove entry from inittab)", rc=rc, err=err)
result['msg'] = "removed inittab entry" + " " + current_entry['name'] result['msg'] = f"removed inittab entry {current_entry['name']}"
result['changed'] = True result['changed'] = True
module.exit_json(**result) module.exit_json(**result)

View file

@ -115,27 +115,27 @@ def _validate_pv(module, vg, pvs):
# Check if pv exists and is free. # Check if pv exists and is free.
if pv not in lspv_list.keys(): if pv not in lspv_list.keys():
module.fail_json(msg="Physical volume '%s' doesn't exist." % pv) module.fail_json(msg=f"Physical volume '{pv}' doesn't exist.")
if lspv_list[pv] == 'None': if lspv_list[pv] == 'None':
# Disk None, looks free. # Disk None, looks free.
# Check if PV is not already in use by Oracle ASM. # Check if PV is not already in use by Oracle ASM.
lquerypv_cmd = module.get_bin_path('lquerypv', True) lquerypv_cmd = module.get_bin_path('lquerypv', True)
rc, current_lquerypv, stderr = module.run_command([lquerypv_cmd, "-h", "/dev/%s" % pv, "20", "10"]) rc, current_lquerypv, stderr = module.run_command([lquerypv_cmd, "-h", f"/dev/{pv}", "20", "10"])
if rc != 0: if rc != 0:
module.fail_json(msg="Failed executing lquerypv command.", rc=rc, stdout=current_lquerypv, stderr=stderr) module.fail_json(msg="Failed executing lquerypv command.", rc=rc, stdout=current_lquerypv, stderr=stderr)
if 'ORCLDISK' in current_lquerypv: if 'ORCLDISK' in current_lquerypv:
module.fail_json("Physical volume '%s' is already used by Oracle ASM." % pv) module.fail_json(f"Physical volume '{pv}' is already used by Oracle ASM.")
msg = "Physical volume '%s' is ok to be used." % pv msg = f"Physical volume '{pv}' is ok to be used."
return True, msg return True, msg
# Check if PV is already in use for the same vg. # Check if PV is already in use for the same vg.
elif vg != lspv_list[pv]: elif vg != lspv_list[pv]:
module.fail_json(msg="Physical volume '%s' is in use by another volume group '%s'." % (pv, lspv_list[pv])) module.fail_json(msg=f"Physical volume '{pv}' is in use by another volume group '{lspv_list[pv]}'.")
msg = "Physical volume '%s' is already used by volume group '%s'." % (pv, lspv_list[pv]) msg = f"Physical volume '{pv}' is already used by volume group '{lspv_list[pv]}'."
return False, msg return False, msg
@ -151,21 +151,21 @@ def _validate_vg(module, vg):
lsvg_cmd = module.get_bin_path('lsvg', True) lsvg_cmd = module.get_bin_path('lsvg', True)
rc, current_active_vgs, err = module.run_command([lsvg_cmd, "-o"]) rc, current_active_vgs, err = module.run_command([lsvg_cmd, "-o"])
if rc != 0: if rc != 0:
module.fail_json(msg="Failed executing '%s' command." % lsvg_cmd) module.fail_json(msg=f"Failed executing '{lsvg_cmd}' command.")
rc, current_all_vgs, err = module.run_command([lsvg_cmd]) rc, current_all_vgs, err = module.run_command([lsvg_cmd])
if rc != 0: if rc != 0:
module.fail_json(msg="Failed executing '%s' command." % lsvg_cmd) module.fail_json(msg=f"Failed executing '{lsvg_cmd}' command.")
if vg in current_all_vgs and vg not in current_active_vgs: if vg in current_all_vgs and vg not in current_active_vgs:
msg = "Volume group '%s' is in varyoff state." % vg msg = f"Volume group '{vg}' is in varyoff state."
return False, msg return False, msg
if vg in current_active_vgs: if vg in current_active_vgs:
msg = "Volume group '%s' is in varyon state." % vg msg = f"Volume group '{vg}' is in varyon state."
return True, msg return True, msg
msg = "Volume group '%s' does not exist." % vg msg = f"Volume group '{vg}' does not exist."
return None, msg return None, msg
@ -205,10 +205,10 @@ def create_extend_vg(module, vg, pvs, pp_size, vg_type, force, vg_validation):
rc, output, err = module.run_command([extendvg_cmd, vg] + pvs) rc, output, err = module.run_command([extendvg_cmd, vg] + pvs)
if rc != 0: if rc != 0:
changed = False changed = False
msg = "Extending volume group '%s' has failed." % vg msg = f"Extending volume group '{vg}' has failed."
return changed, msg return changed, msg
msg = "Volume group '%s' extended." % vg msg = f"Volume group '{vg}' extended."
return changed, msg return changed, msg
elif vg_state is None: elif vg_state is None:
@ -221,10 +221,10 @@ def create_extend_vg(module, vg, pvs, pp_size, vg_type, force, vg_validation):
rc, output, err = module.run_command([mkvg_cmd, vg_opt[vg_type], pp_size, force_opt[force], "-y", vg] + pvs) rc, output, err = module.run_command([mkvg_cmd, vg_opt[vg_type], pp_size, force_opt[force], "-y", vg] + pvs)
if rc != 0: if rc != 0:
changed = False changed = False
msg = "Creating volume group '%s' failed." % vg msg = f"Creating volume group '{vg}' failed."
return changed, msg return changed, msg
msg = "Volume group '%s' created." % vg msg = f"Volume group '{vg}' created."
return changed, msg return changed, msg
@ -246,16 +246,16 @@ def reduce_vg(module, vg, pvs, vg_validation):
lsvg_cmd = module.get_bin_path('lsvg', True) lsvg_cmd = module.get_bin_path('lsvg', True)
rc, current_pvs, err = module.run_command([lsvg_cmd, "-p", vg]) rc, current_pvs, err = module.run_command([lsvg_cmd, "-p", vg])
if rc != 0: if rc != 0:
module.fail_json(msg="Failing to execute '%s' command." % lsvg_cmd) module.fail_json(msg=f"Failing to execute '{lsvg_cmd}' command.")
pvs_to_remove = [] pvs_to_remove = []
for line in current_pvs.splitlines()[2:]: for line in current_pvs.splitlines()[2:]:
pvs_to_remove.append(line.split()[0]) pvs_to_remove.append(line.split()[0])
reduce_msg = "Volume group '%s' removed." % vg reduce_msg = f"Volume group '{vg}' removed."
else: else:
pvs_to_remove = pvs pvs_to_remove = pvs
reduce_msg = ("Physical volume(s) '%s' removed from Volume group '%s'." % (' '.join(pvs_to_remove), vg)) reduce_msg = f"Physical volume(s) '{' '.join(pvs_to_remove)}' removed from Volume group '{vg}'."
# Reduce volume group. # Reduce volume group.
if len(pvs_to_remove) <= 0: if len(pvs_to_remove) <= 0:
@ -270,7 +270,7 @@ def reduce_vg(module, vg, pvs, vg_validation):
reducevg_cmd = module.get_bin_path('reducevg', True) reducevg_cmd = module.get_bin_path('reducevg', True)
rc, stdout, stderr = module.run_command([reducevg_cmd, "-df", vg] + pvs_to_remove) rc, stdout, stderr = module.run_command([reducevg_cmd, "-df", vg] + pvs_to_remove)
if rc != 0: if rc != 0:
module.fail_json(msg="Unable to remove '%s'." % vg, rc=rc, stdout=stdout, stderr=stderr) module.fail_json(msg=f"Unable to remove '{vg}'.", rc=rc, stdout=stdout, stderr=stderr)
msg = reduce_msg msg = reduce_msg
return changed, msg return changed, msg
@ -295,7 +295,7 @@ def state_vg(module, vg, state, vg_validation):
if rc != 0: if rc != 0:
module.fail_json(msg="Command 'varyonvg' failed.", rc=rc, err=err) module.fail_json(msg="Command 'varyonvg' failed.", rc=rc, err=err)
msg = "Varyon volume group %s completed." % vg msg = f"Varyon volume group {vg} completed."
return changed, msg return changed, msg
elif state == 'varyoff': elif state == 'varyoff':
@ -312,7 +312,7 @@ def state_vg(module, vg, state, vg_validation):
if rc != 0: if rc != 0:
module.fail_json(msg="Command 'varyoffvg' failed.", rc=rc, stdout=varyonvg_out, stderr=stderr) module.fail_json(msg="Command 'varyoffvg' failed.", rc=rc, stdout=varyonvg_out, stderr=stderr)
msg = "Varyoff volume group %s completed." % vg msg = f"Varyoff volume group {vg} completed."
return changed, msg return changed, msg
@ -339,7 +339,7 @@ def main():
if pp_size is None: if pp_size is None:
pp_size = '' pp_size = ''
else: else:
pp_size = "-s %s" % pp_size pp_size = f"-s {pp_size}"
vg_validation = _validate_vg(module, vg) vg_validation = _validate_vg(module, vg)

View file

@ -257,9 +257,9 @@ def main():
if rc != 0: if rc != 0:
if state == 'absent': if state == 'absent':
module.exit_json(changed=False, msg="Volume group %s does not exist." % vg) module.exit_json(changed=False, msg=f"Volume group {vg} does not exist.")
else: else:
module.fail_json(msg="Volume group %s does not exist." % vg, rc=rc, out=vg_info, err=err) module.fail_json(msg=f"Volume group {vg} does not exist.", rc=rc, out=vg_info, err=err)
this_vg = parse_vg(vg_info) this_vg = parse_vg(vg_info)
@ -272,7 +272,7 @@ def main():
if rc != 0: if rc != 0:
if state == 'absent': if state == 'absent':
module.exit_json(changed=False, msg="Logical Volume %s does not exist." % lv) module.exit_json(changed=False, msg=f"Logical Volume {lv} does not exist.")
changed = False changed = False
@ -285,56 +285,56 @@ def main():
if this_lv is None: if this_lv is None:
if state == 'present': if state == 'present':
if lv_size > this_vg['free']: if lv_size > this_vg['free']:
module.fail_json(msg="Not enough free space in volume group %s: %s MB free." % (this_vg['name'], this_vg['free'])) module.fail_json(msg=f"Not enough free space in volume group {this_vg['name']}: {this_vg['free']} MB free.")
# create LV # create LV
mklv_cmd = module.get_bin_path("mklv", required=True) mklv_cmd = module.get_bin_path("mklv", required=True)
cmd = test_opt + [mklv_cmd, "-t", lv_type, "-y", lv, "-c", copies, "-e", lv_policy, opts, vg, "%sM" % (lv_size, )] + pvs cmd = test_opt + [mklv_cmd, "-t", lv_type, "-y", lv, "-c", copies, "-e", lv_policy, opts, vg, f"{lv_size}M"] + pvs
rc, out, err = module.run_command(cmd) rc, out, err = module.run_command(cmd)
if rc == 0: if rc == 0:
module.exit_json(changed=True, msg="Logical volume %s created." % lv) module.exit_json(changed=True, msg=f"Logical volume {lv} created.")
else: else:
module.fail_json(msg="Creating logical volume %s failed." % lv, rc=rc, out=out, err=err) module.fail_json(msg=f"Creating logical volume {lv} failed.", rc=rc, out=out, err=err)
else: else:
if state == 'absent': if state == 'absent':
# remove LV # remove LV
rmlv_cmd = module.get_bin_path("rmlv", required=True) rmlv_cmd = module.get_bin_path("rmlv", required=True)
rc, out, err = module.run_command(test_opt + [rmlv_cmd, "-f", this_lv['name']]) rc, out, err = module.run_command(test_opt + [rmlv_cmd, "-f", this_lv['name']])
if rc == 0: if rc == 0:
module.exit_json(changed=True, msg="Logical volume %s deleted." % lv) module.exit_json(changed=True, msg=f"Logical volume {lv} deleted.")
else: else:
module.fail_json(msg="Failed to remove logical volume %s." % lv, rc=rc, out=out, err=err) module.fail_json(msg=f"Failed to remove logical volume {lv}.", rc=rc, out=out, err=err)
else: else:
if this_lv['policy'] != policy: if this_lv['policy'] != policy:
# change lv allocation policy # change lv allocation policy
chlv_cmd = module.get_bin_path("chlv", required=True) chlv_cmd = module.get_bin_path("chlv", required=True)
rc, out, err = module.run_command(test_opt + [chlv_cmd, "-e", lv_policy, this_lv['name']]) rc, out, err = module.run_command(test_opt + [chlv_cmd, "-e", lv_policy, this_lv['name']])
if rc == 0: if rc == 0:
module.exit_json(changed=True, msg="Logical volume %s policy changed: %s." % (lv, policy)) module.exit_json(changed=True, msg=f"Logical volume {lv} policy changed: {policy}.")
else: else:
module.fail_json(msg="Failed to change logical volume %s policy." % lv, rc=rc, out=out, err=err) module.fail_json(msg=f"Failed to change logical volume {lv} policy.", rc=rc, out=out, err=err)
if vg != this_lv['vg']: if vg != this_lv['vg']:
module.fail_json(msg="Logical volume %s already exist in volume group %s" % (lv, this_lv['vg'])) module.fail_json(msg=f"Logical volume {lv} already exist in volume group {this_lv['vg']}")
# from here the last remaining action is to resize it, if no size parameter is passed we do nothing. # from here the last remaining action is to resize it, if no size parameter is passed we do nothing.
if not size: if not size:
module.exit_json(changed=False, msg="Logical volume %s already exist." % (lv)) module.exit_json(changed=False, msg=f"Logical volume {lv} already exist.")
# resize LV based on absolute values # resize LV based on absolute values
if int(lv_size) > this_lv['size']: if int(lv_size) > this_lv['size']:
extendlv_cmd = module.get_bin_path("extendlv", required=True) extendlv_cmd = module.get_bin_path("extendlv", required=True)
cmd = test_opt + [extendlv_cmd, lv, "%sM" % (lv_size - this_lv['size'], )] cmd = test_opt + [extendlv_cmd, lv, f"{lv_size - this_lv['size']}M"]
rc, out, err = module.run_command(cmd) rc, out, err = module.run_command(cmd)
if rc == 0: if rc == 0:
module.exit_json(changed=True, msg="Logical volume %s size extended to %sMB." % (lv, lv_size)) module.exit_json(changed=True, msg=f"Logical volume {lv} size extended to {lv_size}MB.")
else: else:
module.fail_json(msg="Unable to resize %s to %sMB." % (lv, lv_size), rc=rc, out=out, err=err) module.fail_json(msg=f"Unable to resize {lv} to {lv_size}MB.", rc=rc, out=out, err=err)
elif lv_size < this_lv['size']: elif lv_size < this_lv['size']:
module.fail_json(msg="No shrinking of Logical Volume %s permitted. Current size: %s MB" % (lv, this_lv['size'])) module.fail_json(msg=f"No shrinking of Logical Volume {lv} permitted. Current size: {this_lv['size']} MB")
else: else:
module.exit_json(changed=False, msg="Logical volume %s size is already %sMB." % (lv, lv_size)) module.exit_json(changed=False, msg=f"Logical volume {lv} size is already {lv_size}MB.")
if __name__ == '__main__': if __name__ == '__main__':

View file

@ -109,7 +109,7 @@ class AlertaInterface(object):
self.headers = {"Content-Type": "application/json"} self.headers = {"Content-Type": "application/json"}
if module.params.get('api_key', None): if module.params.get('api_key', None):
self.headers["Authorization"] = "Key %s" % module.params['api_key'] self.headers["Authorization"] = f"Key {module.params['api_key']}"
else: else:
self.headers["Authorization"] = basic_auth_header(module.params['api_username'], module.params['api_password']) self.headers["Authorization"] = basic_auth_header(module.params['api_username'], module.params['api_password'])
@ -118,28 +118,28 @@ class AlertaInterface(object):
status_code = info["status"] status_code = info["status"]
if status_code == 401: if status_code == 401:
self.module.fail_json(failed=True, response=info, msg="Unauthorized to request '%s' on '%s'" % (method, url)) self.module.fail_json(failed=True, response=info, msg=f"Unauthorized to request '{method}' on '{url}'")
elif status_code == 403: elif status_code == 403:
self.module.fail_json(failed=True, response=info, msg="Permission Denied for '%s' on '%s'" % (method, url)) self.module.fail_json(failed=True, response=info, msg=f"Permission Denied for '{method}' on '{url}'")
elif status_code == 404: elif status_code == 404:
self.module.fail_json(failed=True, response=info, msg="Not found for request '%s' on '%s'" % (method, url)) self.module.fail_json(failed=True, response=info, msg=f"Not found for request '{method}' on '{url}'")
elif status_code in (200, 201): elif status_code in (200, 201):
return self.module.from_json(response.read()) return self.module.from_json(response.read())
self.module.fail_json(failed=True, response=info, msg="Alerta API error with HTTP %d for %s" % (status_code, url)) self.module.fail_json(failed=True, response=info, msg=f"Alerta API error with HTTP {status_code} for {url}")
def get_customers(self): def get_customers(self):
url = "%s/api/customers" % self.alerta_url url = f"{self.alerta_url}/api/customers"
response = self.send_request(url) response = self.send_request(url)
pages = response["pages"] pages = response["pages"]
if pages > 1: if pages > 1:
for page in range(2, pages + 1): for page in range(2, pages + 1):
page_url = url + '?page=' + str(page) page_url = f"{url}?page={page}"
new_results = self.send_request(page_url) new_results = self.send_request(page_url)
response.update(new_results) response.update(new_results)
return response return response
def create_customer(self): def create_customer(self):
url = "%s/api/customer" % self.alerta_url url = f"{self.alerta_url}/api/customer"
payload = { payload = {
'customer': self.customer, 'customer': self.customer,
@ -151,7 +151,7 @@ class AlertaInterface(object):
return response return response
def delete_customer(self, id): def delete_customer(self, id):
url = "%s/api/customer/%s" % (self.alerta_url, id) url = f"{self.alerta_url}/api/customer/{id}"
response = self.send_request(url, None, 'DELETE') response = self.send_request(url, None, 'DELETE')
return response return response
@ -184,20 +184,20 @@ def main():
if alerta_iface.state == 'present': if alerta_iface.state == 'present':
response = alerta_iface.get_customers() response = alerta_iface.get_customers()
if alerta_iface.find_customer_id(response): if alerta_iface.find_customer_id(response):
module.exit_json(changed=False, response=response, msg="Customer %s already exists" % alerta_iface.customer) module.exit_json(changed=False, response=response, msg=f"Customer {alerta_iface.customer} already exists")
else: else:
if not module.check_mode: if not module.check_mode:
response = alerta_iface.create_customer() response = alerta_iface.create_customer()
module.exit_json(changed=True, response=response, msg="Customer %s created" % alerta_iface.customer) module.exit_json(changed=True, response=response, msg=f"Customer {alerta_iface.customer} created")
else: else:
response = alerta_iface.get_customers() response = alerta_iface.get_customers()
id = alerta_iface.find_customer_id(response) id = alerta_iface.find_customer_id(response)
if id: if id:
if not module.check_mode: if not module.check_mode:
alerta_iface.delete_customer(id) alerta_iface.delete_customer(id)
module.exit_json(changed=True, response=response, msg="Customer %s with id %s deleted" % (alerta_iface.customer, id)) module.exit_json(changed=True, response=response, msg=f"Customer {alerta_iface.customer} with id {id} deleted")
else: else:
module.exit_json(changed=False, response=response, msg="Customer %s does not exists" % alerta_iface.customer) module.exit_json(changed=False, response=response, msg=f"Customer {alerta_iface.customer} does not exists")
if __name__ == "__main__": if __name__ == "__main__":

View file

@ -674,7 +674,7 @@ def run_instance(module, ecs, exact_count):
if len(security_groups) <= 0: if len(security_groups) <= 0:
module.fail_json(msg='Expected the parameter security_groups is non-empty when create new ECS instances, aborting') module.fail_json(msg='Expected the parameter security_groups is non-empty when create new ECS instances, aborting')
client_token = "Ansible-Alicloud-{0}-{1}".format(hash(str(module.params)), str(time.time())) client_token = f"Ansible-Alicloud-{hash(str(module.params))}-{time.time()}"
try: try:
# call to create_instance method from footmark # call to create_instance method from footmark
@ -691,7 +691,7 @@ def run_instance(module, ecs, exact_count):
spot_price_limit=spot_price_limit, spot_strategy=spot_strategy, unique_suffix=unique_suffix) spot_price_limit=spot_price_limit, spot_strategy=spot_strategy, unique_suffix=unique_suffix)
except Exception as e: except Exception as e:
module.fail_json(msg='Unable to create instance, error: {0}'.format(e)) module.fail_json(msg=f'Unable to create instance, error: {e}')
return instances return instances
@ -730,7 +730,7 @@ def modify_instance(module, instance):
try: try:
return instance.modify(name=name, description=description, host_name=host_name, password=password, user_data=user_data) return instance.modify(name=name, description=description, host_name=host_name, password=password, user_data=user_data)
except Exception as e: except Exception as e:
module.fail_json(msg="Modify instance {0} attribute got an error: {1}".format(instance.id, e)) module.fail_json(msg=f"Modify instance {instance.id} attribute got an error: {e}")
def wait_for_instance_modify_charge(ecs, instance_ids, charge_type, delay=10, timeout=300): def wait_for_instance_modify_charge(ecs, instance_ids, charge_type, delay=10, timeout=300):
@ -749,7 +749,7 @@ def wait_for_instance_modify_charge(ecs, instance_ids, charge_type, delay=10, ti
timeout -= delay timeout -= delay
time.sleep(delay) time.sleep(delay)
if timeout <= 0: if timeout <= 0:
raise Exception("Timeout Error: Waiting for instance to {0}. ".format(charge_type)) raise Exception(f"Timeout Error: Waiting for instance to {charge_type}. ")
except Exception as e: except Exception as e:
raise e raise e
@ -824,8 +824,7 @@ def main():
module.fail_json(msg='The parameter instance_ids should be a list, aborting') module.fail_json(msg='The parameter instance_ids should be a list, aborting')
instances = ecs.describe_instances(zone_id=zone_id, instance_ids=instance_ids) instances = ecs.describe_instances(zone_id=zone_id, instance_ids=instance_ids)
if not instances: if not instances:
module.fail_json(msg="There are no instances in our record based on instance_ids {0}. " module.fail_json(msg=f"There are no instances in our record based on instance_ids {instance_ids}. Please check it and try again.")
"Please check it and try again.".format(instance_ids))
elif count_tag: elif count_tag:
instances = ecs.describe_instances(zone_id=zone_id, tags=eval(count_tag)) instances = ecs.describe_instances(zone_id=zone_id, tags=eval(count_tag))
elif instance_name: elif instance_name:
@ -848,7 +847,7 @@ def main():
module.exit_json(changed=changed, ids=ids, instances=[]) module.exit_json(changed=changed, ids=ids, instances=[])
except Exception as e: except Exception as e:
module.fail_json(msg='Delete instance got an error: {0}'.format(e)) module.fail_json(msg=f'Delete instance got an error: {e}')
if module.params['allocate_public_ip'] and max_bandwidth_out < 0: if module.params['allocate_public_ip'] and max_bandwidth_out < 0:
module.fail_json(msg="'max_bandwidth_out' should be greater than 0 when 'allocate_public_ip' is True.") module.fail_json(msg="'max_bandwidth_out' should be greater than 0 when 'allocate_public_ip' is True.")
@ -861,13 +860,13 @@ def main():
for i in range(0, len(instances) - count): for i in range(0, len(instances) - count):
inst = instances[len(instances) - 1] inst = instances[len(instances) - 1]
if inst.status != 'stopped' and not force: if inst.status != 'stopped' and not force:
module.fail_json(msg="That to delete instance {0} is failed results from it is running, " module.fail_json(msg=f"That to delete instance {inst.id} is failed results from it is running, "
"and please stop it or set 'force' as True.".format(inst.id)) "and please stop it or set 'force' as True.")
try: try:
if inst.terminate(force=force): if inst.terminate(force=force):
changed = True changed = True
except Exception as e: except Exception as e:
module.fail_json(msg="Delete instance {0} got an error: {1}".format(inst.id, e)) module.fail_json(msg=f"Delete instance {inst.id} got an error: {e}")
instances.pop(len(instances) - 1) instances.pop(len(instances) - 1)
else: else:
try: try:
@ -879,7 +878,7 @@ def main():
changed = True changed = True
instances.extend(new_instances) instances.extend(new_instances)
except Exception as e: except Exception as e:
module.fail_json(msg="Create new instances got an error: {0}".format(e)) module.fail_json(msg=f"Create new instances got an error: {e}")
# Security Group join/leave begin # Security Group join/leave begin
security_groups = module.params['security_groups'] security_groups = module.params['security_groups']
@ -951,7 +950,7 @@ def main():
changed = True changed = True
ids.extend(targets) ids.extend(targets)
except Exception as e: except Exception as e:
module.fail_json(msg='Start instances got an error: {0}'.format(e)) module.fail_json(msg=f'Start instances got an error: {e}')
elif state == 'stopped': elif state == 'stopped':
try: try:
targets = [] targets = []
@ -965,7 +964,7 @@ def main():
if modify_instance(module, inst): if modify_instance(module, inst):
changed = True changed = True
except Exception as e: except Exception as e:
module.fail_json(msg='Stop instances got an error: {0}'.format(e)) module.fail_json(msg=f'Stop instances got an error: {e}')
elif state == 'restarted': elif state == 'restarted':
try: try:
targets = [] targets = []
@ -977,7 +976,7 @@ def main():
changed = True changed = True
ids.extend(targets) ids.extend(targets)
except Exception as e: except Exception as e:
module.fail_json(msg='Reboot instances got an error: {0}'.format(e)) module.fail_json(msg=f'Reboot instances got an error: {e}')
tags = module.params['tags'] tags = module.params['tags']
if module.params['purge_tags']: if module.params['purge_tags']:
@ -988,7 +987,7 @@ def main():
if inst.remove_tags(tags): if inst.remove_tags(tags):
changed = True changed = True
except Exception as e: except Exception as e:
module.fail_json(msg="{0}".format(e)) module.fail_json(msg=f"{e}")
module.exit_json(changed=changed, instances=get_instances_info(ecs, ids)) module.exit_json(changed=changed, instances=get_instances_info(ecs, ids))
if tags: if tags:
@ -997,7 +996,7 @@ def main():
if inst.add_tags(tags): if inst.add_tags(tags):
changed = True changed = True
except Exception as e: except Exception as e:
module.fail_json(msg="{0}".format(e)) module.fail_json(msg=f"{e}")
module.exit_json(changed=changed, instances=get_instances_info(ecs, ids)) module.exit_json(changed=changed, instances=get_instances_info(ecs, ids))

View file

@ -222,7 +222,7 @@ class AlternativesModule(object):
def install(self): def install(self):
if not os.path.exists(self.path): if not os.path.exists(self.path):
self.module.fail_json(msg="Specified path %s does not exist" % self.path) self.module.fail_json(msg=f"Specified path {self.path} does not exist")
if not self.link: if not self.link:
self.module.fail_json(msg='Needed to install the alternative, but unable to do so as we are missing the link') self.module.fail_json(msg='Needed to install the alternative, but unable to do so as we are missing the link')
@ -235,7 +235,7 @@ class AlternativesModule(object):
cmd += [item for sublist in subcommands for item in sublist] cmd += [item for sublist in subcommands for item in sublist]
self.result['changed'] = True self.result['changed'] = True
self.messages.append("Install alternative '%s' for '%s'." % (self.path, self.name)) self.messages.append(f"Install alternative '{self.path}' for '{self.name}'.")
if not self.module.check_mode: if not self.module.check_mode:
self.module.run_command(cmd, check_rc=True) self.module.run_command(cmd, check_rc=True)
@ -256,7 +256,7 @@ class AlternativesModule(object):
def remove(self): def remove(self):
cmd = [self.UPDATE_ALTERNATIVES, '--remove', self.name, self.path] cmd = [self.UPDATE_ALTERNATIVES, '--remove', self.name, self.path]
self.result['changed'] = True self.result['changed'] = True
self.messages.append("Remove alternative '%s' from '%s'." % (self.path, self.name)) self.messages.append(f"Remove alternative '{self.path}' from '{self.name}'.")
if not self.module.check_mode: if not self.module.check_mode:
self.module.run_command(cmd, check_rc=True) self.module.run_command(cmd, check_rc=True)
@ -273,7 +273,7 @@ class AlternativesModule(object):
cmd = [self.UPDATE_ALTERNATIVES, '--set', self.name, arg] cmd = [self.UPDATE_ALTERNATIVES, '--set', self.name, arg]
self.result['changed'] = True self.result['changed'] = True
self.messages.append("Set alternative '%s' for '%s'." % (arg, self.name)) self.messages.append(f"Set alternative '{arg}' for '{self.name}'.")
if not self.module.check_mode: if not self.module.check_mode:
self.module.run_command(cmd, check_rc=True) self.module.run_command(cmd, check_rc=True)
@ -283,7 +283,7 @@ class AlternativesModule(object):
def auto(self): def auto(self):
cmd = [self.UPDATE_ALTERNATIVES, '--auto', self.name] cmd = [self.UPDATE_ALTERNATIVES, '--auto', self.name]
self.messages.append("Set alternative to auto for '%s'." % (self.name)) self.messages.append(f"Set alternative to auto for '{self.name}'.")
self.result['changed'] = True self.result['changed'] = True
if not self.module.check_mode: if not self.module.check_mode:
@ -340,7 +340,7 @@ class AlternativesModule(object):
) )
if rc != 0: if rc != 0:
self.module.debug("No current alternative found. '%s' exited with %s" % (self.UPDATE_ALTERNATIVES, rc)) self.module.debug(f"No current alternative found. '{self.UPDATE_ALTERNATIVES}' exited with {rc}")
return return
current_mode_regex = re.compile(r'\s-\s(?:status\sis\s)?(\w*)(?:\smode|.)$', re.MULTILINE) current_mode_regex = re.compile(r'\s-\s(?:status\sis\s)?(\w*)(?:\smode|.)$', re.MULTILINE)

View file

@ -169,7 +169,7 @@ class AndroidSdk(StateModuleHelper):
if not self.check_mode: if not self.check_mode:
rc, stdout, stderr = self.sdkmanager.apply_packages_changes(pending_installation, self.vars.accept_licenses) rc, stdout, stderr = self.sdkmanager.apply_packages_changes(pending_installation, self.vars.accept_licenses)
if rc != 0: if rc != 0:
self.do_raise("Could not install packages: %s" % stderr) self.do_raise(f"Could not install packages: {stderr}")
def state_absent(self): def state_absent(self):
packages = self._parse_packages() packages = self._parse_packages()
@ -179,7 +179,7 @@ class AndroidSdk(StateModuleHelper):
if not self.check_mode: if not self.check_mode:
rc, stdout, stderr = self.sdkmanager.apply_packages_changes(to_be_deleted) rc, stdout, stderr = self.sdkmanager.apply_packages_changes(to_be_deleted)
if rc != 0: if rc != 0:
self.do_raise("Could not uninstall packages: %s" % stderr) self.do_raise(f"Could not uninstall packages: {stderr}")
def state_latest(self): def state_latest(self):
packages = self._parse_packages() packages = self._parse_packages()
@ -192,7 +192,7 @@ class AndroidSdk(StateModuleHelper):
if not self.check_mode: if not self.check_mode:
rc, stdout, stderr = self.sdkmanager.apply_packages_changes(to_be_installed, self.vars.accept_licenses) rc, stdout, stderr = self.sdkmanager.apply_packages_changes(to_be_installed, self.vars.accept_licenses)
if rc != 0: if rc != 0:
self.do_raise("Could not install packages: %s" % stderr) self.do_raise(f"Could not install packages: {stderr}")
@staticmethod @staticmethod
def _map_packages_to_names(packages): def _map_packages_to_names(packages):

View file

@ -245,7 +245,7 @@ class AnsibleGalaxyInstall(ModuleHelper):
line = out.splitlines()[0] line = out.splitlines()[0]
match = self._RE_GALAXY_VERSION.match(line) match = self._RE_GALAXY_VERSION.match(line)
if not match: if not match:
self.do_raise("Unable to determine ansible-galaxy version from: {0}".format(line)) self.do_raise(f"Unable to determine ansible-galaxy version from: {line}")
version = match.group("version") version = match.group("version")
return version return version

View file

@ -267,12 +267,12 @@ class BalancerMember(object):
resp, info = fetch_url(self.module, self.management_url, headers={'Referer': self.management_url}) resp, info = fetch_url(self.module, self.management_url, headers={'Referer': self.management_url})
if info['status'] != 200: if info['status'] != 200:
raise ModuleHelperException("Could not get balancer_member_page, check for connectivity! {0}".format(info)) raise ModuleHelperException(f"Could not get balancer_member_page, check for connectivity! {info}")
try: try:
soup = BeautifulSoup(resp) soup = BeautifulSoup(resp)
except TypeError as exc: except TypeError as exc:
raise ModuleHelperException("Cannot parse balancer_member_page HTML! {0}".format(exc)) from exc raise ModuleHelperException(f"Cannot parse balancer_member_page HTML! {exc}") from exc
subsoup = find_all(find_all(soup, 'table')[1], 'tr') subsoup = find_all(find_all(soup, 'table')[1], 'tr')
keys = find_all(subsoup[0], 'th') keys = find_all(subsoup[0], 'th')
@ -299,12 +299,12 @@ class BalancerMember(object):
'ignore_errors': '&w_status_I'} 'ignore_errors': '&w_status_I'}
request_body = regexp_extraction(self.management_url, EXPRESSION, 1) request_body = regexp_extraction(self.management_url, EXPRESSION, 1)
values_url = "".join("{0}={1}".format(url_param, 1 if values[mode] else 0) for mode, url_param in values_mapping.items()) values_url = "".join(f"{url_param}={1 if values[mode] else 0}" for mode, url_param in values_mapping.items())
request_body = "{0}{1}".format(request_body, values_url) request_body = f"{request_body}{values_url}"
response, info = fetch_url(self.module, self.management_url, data=request_body, headers={'Referer': self.management_url}) response, info = fetch_url(self.module, self.management_url, data=request_body, headers={'Referer': self.management_url})
if info['status'] != 200: if info['status'] != 200:
raise ModuleHelperException("Could not set the member status! {0} {1}".format(self.host, info['status'])) raise ModuleHelperException(f"Could not set the member status! {self.host} {info['status']}")
attributes = property(get_member_attributes) attributes = property(get_member_attributes)
status = property(get_member_status, set_member_status) status = property(get_member_status, set_member_status)
@ -327,8 +327,8 @@ class Balancer(object):
def __init__(self, module, host, suffix, tls=False): def __init__(self, module, host, suffix, tls=False):
proto = "https" if tls else "http" proto = "https" if tls else "http"
self.base_url = '{0}://{1}'.format(proto, host) self.base_url = f'{proto}://{host}'
self.url = '{0}://{1}{2}'.format(proto, host, suffix) self.url = f'{proto}://{host}{suffix}'
self.module = module self.module = module
self.page = self.fetch_balancer_page() self.page = self.fetch_balancer_page()
@ -336,7 +336,7 @@ class Balancer(object):
""" Returns the balancer management html page as a string for later parsing.""" """ Returns the balancer management html page as a string for later parsing."""
resp, info = fetch_url(self.module, self.url) resp, info = fetch_url(self.module, self.url)
if info['status'] != 200: if info['status'] != 200:
raise ModuleHelperException("Could not get balancer page! HTTP status response: {0}".format(info['status'])) raise ModuleHelperException(f"Could not get balancer page! HTTP status response: {info['status']}")
content = to_text(resp.read()) content = to_text(resp.read())
apache_version = regexp_extraction(content.upper(), APACHE_VERSION_EXPRESSION, 1) apache_version = regexp_extraction(content.upper(), APACHE_VERSION_EXPRESSION, 1)
@ -344,7 +344,7 @@ class Balancer(object):
raise ModuleHelperException("Could not get the Apache server version from the balancer-manager") raise ModuleHelperException("Could not get the Apache server version from the balancer-manager")
if not re.search(pattern=r"2\.4\.[\d]*", string=apache_version): if not re.search(pattern=r"2\.4\.[\d]*", string=apache_version):
raise ModuleHelperException("This module only acts on an Apache2 2.4+ instance, current Apache2 version: {0}".format(apache_version)) raise ModuleHelperException(f"This module only acts on an Apache2 2.4+ instance, current Apache2 version: {apache_version}")
return content return content
def get_balancer_members(self): def get_balancer_members(self):
@ -352,7 +352,7 @@ class Balancer(object):
try: try:
soup = BeautifulSoup(self.page) soup = BeautifulSoup(self.page)
except TypeError as e: except TypeError as e:
raise ModuleHelperException("Cannot parse balancer page HTML! {0}".format(self.page)) from e raise ModuleHelperException(f"Cannot parse balancer page HTML! {self.page}") from e
elements = find_all(soup, 'a') elements = find_all(soup, 'a')
for element in elements[1::1]: for element in elements[1::1]:
@ -413,7 +413,7 @@ class ApacheModProxy(ModuleHelper):
self.vars.member = member.as_dict() self.vars.member = member.as_dict()
if not member_exists: if not member_exists:
self.do_raise(msg='{0} is not a member of the balancer {1}!'.format(self.vars.member_host, self.vars.balancer_vhost)) self.do_raise(msg=f'{self.vars.member_host} is not a member of the balancer {self.vars.balancer_vhost}!')
def main(): def main():

View file

@ -142,7 +142,7 @@ def _module_is_enabled(module):
result, stdout, stderr = module.run_command([control_binary, "-M"]) result, stdout, stderr = module.run_command([control_binary, "-M"])
if result != 0: if result != 0:
error_msg = "Error executing %s: %s" % (control_binary, stderr) error_msg = f"Error executing {control_binary}: {stderr}"
if module.params['ignore_configcheck']: if module.params['ignore_configcheck']:
if 'AH00534' in stderr and 'mpm_' in module.params['name']: if 'AH00534' in stderr and 'mpm_' in module.params['name']:
if module.params['warn_mpm_absent']: if module.params['warn_mpm_absent']:
@ -156,7 +156,7 @@ def _module_is_enabled(module):
else: else:
module.fail_json(msg=error_msg) module.fail_json(msg=error_msg)
searchstring = ' ' + module.params['identifier'] searchstring = f" {module.params['identifier']}"
return searchstring in stdout return searchstring in stdout
@ -188,11 +188,11 @@ def create_apache_identifier(name):
if search in name: if search in name:
try: try:
rematch = reexpr.search(name) rematch = reexpr.search(name)
return rematch.group(1) + '_module' return f"{rematch.group(1)}_module"
except AttributeError: except AttributeError:
pass pass
return name + '_module' return f"{name}_module"
def _set_state(module, state): def _set_state(module, state):
@ -202,7 +202,7 @@ def _set_state(module, state):
want_enabled = state == 'present' want_enabled = state == 'present'
state_string = {'present': 'enabled', 'absent': 'disabled'}[state] state_string = {'present': 'enabled', 'absent': 'disabled'}[state]
a2mod_binary = {'present': 'a2enmod', 'absent': 'a2dismod'}[state] a2mod_binary = {'present': 'a2enmod', 'absent': 'a2dismod'}[state]
success_msg = "Module %s %s" % (name, state_string) success_msg = f"Module {name} {state_string}"
if _module_is_enabled(module) != want_enabled: if _module_is_enabled(module) != want_enabled:
if module.check_mode: if module.check_mode:
@ -210,7 +210,7 @@ def _set_state(module, state):
a2mod_binary_path = module.get_bin_path(a2mod_binary) a2mod_binary_path = module.get_bin_path(a2mod_binary)
if a2mod_binary_path is None: if a2mod_binary_path is None:
module.fail_json(msg="%s not found. Perhaps this system does not use %s to manage apache" % (a2mod_binary, a2mod_binary)) module.fail_json(msg=f"{a2mod_binary} not found. Perhaps this system does not use {a2mod_binary} to manage apache")
a2mod_binary_cmd = [a2mod_binary_path] a2mod_binary_cmd = [a2mod_binary_path]
@ -224,15 +224,10 @@ def _set_state(module, state):
module.exit_json(changed=True, result=success_msg) module.exit_json(changed=True, result=success_msg)
else: else:
msg = ( msg = (
'Failed to set module {name} to {state}:\n' f'Failed to set module {name} to {state_string}:\n'
'{stdout}\n' f'{stdout}\n'
'Maybe the module identifier ({identifier}) was guessed incorrectly.' f'Maybe the module identifier ({module.params["identifier"]}) was guessed incorrectly.'
'Consider setting the "identifier" option.' 'Consider setting the "identifier" option.'
).format(
name=name,
state=state_string,
stdout=stdout,
identifier=module.params['identifier']
) )
module.fail_json(msg=msg, module.fail_json(msg=msg,
rc=result, rc=result,

View file

@ -195,7 +195,7 @@ def update_package_db(module, exit):
def query_toplevel(module, name, world): def query_toplevel(module, name, world):
# world contains a list of top-level packages separated by ' ' or \n # world contains a list of top-level packages separated by ' ' or \n
# packages may contain repository (@) or version (=<>~) separator characters or start with negation ! # packages may contain repository (@) or version (=<>~) separator characters or start with negation !
regex = re.compile(r'^' + re.escape(name) + r'([@=<>~].+)?$') regex = re.compile(rf"^{re.escape(name)}([@=<>~].+)?$")
with open(world) as f: with open(world) as f:
content = f.read().split() content = f.read().split()
for p in content: for p in content:
@ -216,7 +216,7 @@ def query_package(module, name):
def query_latest(module, name): def query_latest(module, name):
cmd = APK_PATH + ["version", name] cmd = APK_PATH + ["version", name]
rc, stdout, stderr = module.run_command(cmd, check_rc=False) rc, stdout, stderr = module.run_command(cmd, check_rc=False)
search_pattern = r"(%s)-[\d\.\w]+-[\d\w]+\s+(.)\s+[\d\.\w]+-[\d\w]+\s+" % (re.escape(name)) search_pattern = rf"({re.escape(name)})-[\d\.\w]+-[\d\w]+\s+(.)\s+[\d\.\w]+-[\d\w]+\s+"
match = re.search(search_pattern, stdout) match = re.search(search_pattern, stdout)
if match and match.group(2) == "<": if match and match.group(2) == "<":
return False return False
@ -226,7 +226,7 @@ def query_latest(module, name):
def query_virtual(module, name): def query_virtual(module, name):
cmd = APK_PATH + ["-v", "info", "--description", name] cmd = APK_PATH + ["-v", "info", "--description", name]
rc, stdout, stderr = module.run_command(cmd, check_rc=False) rc, stdout, stderr = module.run_command(cmd, check_rc=False)
search_pattern = r"^%s: virtual meta package" % (re.escape(name)) search_pattern = rf"^{re.escape(name)}: virtual meta package"
if re.search(search_pattern, stdout): if re.search(search_pattern, stdout):
return True return True
return False return False
@ -293,8 +293,8 @@ def install_packages(module, names, state, world):
rc, stdout, stderr = module.run_command(cmd, check_rc=False) rc, stdout, stderr = module.run_command(cmd, check_rc=False)
packagelist = parse_for_packages(stdout) packagelist = parse_for_packages(stdout)
if rc != 0: if rc != 0:
module.fail_json(msg="failed to install %s" % (packages), stdout=stdout, stderr=stderr, packages=packagelist) module.fail_json(msg=f"failed to install {packages}", stdout=stdout, stderr=stderr, packages=packagelist)
module.exit_json(changed=True, msg="installed %s package(s)" % (packages), stdout=stdout, stderr=stderr, packages=packagelist) module.exit_json(changed=True, msg=f"installed {packages} package(s)", stdout=stdout, stderr=stderr, packages=packagelist)
def remove_packages(module, names): def remove_packages(module, names):
@ -317,8 +317,8 @@ def remove_packages(module, names):
rc = 1 rc = 1
break break
if rc != 0: if rc != 0:
module.fail_json(msg="failed to remove %s package(s)" % (names), stdout=stdout, stderr=stderr, packages=packagelist) module.fail_json(msg=f"failed to remove {names} package(s)", stdout=stdout, stderr=stderr, packages=packagelist)
module.exit_json(changed=True, msg="removed %s package(s)" % (names), stdout=stdout, stderr=stderr, packages=packagelist) module.exit_json(changed=True, msg=f"removed {names} package(s)", stdout=stdout, stderr=stderr, packages=packagelist)
# ========================================== # ==========================================
# Main control flow. # Main control flow.

View file

@ -85,7 +85,7 @@ def apt_repo(module, *args):
rc, out, err = module.run_command([APT_REPO_PATH] + args) rc, out, err = module.run_command([APT_REPO_PATH] + args)
if rc != 0: if rc != 0:
module.fail_json(msg="'%s' failed: %s" % (' '.join(['apt-repo'] + args), err)) module.fail_json(msg=f"'{' '.join(['apt-repo'] + args)}' failed: {err}")
return out return out

View file

@ -251,12 +251,12 @@ def remove_packages(module, packages):
rc, out, err = module.run_command([APT_PATH, "-y", "remove", package], environ_update={"LANG": "C"}) rc, out, err = module.run_command([APT_PATH, "-y", "remove", package], environ_update={"LANG": "C"})
if rc != 0: if rc != 0:
module.fail_json(msg="failed to remove %s: %s" % (package, err)) module.fail_json(msg=f"failed to remove {package}: {err}")
remove_c += 1 remove_c += 1
if remove_c > 0: if remove_c > 0:
return (True, "removed %s package(s)" % remove_c) return (True, f"removed {remove_c} package(s)")
return (False, "package(s) already absent") return (False, "package(s) already absent")
@ -282,9 +282,9 @@ def install_packages(module, pkgspec, allow_upgrade=False):
# apt-rpm always have 0 for exit code if --force is used # apt-rpm always have 0 for exit code if --force is used
if rc or not installed: if rc or not installed:
module.fail_json(msg="'%s' failed: %s" % (" ".join(command), err)) module.fail_json(msg=f"'{' '.join(command)}' failed: {err}")
else: else:
return (True, "%s present(s)" % packages) return (True, f"{packages} present(s)")
else: else:
return (False, "Nothing to install") return (False, "Nothing to install")

View file

@ -305,7 +305,7 @@ class Archive(object, metaclass=abc.ABCMeta):
if self.contains(_to_native(archive_name)): if self.contains(_to_native(archive_name)):
self.successes.append(path) self.successes.append(path)
except Exception as e: except Exception as e:
self.errors.append('%s: %s' % (_to_native_ascii(path), _to_native(e))) self.errors.append(f'{_to_native_ascii(path)}: {e}')
def add_single_target(self, path): def add_single_target(self, path):
if self.format in ('zip', 'tar'): if self.format in ('zip', 'tar'):
@ -325,7 +325,7 @@ class Archive(object, metaclass=abc.ABCMeta):
self.module.fail_json( self.module.fail_json(
path=_to_native(path), path=_to_native(path),
dest=_to_native(self.destination), dest=_to_native(self.destination),
msg='Unable to write to compressed file: %s' % _to_native(e), exception=format_exc() msg=f'Unable to write to compressed file: {e}', exception=format_exc()
) )
def add_targets(self): def add_targets(self):
@ -347,18 +347,16 @@ class Archive(object, metaclass=abc.ABCMeta):
if self.format in ('zip', 'tar'): if self.format in ('zip', 'tar'):
archive_format = self.format archive_format = self.format
else: else:
archive_format = 'tar.' + self.format archive_format = f"tar.{self.format}"
self.module.fail_json( self.module.fail_json(
msg='Error when writing %s archive at %s: %s' % ( msg=f'Error when writing {archive_format} archive at {_to_native(self.destination)}: {e}',
archive_format, _to_native(self.destination), _to_native(e)
),
exception=format_exc() exception=format_exc()
) )
self.close() self.close()
if self.errors: if self.errors:
self.module.fail_json( self.module.fail_json(
msg='Errors when writing archive at %s: %s' % (_to_native(self.destination), '; '.join(self.errors)) msg=f"Errors when writing archive at {_to_native(self.destination)}: {'; '.join(self.errors)}"
) )
def is_different_from_original(self): def is_different_from_original(self):
@ -400,7 +398,7 @@ class Archive(object, metaclass=abc.ABCMeta):
except OSError as e: except OSError as e:
self.module.fail_json( self.module.fail_json(
path=_to_native(path), path=_to_native(path),
msg='Unable to remove source file: %s' % _to_native(e), exception=format_exc() msg=f'Unable to remove source file: {e}', exception=format_exc()
) )
def remove_targets(self): def remove_targets(self):
@ -459,7 +457,7 @@ class Archive(object, metaclass=abc.ABCMeta):
elif self.format == 'xz': elif self.format == 'xz':
f = lzma.LZMAFile(path, mode) f = lzma.LZMAFile(path, mode)
else: else:
self.module.fail_json(msg="%s is not a valid format" % self.format) self.module.fail_json(msg=f"{self.format} is not a valid format")
return f return f
@ -536,7 +534,7 @@ class TarArchive(Archive):
def open(self): def open(self):
if self.format in ('gz', 'bz2'): if self.format in ('gz', 'bz2'):
self.file = tarfile.open(_to_native_ascii(self.destination), 'w|' + self.format) self.file = tarfile.open(_to_native_ascii(self.destination), f"w|{self.format}")
# python3 tarfile module allows xz format but for python2 we have to create the tarfile # python3 tarfile module allows xz format but for python2 we have to create the tarfile
# in memory and then compress it with lzma. # in memory and then compress it with lzma.
elif self.format == 'xz': elif self.format == 'xz':
@ -545,7 +543,7 @@ class TarArchive(Archive):
elif self.format == 'tar': elif self.format == 'tar':
self.file = tarfile.open(_to_native_ascii(self.destination), 'w') self.file = tarfile.open(_to_native_ascii(self.destination), 'w')
else: else:
self.module.fail_json(msg="%s is not a valid archive format" % self.format) self.module.fail_json(msg=f"{self.format} is not a valid archive format")
def _add(self, path, archive_name): def _add(self, path, archive_name):
def filter(tarinfo): def filter(tarinfo):
@ -563,7 +561,7 @@ class TarArchive(Archive):
checksums = set((info.name, info.chksum) for info in archive.getmembers()) checksums = set((info.name, info.chksum) for info in archive.getmembers())
archive.close() archive.close()
else: else:
archive = tarfile.open(_to_native_ascii(path), 'r|' + self.format) archive = tarfile.open(_to_native_ascii(path), f"r|{self.format}")
checksums = set((info.name, info.chksum) for info in archive.getmembers()) checksums = set((info.name, info.chksum) for info in archive.getmembers())
archive.close() archive.close()
except (LZMAError, tarfile.ReadError, tarfile.CompressionError): except (LZMAError, tarfile.ReadError, tarfile.CompressionError):

View file

@ -71,7 +71,7 @@ from ansible.module_utils.basic import AnsibleModule
def activate(module): def activate(module):
cmd = "%s activate --force" % (AWALL_PATH) cmd = f"{AWALL_PATH} activate --force"
rc, stdout, stderr = module.run_command(cmd) rc, stdout, stderr = module.run_command(cmd)
if rc == 0: if rc == 0:
return True return True
@ -80,9 +80,9 @@ def activate(module):
def is_policy_enabled(module, name): def is_policy_enabled(module, name):
cmd = "%s list" % (AWALL_PATH) cmd = f"{AWALL_PATH} list"
rc, stdout, stderr = module.run_command(cmd) rc, stdout, stderr = module.run_command(cmd)
if re.search(r"^%s\s+enabled" % name, stdout, re.MULTILINE): if re.search(rf"^{name}\s+enabled", stdout, re.MULTILINE):
return True return True
return False return False
@ -96,15 +96,15 @@ def enable_policy(module, names, act):
module.exit_json(changed=False, msg="policy(ies) already enabled") module.exit_json(changed=False, msg="policy(ies) already enabled")
names = " ".join(policies) names = " ".join(policies)
if module.check_mode: if module.check_mode:
cmd = "%s list" % (AWALL_PATH) cmd = f"{AWALL_PATH} list"
else: else:
cmd = "%s enable %s" % (AWALL_PATH, names) cmd = f"{AWALL_PATH} enable {names}"
rc, stdout, stderr = module.run_command(cmd) rc, stdout, stderr = module.run_command(cmd)
if rc != 0: if rc != 0:
module.fail_json(msg="failed to enable %s" % names, stdout=stdout, stderr=stderr) module.fail_json(msg=f"failed to enable {names}", stdout=stdout, stderr=stderr)
if act and not module.check_mode: if act and not module.check_mode:
activate(module) activate(module)
module.exit_json(changed=True, msg="enabled awall policy(ies): %s" % names) module.exit_json(changed=True, msg=f"enabled awall policy(ies): {names}")
def disable_policy(module, names, act): def disable_policy(module, names, act):
@ -116,15 +116,15 @@ def disable_policy(module, names, act):
module.exit_json(changed=False, msg="policy(ies) already disabled") module.exit_json(changed=False, msg="policy(ies) already disabled")
names = " ".join(policies) names = " ".join(policies)
if module.check_mode: if module.check_mode:
cmd = "%s list" % (AWALL_PATH) cmd = f"{AWALL_PATH} list"
else: else:
cmd = "%s disable %s" % (AWALL_PATH, names) cmd = f"{AWALL_PATH} disable {names}"
rc, stdout, stderr = module.run_command(cmd) rc, stdout, stderr = module.run_command(cmd)
if rc != 0: if rc != 0:
module.fail_json(msg="failed to disable %s" % names, stdout=stdout, stderr=stderr) module.fail_json(msg=f"failed to disable {names}", stdout=stdout, stderr=stderr)
if act and not module.check_mode: if act and not module.check_mode:
activate(module) activate(module)
module.exit_json(changed=True, msg="disabled awall policy(ies): %s" % names) module.exit_json(changed=True, msg=f"disabled awall policy(ies): {names}")
def main(): def main():