diff --git a/changelogs/fragments/10942-mod-fstr-bc.yml b/changelogs/fragments/10942-mod-fstr-bc.yml
new file mode 100644
index 0000000000..dcb56045f2
--- /dev/null
+++ b/changelogs/fragments/10942-mod-fstr-bc.yml
@@ -0,0 +1,31 @@
+minor_changes:
+ - beadm - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - bigpanda - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - bitbucket_access_key - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - bitbucket_pipeline_key_pair - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - bitbucket_pipeline_known_host - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - bitbucket_pipeline_variable - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - bower - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - btrfs_subvolume - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - campfire - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - capabilities - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - cargo - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - catapult - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - circonus_annotation - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - cisco_webex - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - cloud_init_data_facts - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - cloudflare_dns - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - cobbler_sync - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - cobbler_system - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - composer - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - consul - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - consul_agent_check - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - consul_agent_service - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - consul_auth_method - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - consul_binding_rule - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - consul_kv - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - consul_session - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - copr - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - cpanm - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - cronvar - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
+ - crypttab - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10945).
diff --git a/plugins/modules/beadm.py b/plugins/modules/beadm.py
index f285616ca7..3fa9e0b4cc 100644
--- a/plugins/modules/beadm.py
+++ b/plugins/modules/beadm.py
@@ -329,7 +329,7 @@ def main():
(rc, out, err) = be.destroy_be()
if rc != 0:
- module.fail_json(msg='Error while destroying BE: "%s"' % err,
+ module.fail_json(msg=f'Error while destroying BE: "{err}"',
name=be.name,
stderr=err,
rc=rc)
@@ -344,7 +344,7 @@ def main():
(rc, out, err) = be.create_be()
if rc != 0:
- module.fail_json(msg='Error while creating BE: "%s"' % err,
+ module.fail_json(msg=f'Error while creating BE: "{err}"',
name=be.name,
stderr=err,
rc=rc)
@@ -363,7 +363,7 @@ def main():
(rc, out, err) = be.activate_be()
if rc != 0:
- module.fail_json(msg='Error while activating BE: "%s"' % err,
+ module.fail_json(msg=f'Error while activating BE: "{err}"',
name=be.name,
stderr=err,
rc=rc)
@@ -375,7 +375,7 @@ def main():
(rc, out, err) = be.mount_be()
if rc != 0:
- module.fail_json(msg='Error while mounting BE: "%s"' % err,
+ module.fail_json(msg=f'Error while mounting BE: "{err}"',
name=be.name,
stderr=err,
rc=rc)
@@ -388,7 +388,7 @@ def main():
(rc, out, err) = be.unmount_be()
if rc != 0:
- module.fail_json(msg='Error while unmounting BE: "%s"' % err,
+ module.fail_json(msg=f'Error while unmounting BE: "{err}"',
name=be.name,
stderr=err,
rc=rc)
diff --git a/plugins/modules/bigpanda.py b/plugins/modules/bigpanda.py
index 1bdd79d548..0f8ffad456 100644
--- a/plugins/modules/bigpanda.py
+++ b/plugins/modules/bigpanda.py
@@ -183,7 +183,7 @@ def main():
if v is not None:
body[k] = v
- request_url = url + '/data/events/deployments/start'
+ request_url = f"{url}/data/events/deployments/start"
else:
message = module.params['deployment_message']
if message is not None:
@@ -194,7 +194,7 @@ def main():
else:
body['status'] = 'failure'
- request_url = url + '/data/events/deployments/end'
+ request_url = f"{url}/data/events/deployments/end"
# Build the deployment object we return
deployment = dict(token=token, url=url)
@@ -209,7 +209,7 @@ def main():
# Send the data to bigpanda
data = json.dumps(body)
- headers = {'Authorization': 'Bearer %s' % token, 'Content-Type': 'application/json'}
+ headers = {'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'}
try:
response, info = fetch_url(module, request_url, data=data, headers=headers)
if info['status'] == 200:
diff --git a/plugins/modules/bitbucket_access_key.py b/plugins/modules/bitbucket_access_key.py
index 2b2bf9b8c5..88a9506805 100644
--- a/plugins/modules/bitbucket_access_key.py
+++ b/plugins/modules/bitbucket_access_key.py
@@ -153,7 +153,7 @@ def get_existing_deploy_key(module, bitbucket):
module.fail_json(msg=error_messages['required_permission'])
if info['status'] != 200:
- module.fail_json(msg='Failed to retrieve the list of deploy keys: {0}'.format(info))
+ module.fail_json(msg=f'Failed to retrieve the list of deploy keys: {info}')
res = next((v for v in content['values'] if v['label'] == module.params['label']), None)
@@ -186,10 +186,7 @@ def create_deploy_key(module, bitbucket):
module.fail_json(msg=error_messages['invalid_key'])
if info['status'] != 200:
- module.fail_json(msg='Failed to create deploy key `{label}`: {info}'.format(
- label=module.params['label'],
- info=info,
- ))
+ module.fail_json(msg=f"Failed to create deploy key `{module.params['label']}`: {info}")
def delete_deploy_key(module, bitbucket, key_id):
@@ -209,10 +206,7 @@ def delete_deploy_key(module, bitbucket, key_id):
module.fail_json(msg=error_messages['required_permission'])
if info['status'] != 204:
- module.fail_json(msg='Failed to delete deploy key `{label}`: {info}'.format(
- label=module.params['label'],
- info=info,
- ))
+ module.fail_json(msg=f"Failed to delete deploy key `{module.params['label']}`: {info}")
def main():
diff --git a/plugins/modules/bitbucket_pipeline_key_pair.py b/plugins/modules/bitbucket_pipeline_key_pair.py
index 28d837c914..e92652a36a 100644
--- a/plugins/modules/bitbucket_pipeline_key_pair.py
+++ b/plugins/modules/bitbucket_pipeline_key_pair.py
@@ -133,7 +133,7 @@ def update_ssh_key_pair(module, bitbucket):
module.fail_json(msg=error_messages['invalid_params'])
if info['status'] != 200:
- module.fail_json(msg='Failed to create or update pipeline ssh key pair : {0}'.format(info))
+ module.fail_json(msg=f'Failed to create or update pipeline ssh key pair : {info}')
def delete_ssh_key_pair(module, bitbucket):
@@ -149,7 +149,7 @@ def delete_ssh_key_pair(module, bitbucket):
module.fail_json(msg=error_messages['invalid_params'])
if info['status'] != 204:
- module.fail_json(msg='Failed to delete pipeline ssh key pair: {0}'.format(info))
+ module.fail_json(msg=f'Failed to delete pipeline ssh key pair: {info}')
def main():
diff --git a/plugins/modules/bitbucket_pipeline_known_host.py b/plugins/modules/bitbucket_pipeline_known_host.py
index fb382c8afb..259e9a6c41 100644
--- a/plugins/modules/bitbucket_pipeline_known_host.py
+++ b/plugins/modules/bitbucket_pipeline_known_host.py
@@ -149,7 +149,7 @@ def get_existing_known_host(module, bitbucket):
module.fail_json(msg='Invalid `repository` or `workspace`.')
if info['status'] != 200:
- module.fail_json(msg='Failed to retrieve list of known hosts: {0}'.format(info))
+ module.fail_json(msg=f'Failed to retrieve list of known hosts: {info}')
host = next((v for v in content['values'] if v['hostname'] == module.params['name']), None)
@@ -179,14 +179,14 @@ def get_host_key(module, hostname):
sock = socket.socket()
sock.connect((hostname, 22))
except socket.error:
- module.fail_json(msg='Error opening socket to {0}'.format(hostname))
+ module.fail_json(msg=f'Error opening socket to {hostname}')
try:
trans = paramiko.transport.Transport(sock)
trans.start_client()
host_key = trans.get_remote_server_key()
except paramiko.SSHException:
- module.fail_json(msg='SSH error on retrieving {0} server key'.format(hostname))
+ module.fail_json(msg=f'SSH error on retrieving {hostname} server key')
trans.close()
sock.close()
@@ -227,10 +227,7 @@ def create_known_host(module, bitbucket):
module.fail_json(msg=error_messages['invalid_params'])
if info['status'] != 201:
- module.fail_json(msg='Failed to create known host `{hostname}`: {info}'.format(
- hostname=module.params['hostname'],
- info=info,
- ))
+ module.fail_json(msg=f"Failed to create known host `{module.params['hostname']}`: {info}")
def delete_known_host(module, bitbucket, known_host_uuid):
@@ -247,10 +244,7 @@ def delete_known_host(module, bitbucket, known_host_uuid):
module.fail_json(msg=error_messages['invalid_params'])
if info['status'] != 204:
- module.fail_json(msg='Failed to delete known host `{hostname}`: {info}'.format(
- hostname=module.params['name'],
- info=info,
- ))
+ module.fail_json(msg=f"Failed to delete known host `{module.params['name']}`: {info}")
def main():
diff --git a/plugins/modules/bitbucket_pipeline_variable.py b/plugins/modules/bitbucket_pipeline_variable.py
index ea43beba55..67fda53e5c 100644
--- a/plugins/modules/bitbucket_pipeline_variable.py
+++ b/plugins/modules/bitbucket_pipeline_variable.py
@@ -122,7 +122,7 @@ def get_existing_pipeline_variable(module, bitbucket):
# Look through the all response pages in search of variable we need
page = 1
while True:
- next_url = "%s?page=%s" % (variables_base_url, page)
+ next_url = f"{variables_base_url}?page={page}"
info, content = bitbucket.request(
api_url=next_url,
method='GET',
@@ -132,7 +132,7 @@ def get_existing_pipeline_variable(module, bitbucket):
module.fail_json(msg='Invalid `repository` or `workspace`.')
if info['status'] != 200:
- module.fail_json(msg='Failed to retrieve the list of pipeline variables: {0}'.format(info))
+ module.fail_json(msg=f'Failed to retrieve the list of pipeline variables: {info}')
# We are at the end of list
if 'pagelen' in content and content['pagelen'] == 0:
@@ -161,10 +161,7 @@ def create_pipeline_variable(module, bitbucket):
)
if info['status'] != 201:
- module.fail_json(msg='Failed to create pipeline variable `{name}`: {info}'.format(
- name=module.params['name'],
- info=info,
- ))
+ module.fail_json(msg=f"Failed to create pipeline variable `{module.params['name']}`: {info}")
def update_pipeline_variable(module, bitbucket, variable_uuid):
@@ -182,10 +179,7 @@ def update_pipeline_variable(module, bitbucket, variable_uuid):
)
if info['status'] != 200:
- module.fail_json(msg='Failed to update pipeline variable `{name}`: {info}'.format(
- name=module.params['name'],
- info=info,
- ))
+ module.fail_json(msg=f"Failed to update pipeline variable `{module.params['name']}`: {info}")
def delete_pipeline_variable(module, bitbucket, variable_uuid):
@@ -199,10 +193,7 @@ def delete_pipeline_variable(module, bitbucket, variable_uuid):
)
if info['status'] != 204:
- module.fail_json(msg='Failed to delete pipeline variable `{name}`: {info}'.format(
- name=module.params['name'],
- info=info,
- ))
+ module.fail_json(msg=f"Failed to delete pipeline variable `{module.params['name']}`: {info}")
class BitBucketPipelineVariable(AnsibleModule):
diff --git a/plugins/modules/bower.py b/plugins/modules/bower.py
index fd4e2c4920..c1959fe74e 100644
--- a/plugins/modules/bower.py
+++ b/plugins/modules/bower.py
@@ -107,7 +107,7 @@ class Bower(object):
self.version = kwargs['version']
if kwargs['version']:
- self.name_version = self.name + '#' + self.version
+ self.name_version = f"{self.name}#{self.version}"
else:
self.name_version = self.name
@@ -118,7 +118,7 @@ class Bower(object):
if self.relative_execpath:
cmd.append(os.path.join(self.path, self.relative_execpath, "bower"))
if not os.path.isfile(cmd[-1]):
- self.module.fail_json(msg="bower not found at relative path %s" % self.relative_execpath)
+ self.module.fail_json(msg=f"bower not found at relative path {self.relative_execpath}")
else:
cmd.append("bower")
@@ -140,7 +140,7 @@ class Bower(object):
if not os.path.exists(self.path):
os.makedirs(self.path)
if not os.path.isdir(self.path):
- self.module.fail_json(msg="path %s is not a directory" % self.path)
+ self.module.fail_json(msg=f"path {self.path} is not a directory")
cwd = self.path
rc, out, err = self.module.run_command(cmd, check_rc=check_rc, cwd=cwd)
diff --git a/plugins/modules/btrfs_subvolume.py b/plugins/modules/btrfs_subvolume.py
index 92c3c99c02..8b2726d763 100644
--- a/plugins/modules/btrfs_subvolume.py
+++ b/plugins/modules/btrfs_subvolume.py
@@ -285,13 +285,13 @@ class BtrfsSubvolumeModule(object):
if not filesystem.is_mounted():
if not self.__automount:
raise BtrfsModuleException(
- "Target filesystem uuid=%s is not currently mounted and automount=False."
- "Mount explicitly before module execution or pass automount=True" % filesystem.uuid)
+ f"Target filesystem uuid={filesystem.uuid} is not currently mounted and automount=False."
+ "Mount explicitly before module execution or pass automount=True")
elif self.module.check_mode:
# TODO is failing the module an appropriate outcome in this scenario?
raise BtrfsModuleException(
- "Target filesystem uuid=%s is not currently mounted. Unable to validate the current"
- "state while running with check_mode=True" % filesystem.uuid)
+ f"Target filesystem uuid={filesystem.uuid} is not currently mounted. Unable to validate the current"
+ "state while running with check_mode=True")
else:
self.__mount_subvolume_id_to_tempdir(filesystem, self.__BTRFS_ROOT_SUBVOLUME_ID)
filesystem.refresh()
@@ -323,8 +323,7 @@ class BtrfsSubvolumeModule(object):
return filesystem
else:
raise BtrfsModuleException(
- "Failed to automatically identify targeted filesystem. "
- "No explicit device indicated and found %d available filesystems." % len(filesystems)
+ f"Failed to automatically identify targeted filesystem. No explicit device indicated and found {len(filesystems)} available filesystems."
)
# Prepare unit of work
@@ -372,10 +371,10 @@ class BtrfsSubvolumeModule(object):
# No change required
return
elif self.__snapshot_conflict == "error":
- raise BtrfsModuleException("Target subvolume=%s already exists and snapshot_conflict='error'" % self.__name)
+ raise BtrfsModuleException(f"Target subvolume={self.__name} already exists and snapshot_conflict='error'")
if source_subvolume is None:
- raise BtrfsModuleException("Source subvolume %s does not exist" % self.__snapshot_source)
+ raise BtrfsModuleException(f"Source subvolume {self.__snapshot_source} does not exist")
elif subvolume is not None and source_subvolume.id == subvolume.id:
raise BtrfsModuleException("Snapshot source and target are the same.")
else:
@@ -397,9 +396,9 @@ class BtrfsSubvolumeModule(object):
if subvolume.is_filesystem_root():
raise BtrfsModuleException("Can not delete the filesystem's root subvolume")
if not self.__recursive and len(subvolume.get_child_subvolumes()) > 0:
- raise BtrfsModuleException("Subvolume targeted for deletion %s has children and recursive=False."
+ raise BtrfsModuleException(f"Subvolume targeted for deletion {subvolume.path} has children and recursive=False."
"Either explicitly delete the child subvolumes first or pass "
- "parameter recursive=True." % subvolume.path)
+ "parameter recursive=True.")
self.__stage_required_mount(subvolume.get_parent_subvolume())
queue = self.__prepare_recursive_delete_order(subvolume) if self.__recursive else [subvolume]
@@ -407,7 +406,7 @@ class BtrfsSubvolumeModule(object):
for s in queue:
if s.is_mounted():
# TODO potentially unmount the subvolume if automount=True ?
- raise BtrfsModuleException("Can not delete mounted subvolume=%s" % s.path)
+ raise BtrfsModuleException(f"Can not delete mounted subvolume={s.path}")
if s.is_filesystem_default():
self.__stage_set_default_subvolume(self.__BTRFS_ROOT_SUBVOLUME, self.__BTRFS_ROOT_SUBVOLUME_ID)
self.__stage_delete_subvolume(s)
@@ -436,7 +435,7 @@ class BtrfsSubvolumeModule(object):
if self.__automount:
self.__required_mounts.append(subvolume)
else:
- raise BtrfsModuleException("The requested changes will require the subvolume '%s' to be mounted, but automount=False" % subvolume.path)
+ raise BtrfsModuleException(f"The requested changes will require the subvolume '{subvolume.path}' to be mounted, but automount=False")
def __stage_create_subvolume(self, subvolume_path, intermediate=False):
"""
@@ -488,7 +487,7 @@ class BtrfsSubvolumeModule(object):
elif op['action'] == self.__SET_DEFAULT_SUBVOLUME_OPERATION:
self.__execute_set_default_subvolume(op)
else:
- raise ValueError("Unknown operation type '%s'" % op['action'])
+ raise ValueError(f"Unknown operation type '{op['action']}'")
def __execute_create_subvolume(self, operation):
target_mounted_path = self.__filesystem.get_mountpath_as_child(operation['target'])
@@ -521,7 +520,7 @@ class BtrfsSubvolumeModule(object):
target_subvolume = self.__filesystem.get_subvolume_by_name(target)
if target_subvolume is None:
- raise BtrfsModuleException("Failed to find existing subvolume '%s'" % target)
+ raise BtrfsModuleException(f"Failed to find existing subvolume '{target}'")
else:
target_id = target_subvolume.id
@@ -557,9 +556,9 @@ class BtrfsSubvolumeModule(object):
# this check should be redundant
if self.module.check_mode or not self.__automount:
raise BtrfsModuleException("Unable to temporarily mount required subvolumes"
- "with automount=%s and check_mode=%s" % (self.__automount, self.module.check_mode))
+ f" with automount={self.__automount} and check_mode={self.module.check_mode}")
- cache_key = "%s:%d" % (filesystem.uuid, subvolid)
+ cache_key = f"{filesystem.uuid}:{int(subvolid)}"
# The subvolume was already mounted, so return the current path
if cache_key in self.__temporary_mounts:
return self.__temporary_mounts[cache_key]
@@ -569,7 +568,7 @@ class BtrfsSubvolumeModule(object):
self.__temporary_mounts[cache_key] = mountpoint
mount = self.module.get_bin_path("mount", required=True)
- command = [mount, "-o", "noatime,subvolid=%d" % subvolid, device, mountpoint]
+ command = [mount, "-o", f"noatime,subvolid={int(subvolid)}", device, mountpoint]
result = self.module.run_command(command, check_rc=True)
return mountpoint
@@ -609,13 +608,13 @@ class BtrfsSubvolumeModule(object):
elif action_type == self.__SET_DEFAULT_SUBVOLUME_OPERATION:
return self.__format_set_default_subvolume_result(operation)
else:
- raise ValueError("Unknown operation type '%s'" % operation['action'])
+ raise ValueError(f"Unknown operation type '{operation['action']}'")
def __format_create_subvolume_result(self, operation):
target = operation['target']
target_subvolume = self.__filesystem.get_subvolume_by_name(target)
target_id = target_subvolume.id if target_subvolume is not None else self.__UNKNOWN_SUBVOLUME_ID
- return "Created subvolume '%s' (%s)" % (target, target_id)
+ return f"Created subvolume '{target}' ({target_id})"
def __format_create_snapshot_result(self, operation):
source = operation['source']
@@ -624,12 +623,12 @@ class BtrfsSubvolumeModule(object):
target = operation['target']
target_subvolume = self.__filesystem.get_subvolume_by_name(target)
target_id = target_subvolume.id if target_subvolume is not None else self.__UNKNOWN_SUBVOLUME_ID
- return "Created snapshot '%s' (%s) from '%s' (%s)" % (target, target_id, source, source_id)
+ return f"Created snapshot '{target}' ({target_id}) from '{source}' ({source_id})"
def __format_delete_subvolume_result(self, operation):
target = operation['target']
target_id = operation['target_id']
- return "Deleted subvolume '%s' (%s)" % (target, target_id)
+ return f"Deleted subvolume '{target}' ({target_id})"
def __format_set_default_subvolume_result(self, operation):
target = operation['target']
@@ -638,7 +637,7 @@ class BtrfsSubvolumeModule(object):
else:
target_subvolume = self.__filesystem.get_subvolume_by_name(target)
target_id = target_subvolume.id if target_subvolume is not None else self.__UNKNOWN_SUBVOLUME_ID
- return "Updated default subvolume to '%s' (%s)" % (target, target_id)
+ return f"Updated default subvolume to '{target}' ({target_id})"
def run_module():
diff --git a/plugins/modules/campfire.py b/plugins/modules/campfire.py
index c1da278634..1adf61c637 100644
--- a/plugins/modules/campfire.py
+++ b/plugins/modules/campfire.py
@@ -159,7 +159,7 @@ def main():
msg = module.params["msg"]
notify = module.params["notify"]
- URI = "https://%s.campfirenow.com" % subscription
+ URI = f"https://{subscription}.campfirenow.com"
NSTR = "SoundMessage%s"
MSTR = "%s"
AGENT = "Ansible/1.2"
@@ -168,7 +168,7 @@ def main():
module.params['url_username'] = token
module.params['url_password'] = 'X'
- target_url = '%s/room/%s/speak.xml' % (URI, room)
+ target_url = f'{URI}/room/{room}/speak.xml'
headers = {'Content-Type': 'application/xml',
'User-agent': AGENT}
@@ -176,16 +176,12 @@ def main():
if notify:
response, info = fetch_url(module, target_url, data=NSTR % html_escape(notify), headers=headers)
if info['status'] not in [200, 201]:
- module.fail_json(msg="unable to send msg: '%s', campfire api"
- " returned error code: '%s'" %
- (notify, info['status']))
+ module.fail_json(msg=f"unable to send msg: '{notify}', campfire api returned error code: '{info['status']}'")
# Send the message
response, info = fetch_url(module, target_url, data=MSTR % html_escape(msg), headers=headers)
if info['status'] not in [200, 201]:
- module.fail_json(msg="unable to send msg: '%s', campfire api"
- " returned error code: '%s'" %
- (msg, info['status']))
+ module.fail_json(msg=f"unable to send msg: '{msg}', campfire api returned error code: '{info['status']}'")
module.exit_json(changed=True, room=room, msg=msg, notify=notify)
diff --git a/plugins/modules/capabilities.py b/plugins/modules/capabilities.py
index 64df086d67..3ae951994c 100644
--- a/plugins/modules/capabilities.py
+++ b/plugins/modules/capabilities.py
@@ -116,13 +116,13 @@ class CapabilitiesModule(object):
# If the file does not exist, the stderr will be (with rc == 0...):
# '/foo (No such file or directory)'
if rc != 0 or stderr != "":
- self.module.fail_json(msg="Unable to get capabilities of %s" % path, stdout=stdout.strip(), stderr=stderr)
+ self.module.fail_json(msg=f"Unable to get capabilities of {path}", stdout=stdout.strip(), stderr=stderr)
if stdout.strip() != path:
if ' =' in stdout:
# process output of an older version of libcap
caps = stdout.split(' =')[1].strip().split()
elif stdout.strip().endswith(")"): # '/foo (Error Message)'
- self.module.fail_json(msg="Unable to get capabilities of %s" % path, stdout=stdout.strip(), stderr=stderr)
+ self.module.fail_json(msg=f"Unable to get capabilities of {path}", stdout=stdout.strip(), stderr=stderr)
else:
# otherwise, we have a newer version here
# see original commit message of cap/v0.2.40-18-g177cd41 in libcap.git
@@ -145,7 +145,7 @@ class CapabilitiesModule(object):
cmd = [self.setcap_cmd, caps, path]
rc, stdout, stderr = self.module.run_command(cmd)
if rc != 0:
- self.module.fail_json(msg="Unable to set capabilities of %s" % path, stdout=stdout, stderr=stderr)
+ self.module.fail_json(msg=f"Unable to set capabilities of {path}", stdout=stdout, stderr=stderr)
else:
return stdout
@@ -158,7 +158,7 @@ class CapabilitiesModule(object):
i += 1
except Exception:
if op_required:
- self.module.fail_json(msg="Couldn't find operator (one of: %s)" % str(OPS))
+ self.module.fail_json(msg=f"Couldn't find operator (one of: {OPS})")
else:
return (cap, None, None)
op = cap[opind]
diff --git a/plugins/modules/cargo.py b/plugins/modules/cargo.py
index 3ec0012ca0..b4805dc8cc 100644
--- a/plugins/modules/cargo.py
+++ b/plugins/modules/cargo.py
@@ -145,7 +145,7 @@ class Cargo(object):
@path.setter
def path(self, path):
if path is not None and not os.path.isdir(path):
- self.module.fail_json(msg="Path %s is not a directory" % path)
+ self.module.fail_json(msg=f"Path {path} is not a directory")
self._path = path
def _exec(
@@ -208,7 +208,7 @@ class Cargo(object):
match = re.search(r'"(.+)"', data)
if not match:
self.module.fail_json(
- msg="No published version for package %s found" % name
+ msg=f"No published version for package {name} found"
)
return match.group(1)
@@ -230,8 +230,7 @@ class Cargo(object):
)
if not package:
self.module.fail_json(
- msg="Package %s not defined in source, found: %s"
- % (name, [x["name"] for x in manifest["packages"]])
+ msg=f"Package {name} not defined in source, found: {[x['name'] for x in manifest['packages']]}"
)
return package["version"]
diff --git a/plugins/modules/catapult.py b/plugins/modules/catapult.py
index 053eb4b51b..76323cfb1f 100644
--- a/plugins/modules/catapult.py
+++ b/plugins/modules/catapult.py
@@ -105,7 +105,7 @@ def send(module, src, dest, msg, media, user_id, api_token, api_secret):
Send the message
"""
AGENT = "Ansible"
- URI = "https://api.catapult.inetwork.com/v1/users/%s/messages" % user_id
+ URI = f"https://api.catapult.inetwork.com/v1/users/{user_id}/messages"
data = {'from': src, 'to': dest, 'text': msg}
if media:
data['media'] = media
diff --git a/plugins/modules/circonus_annotation.py b/plugins/modules/circonus_annotation.py
index 4d00b6fb98..cd157e2d7b 100644
--- a/plugins/modules/circonus_annotation.py
+++ b/plugins/modules/circonus_annotation.py
@@ -169,7 +169,7 @@ def check_requests_dep(module):
else:
required_version = '2.0.0'
if LooseVersion(requests.__version__) < LooseVersion(required_version):
- module.fail_json(msg="'requests' library version should be >= %s, found: %s." % (required_version, requests.__version__))
+ module.fail_json(msg=f"'requests' library version should be >= {required_version}, found: {requests.__version__}.")
def post_annotation(annotation, api_key):
diff --git a/plugins/modules/cisco_webex.py b/plugins/modules/cisco_webex.py
index bd9c148b53..82ce0a798a 100644
--- a/plugins/modules/cisco_webex.py
+++ b/plugins/modules/cisco_webex.py
@@ -129,7 +129,7 @@ def webex_msg(module):
ansible = module.params
headers = {
- 'Authorization': 'Bearer {0}'.format(ansible['personal_token']),
+ 'Authorization': f"Bearer {ansible['personal_token']}",
'content-type': 'application/json'
}
diff --git a/plugins/modules/cloud_init_data_facts.py b/plugins/modules/cloud_init_data_facts.py
index 8da427fa2e..9c3888f25f 100644
--- a/plugins/modules/cloud_init_data_facts.py
+++ b/plugins/modules/cloud_init_data_facts.py
@@ -103,7 +103,7 @@ def gather_cloud_init_data_facts(module):
filter = module.params.get('filter')
if filter is None or filter == i:
res['cloud_init_data_facts'][i] = dict()
- json_file = os.path.join(CLOUD_INIT_PATH, i + '.json')
+ json_file = os.path.join(CLOUD_INIT_PATH, f"{i}.json")
if os.path.exists(json_file):
with open(json_file, 'rb') as f:
diff --git a/plugins/modules/cloudflare_dns.py b/plugins/modules/cloudflare_dns.py
index 1398d5873a..4f775c73f5 100644
--- a/plugins/modules/cloudflare_dns.py
+++ b/plugins/modules/cloudflare_dns.py
@@ -498,15 +498,15 @@ class CloudflareAPI(object):
if self.type == 'SRV':
if (self.proto is not None) and (not self.proto.startswith('_')):
- self.proto = '_{0}'.format(self.proto)
+ self.proto = f'_{self.proto}'
if (self.service is not None) and (not self.service.startswith('_')):
- self.service = '_{0}'.format(self.service)
+ self.service = f'_{self.service}'
if self.type == 'TLSA':
if (self.proto is not None) and (not self.proto.startswith('_')):
- self.proto = '_{0}'.format(self.proto)
+ self.proto = f'_{self.proto}'
if (self.port is not None):
- self.port = '_{0}'.format(self.port)
+ self.port = f'_{self.port}'
if not self.record.endswith(self.zone):
self.record = join_str('.', self.record, self.zone)
@@ -518,7 +518,7 @@ class CloudflareAPI(object):
def _cf_simple_api_call(self, api_call, method='GET', payload=None):
if self.api_token:
headers = {
- 'Authorization': 'Bearer {0}'.format(self.api_token),
+ 'Authorization': f'Bearer {self.api_token}',
'Content-Type': 'application/json',
}
else:
@@ -532,7 +532,7 @@ class CloudflareAPI(object):
try:
data = json.dumps(payload)
except Exception as e:
- self.module.fail_json(msg="Failed to encode payload as JSON: %s " % to_native(e))
+ self.module.fail_json(msg=f"Failed to encode payload as JSON: {e} ")
resp, info = fetch_url(self.module,
self.cf_api_endpoint + api_call,
@@ -542,27 +542,27 @@ class CloudflareAPI(object):
timeout=self.timeout)
if info['status'] not in [200, 304, 400, 401, 403, 429, 405, 415]:
- self.module.fail_json(msg="Failed API call {0}; got unexpected HTTP code {1}: {2}".format(api_call, info['status'], info.get('msg')))
+ self.module.fail_json(msg=f"Failed API call {api_call}; got unexpected HTTP code {info['status']}: {info.get('msg')}")
error_msg = ''
if info['status'] == 401:
# Unauthorized
- error_msg = "API user does not have permission; Status: {0}; Method: {1}: Call: {2}".format(info['status'], method, api_call)
+ error_msg = f"API user does not have permission; Status: {info['status']}; Method: {method}: Call: {api_call}"
elif info['status'] == 403:
# Forbidden
- error_msg = "API request not authenticated; Status: {0}; Method: {1}: Call: {2}".format(info['status'], method, api_call)
+ error_msg = f"API request not authenticated; Status: {info['status']}; Method: {method}: Call: {api_call}"
elif info['status'] == 429:
# Too many requests
- error_msg = "API client is rate limited; Status: {0}; Method: {1}: Call: {2}".format(info['status'], method, api_call)
+ error_msg = f"API client is rate limited; Status: {info['status']}; Method: {method}: Call: {api_call}"
elif info['status'] == 405:
# Method not allowed
- error_msg = "API incorrect HTTP method provided; Status: {0}; Method: {1}: Call: {2}".format(info['status'], method, api_call)
+ error_msg = f"API incorrect HTTP method provided; Status: {info['status']}; Method: {method}: Call: {api_call}"
elif info['status'] == 415:
# Unsupported Media Type
- error_msg = "API request is not valid JSON; Status: {0}; Method: {1}: Call: {2}".format(info['status'], method, api_call)
+ error_msg = f"API request is not valid JSON; Status: {info['status']}; Method: {method}: Call: {api_call}"
elif info['status'] == 400:
# Bad Request
- error_msg = "API bad request; Status: {0}; Method: {1}: Call: {2}".format(info['status'], method, api_call)
+ error_msg = f"API bad request; Status: {info['status']}; Method: {method}: Call: {api_call}"
result = None
try:
@@ -580,23 +580,23 @@ class CloudflareAPI(object):
try:
result = json.loads(to_text(content, errors='surrogate_or_strict'))
except (getattr(json, 'JSONDecodeError', ValueError)) as e:
- error_msg += "; Failed to parse API response with error {0}: {1}".format(to_native(e), content)
+ error_msg += f"; Failed to parse API response with error {to_native(e)}: {content}"
# Without a valid/parsed JSON response no more error processing can be done
if result is None:
self.module.fail_json(msg=error_msg)
if 'success' not in result:
- error_msg += "; Unexpected error details: {0}".format(result.get('error'))
+ error_msg += f"; Unexpected error details: {result.get('error')}"
self.module.fail_json(msg=error_msg)
if not result['success']:
error_msg += "; Error details: "
for error in result['errors']:
- error_msg += "code: {0}, error: {1}; ".format(error['code'], error['message'])
+ error_msg += f"code: {error['code']}, error: {error['message']}; "
if 'error_chain' in error:
for chain_error in error['error_chain']:
- error_msg += "code: {0}, error: {1}; ".format(chain_error['code'], chain_error['message'])
+ error_msg += f"code: {chain_error['code']}, error: {chain_error['message']}; "
self.module.fail_json(msg=error_msg)
return result, info['status']
@@ -610,7 +610,7 @@ class CloudflareAPI(object):
pagination = result['result_info']
if pagination['total_pages'] > 1:
next_page = int(pagination['page']) + 1
- parameters = ['page={0}'.format(next_page)]
+ parameters = [f'page={next_page}']
# strip "page" parameter from call parameters (if there are any)
if '?' in api_call:
raw_api_call, query = api_call.split('?', 1)
@@ -618,7 +618,7 @@ class CloudflareAPI(object):
else:
raw_api_call = api_call
while next_page <= pagination['total_pages']:
- raw_api_call += '?{0}'.format('&'.join(parameters))
+ raw_api_call += f"?{'&'.join(parameters)}"
result, status = self._cf_simple_api_call(raw_api_call, method, payload)
data += result['result']
next_page += 1
@@ -631,10 +631,10 @@ class CloudflareAPI(object):
zones = self.get_zones(zone)
if len(zones) > 1:
- self.module.fail_json(msg="More than one zone matches {0}".format(zone))
+ self.module.fail_json(msg=f"More than one zone matches {zone}")
if len(zones) < 1:
- self.module.fail_json(msg="No zone found with name {0}".format(zone))
+ self.module.fail_json(msg=f"No zone found with name {zone}")
return zones[0]['id']
@@ -643,8 +643,8 @@ class CloudflareAPI(object):
name = self.zone
param = ''
if name:
- param = '?{0}'.format(urlencode({'name': name}))
- zones, status = self._cf_api_call('/zones{0}'.format(param))
+ param = f"?{urlencode({'name': name})}"
+ zones, status = self._cf_api_call(f'/zones{param}')
return zones
def get_dns_records(self, zone_name=None, type=None, record=None, value=''):
@@ -660,7 +660,7 @@ class CloudflareAPI(object):
value = self.value
zone_id = self._get_zone_id()
- api_call = '/zones/{0}/dns_records'.format(zone_id)
+ api_call = f'/zones/{zone_id}/dns_records'
query = {}
if type:
query['type'] = type
@@ -669,7 +669,7 @@ class CloudflareAPI(object):
if value:
query['content'] = value
if query:
- api_call += '?{0}'.format(urlencode(query))
+ api_call += f'?{urlencode(query)}'
records, status = self._cf_api_call(api_call)
return records
@@ -705,11 +705,11 @@ class CloudflareAPI(object):
if not ((rr['type'] == self.type) and (rr['name'] == search_record) and (rr['content'] == content)):
self.changed = True
if not self.module.check_mode:
- result, info = self._cf_api_call('/zones/{0}/dns_records/{1}'.format(zone_id, rr['id']), 'DELETE')
+ result, info = self._cf_api_call(f"/zones/{zone_id}/dns_records/{rr['id']}", 'DELETE')
else:
self.changed = True
if not self.module.check_mode:
- result, info = self._cf_api_call('/zones/{0}/dns_records/{1}'.format(zone_id, rr['id']), 'DELETE')
+ result, info = self._cf_api_call(f"/zones/{zone_id}/dns_records/{rr['id']}", 'DELETE')
return self.changed
def ensure_dns_record(self):
@@ -880,7 +880,7 @@ class CloudflareAPI(object):
if self.module.check_mode:
result = new_record
else:
- result, info = self._cf_api_call('/zones/{0}/dns_records/{1}'.format(zone_id, records[0]['id']), 'PUT', new_record)
+ result, info = self._cf_api_call(f"/zones/{zone_id}/dns_records/{records[0]['id']}", 'PUT', new_record)
self.changed = True
return result, self.changed
else:
@@ -888,7 +888,7 @@ class CloudflareAPI(object):
if self.module.check_mode:
result = new_record
else:
- result, info = self._cf_api_call('/zones/{0}/dns_records'.format(zone_id), 'POST', new_record)
+ result, info = self._cf_api_call(f'/zones/{zone_id}/dns_records', 'POST', new_record)
self.changed = True
return result, self.changed
diff --git a/plugins/modules/cobbler_sync.py b/plugins/modules/cobbler_sync.py
index 158f6ee3d6..e66fbe83ac 100644
--- a/plugins/modules/cobbler_sync.py
+++ b/plugins/modules/cobbler_sync.py
@@ -132,13 +132,13 @@ def main():
except xmlrpc_client.Fault as e:
module.fail_json(msg="Failed to log in to Cobbler '{url}' as '{username}'. {error}".format(url=url, error=to_text(e), **module.params))
except Exception as e:
- module.fail_json(msg="Connection to '{url}' failed. {error}".format(url=url, error=to_text(e)))
+ module.fail_json(msg=f"Connection to '{url}' failed. {e}")
if not module.check_mode:
try:
conn.sync(token)
except Exception as e:
- module.fail_json(msg="Failed to sync Cobbler. {error}".format(error=to_text(e)))
+ module.fail_json(msg=f"Failed to sync Cobbler. {e}")
elapsed = now() - start
module.exit_json(elapsed=elapsed.seconds, **result)
diff --git a/plugins/modules/cobbler_system.py b/plugins/modules/cobbler_system.py
index 80a45854c9..4a41270066 100644
--- a/plugins/modules/cobbler_system.py
+++ b/plugins/modules/cobbler_system.py
@@ -254,7 +254,7 @@ def main():
except xmlrpc_client.Fault as e:
module.fail_json(msg="Failed to log in to Cobbler '{url}' as '{username}'. {error}".format(url=url, error=to_text(e), **module.params))
except Exception as e:
- module.fail_json(msg="Connection to '{url}' failed. {error}".format(url=url, error=to_text(e), **module.params))
+ module.fail_json(msg=f"Connection to '{url}' failed. {e}")
system = getsystem(conn, name, token)
# result['system'] = system
@@ -282,13 +282,13 @@ def main():
for key, value in module.params['properties'].items():
if key not in system:
- module.warn("Property '{0}' is not a valid system property.".format(key))
+ module.warn(f"Property '{key}' is not a valid system property.")
if system[key] != value:
try:
conn.modify_system(system_id, key, value, token)
result['changed'] = True
except Exception as e:
- module.fail_json(msg="Unable to change '{0}' to '{1}'. {2}".format(key, value, e))
+ module.fail_json(msg=f"Unable to change '{key}' to '{value}'. {e}")
else:
# Create a new entry
@@ -301,7 +301,7 @@ def main():
try:
conn.modify_system(system_id, key, value, token)
except Exception as e:
- module.fail_json(msg="Unable to change '{0}' to '{1}'. {2}".format(key, value, e))
+ module.fail_json(msg=f"Unable to change '{key}' to '{value}'. {e}")
# Add interface properties
interface_properties = dict()
@@ -311,10 +311,10 @@ def main():
if key == 'name':
continue
if key not in IFPROPS_MAPPING:
- module.warn("Property '{0}' is not a valid system property.".format(key))
+ module.warn(f"Property '{key}' is not a valid system property.")
if not system or system['interfaces'][device][IFPROPS_MAPPING[key]] != value:
result['changed'] = True
- interface_properties['{0}-{1}'.format(key, device)] = value
+ interface_properties[f'{key}-{device}'] = value
if result['changed'] is True:
conn.modify_system(system_id, "modify_interface", interface_properties, token)
@@ -334,7 +334,7 @@ def main():
try:
conn.sync(token)
except Exception as e:
- module.fail_json(msg="Failed to sync Cobbler. {0}".format(to_text(e)))
+ module.fail_json(msg=f"Failed to sync Cobbler. {e}")
if state in ('absent', 'present'):
result['system'] = getsystem(conn, name, token)
diff --git a/plugins/modules/composer.py b/plugins/modules/composer.py
index 8301e3174f..b37962fec1 100644
--- a/plugins/modules/composer.py
+++ b/plugins/modules/composer.py
@@ -238,7 +238,7 @@ def main():
for option in default_options:
if option in available_options:
- option = "--%s" % option
+ option = f"--{option}"
options.append(option)
option_params = {
@@ -255,14 +255,14 @@ def main():
for param, option in option_params.items():
if module.params.get(param) and option in available_options:
- option = "--%s" % option
+ option = f"--{option}"
options.append(option)
if module.check_mode:
if 'dry-run' in available_options:
options.append('--dry-run')
else:
- module.exit_json(skipped=True, msg="command '%s' does not support check mode, skipping" % command)
+ module.exit_json(skipped=True, msg=f"command '{command}' does not support check mode, skipping")
rc, out, err = composer_command(module, [command], arguments, options)
diff --git a/plugins/modules/consul.py b/plugins/modules/consul.py
index 456335babf..2183b62005 100644
--- a/plugins/modules/consul.py
+++ b/plugins/modules/consul.py
@@ -232,7 +232,7 @@ try:
if token:
params['token'] = token
return self.agent.http.put(consul.base.CB.bool(),
- '/v1/agent/service/deregister/%s' % service_id,
+ f'/v1/agent/service/deregister/{service_id}',
params=params)
python_consul_installed = True
@@ -501,7 +501,7 @@ class ConsulCheck(object):
if duration:
duration_units = ['ns', 'us', 'ms', 's', 'm', 'h']
if not any(duration.endswith(suffix) for suffix in duration_units):
- duration = "{0}s".format(duration)
+ duration = f"{duration}s"
return duration
def register(self, consul_api):
@@ -603,7 +603,7 @@ def main():
except SystemExit:
raise
except ConnectionError as e:
- module.fail_json(msg='Could not connect to consul agent at %s:%s, error was %s' % (p['host'], p['port'], str(e)))
+ module.fail_json(msg=f"Could not connect to consul agent at {p['host']}:{p['port']}, error was {e}")
except Exception as e:
module.fail_json(msg=str(e))
diff --git a/plugins/modules/consul_agent_check.py b/plugins/modules/consul_agent_check.py
index e241c8ddf4..72a48e86d4 100644
--- a/plugins/modules/consul_agent_check.py
+++ b/plugins/modules/consul_agent_check.py
@@ -202,9 +202,9 @@ class ConsulAgentCheckModule(_ConsulModule):
if operation == OPERATION_READ:
return "agent/checks"
if operation in [OPERATION_CREATE, OPERATION_UPDATE]:
- return "/".join([self.api_endpoint, "register"])
+ return f"{self.api_endpoint}/register"
if operation == OPERATION_DELETE:
- return "/".join([self.api_endpoint, "deregister", identifier])
+ return f"{self.api_endpoint}/deregister/{identifier}"
return super(ConsulAgentCheckModule, self).endpoint_url(operation, identifier)
diff --git a/plugins/modules/consul_agent_service.py b/plugins/modules/consul_agent_service.py
index 7d7c94c05a..ba59d7a007 100644
--- a/plugins/modules/consul_agent_service.py
+++ b/plugins/modules/consul_agent_service.py
@@ -230,9 +230,9 @@ class ConsulAgentServiceModule(_ConsulModule):
def endpoint_url(self, operation, identifier=None):
if operation in [OPERATION_CREATE, OPERATION_UPDATE]:
- return "/".join([self.api_endpoint, "register"])
+ return f"{self.api_endpoint}/register"
if operation == OPERATION_DELETE:
- return "/".join([self.api_endpoint, "deregister", identifier])
+ return f"{self.api_endpoint}/deregister/{identifier}"
return super(ConsulAgentServiceModule, self).endpoint_url(operation, identifier)
diff --git a/plugins/modules/consul_auth_method.py b/plugins/modules/consul_auth_method.py
index 88842662bb..e96f1a3c2f 100644
--- a/plugins/modules/consul_auth_method.py
+++ b/plugins/modules/consul_auth_method.py
@@ -153,12 +153,12 @@ def normalize_ttl(ttl):
new_ttl = ""
hours, remainder = divmod(ttl, 3600)
if hours:
- new_ttl += "{0}h".format(hours)
+ new_ttl += f"{hours}h"
minutes, seconds = divmod(remainder, 60)
if minutes:
- new_ttl += "{0}m".format(minutes)
+ new_ttl += f"{minutes}m"
if seconds:
- new_ttl += "{0}s".format(seconds)
+ new_ttl += f"{seconds}s"
return new_ttl
diff --git a/plugins/modules/consul_binding_rule.py b/plugins/modules/consul_binding_rule.py
index de1fae9357..20b8133666 100644
--- a/plugins/modules/consul_binding_rule.py
+++ b/plugins/modules/consul_binding_rule.py
@@ -125,12 +125,12 @@ class ConsulBindingRuleModule(_ConsulModule):
unique_identifiers = ["id"]
def read_object(self):
- url = "acl/binding-rules?authmethod={0}".format(self.params["auth_method"])
+ url = f"acl/binding-rules?authmethod={self.params['auth_method']}"
try:
results = self.get(url)
for result in results:
if result.get("Description").startswith(
- "{0}: ".format(self.params["name"])
+ f"{self.params['name']}: "
):
return result
except RequestError as e:
@@ -149,7 +149,7 @@ class ConsulBindingRuleModule(_ConsulModule):
final = super(ConsulBindingRuleModule, self).prepare_object(existing, obj)
name = self.params["name"]
description = final.pop("Description", "").split(": ", 1)[-1]
- final["Description"] = "{0}: {1}".format(name, description)
+ final["Description"] = f"{name}: {description}"
return final
diff --git a/plugins/modules/consul_kv.py b/plugins/modules/consul_kv.py
index d9354e62c5..bb1f9e7678 100644
--- a/plugins/modules/consul_kv.py
+++ b/plugins/modules/consul_kv.py
@@ -188,7 +188,7 @@ def execute(module):
elif state == 'absent':
remove_value(module)
else:
- module.exit_json(msg="Unsupported state: %s" % (state, ))
+ module.exit_json(msg=f"Unsupported state: {state}")
def lock(module, state):
@@ -201,8 +201,7 @@ def lock(module, state):
if not session:
module.fail(
- msg='%s of lock for %s requested but no session supplied' %
- (state, key))
+ msg=f'{state} of lock for {key} requested but no session supplied')
index, changed = _has_value_changed(consul_api, key, value)
@@ -239,7 +238,7 @@ def set_value(module):
value = module.params.get('value')
if value is NOT_SET:
- raise AssertionError('Cannot set value of "%s" to `NOT_SET`' % key)
+ raise AssertionError(f'Cannot set value of "{key}" to `NOT_SET`')
index, changed = _has_value_changed(consul_api, key, value)
@@ -320,8 +319,7 @@ def main():
try:
execute(module)
except ConnectionError as e:
- module.fail_json(msg='Could not connect to consul agent at %s:%s, error was %s' % (
- module.params.get('host'), module.params.get('port'), e))
+ module.fail_json(msg=f"Could not connect to consul agent at {module.params.get('host')}:{module.params.get('port')}, error was {e}")
except Exception as e:
module.fail_json(msg=str(e))
diff --git a/plugins/modules/consul_session.py b/plugins/modules/consul_session.py
index acfb8e5504..e1b4c68d7e 100644
--- a/plugins/modules/consul_session.py
+++ b/plugins/modules/consul_session.py
@@ -178,7 +178,7 @@ def lookup_sessions(module, consul_module):
sessions=session_by_id)
except Exception as e:
- module.fail_json(msg="Could not retrieve session info %s" % e)
+ module.fail_json(msg=f"Could not retrieve session info {e}")
def create_session(consul_module, name, behavior, ttl, node,
@@ -191,7 +191,7 @@ def create_session(consul_module, name, behavior, ttl, node,
"Behavior": behavior,
}
if ttl is not None:
- create_data["TTL"] = "%ss" % str(ttl) # TTL is in seconds
+ create_data["TTL"] = f"{ttl}s" # TTL is in seconds
create_session_response_dict = consul_module.put(
'session/create',
params={
@@ -229,7 +229,7 @@ def update_session(module, consul_module):
checks=checks,
node=node)
except Exception as e:
- module.fail_json(msg="Could not create/update session %s" % e)
+ module.fail_json(msg=f"Could not create/update session {e}")
def destroy_session(consul_module, session_id):
@@ -245,8 +245,7 @@ def remove_session(module, consul_module):
module.exit_json(changed=True,
session_id=session_id)
except Exception as e:
- module.fail_json(msg="Could not remove session with id '%s' %s" % (
- session_id, e))
+ module.fail_json(msg=f"Could not remove session with id '{session_id}' {e}")
def main():
diff --git a/plugins/modules/copr.py b/plugins/modules/copr.py
index 4d627ceb8f..24832a59f8 100644
--- a/plugins/modules/copr.py
+++ b/plugins/modules/copr.py
@@ -214,9 +214,7 @@ class CoprModule(object):
Info about a repository and status code of the get request.
"""
repo_info = None
- url = "{0}://{1}/coprs/{2}/repo/{3}/dnf.repo?arch={4}".format(
- self.protocol, self.host, self.name, chroot, self.arch
- )
+ url = f"{self.protocol}://{self.host}/coprs/{self.name}/repo/{chroot}/dnf.repo?arch={self.arch}"
try:
r = open_url(url)
status_code = r.getcode()
@@ -245,7 +243,7 @@ class CoprModule(object):
version = "8"
elif version == "stream-9":
version = "9"
- chroot = "epel-{0}".format(version)
+ chroot = f"epel-{version}"
distribution = "epel"
else:
if str(status_code) != "404":
@@ -254,7 +252,7 @@ class CoprModule(object):
)
else:
self.raise_exception(
- "Chroot {0} does not exist in {1}".format(self.chroot, self.name)
+ f"Chroot {self.chroot} does not exist in {self.name}"
)
def _enable_repo(self, repo_filename_path, repo_content=None):
@@ -272,23 +270,23 @@ class CoprModule(object):
repo_content = self._download_repo_info()
if self.ansible_module.params["includepkgs"]:
includepkgs_value = ','.join(self.ansible_module.params['includepkgs'])
- repo_content = repo_content.rstrip('\n') + '\nincludepkgs={0}\n'.format(includepkgs_value)
+ repo_content_strip = repo_content.rstrip('\n') # Python 3.11 does not allow backslash chars within f-string expressions
+ repo_content = f"{repo_content_strip}\nincludepkgs={includepkgs_value}\n"
if self.ansible_module.params["excludepkgs"]:
excludepkgs_value = ','.join(self.ansible_module.params['excludepkgs'])
- repo_content = repo_content.rstrip('\n') + '\nexcludepkgs={0}\n'.format(excludepkgs_value)
+ repo_content_strip = repo_content.rstrip('\n') # Python 3.11 does not allow backslash chars within f-string expressions
+ repo_content = f"{repo_content_strip}\nexcludepkgs={excludepkgs_value}\n"
if self._compare_repo_content(repo_filename_path, repo_content):
return False
if not self.check_mode:
with open(repo_filename_path, "w+") as file:
file.write(repo_content)
- os.chmod(
- repo_filename_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH,
- )
+ os.chmod(repo_filename_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
return True
def _get_repo_with_old_id(self):
"""Try to get a repository with the old name."""
- repo_id = "{0}-{1}".format(self.user, self.project)
+ repo_id = f"{self.user}-{self.project}"
if repo_id in self.base.repos and "_copr" in self.base.repos[repo_id].repofile:
file_name = self.base.repos[repo_id].repofile.split("/")[-1]
try:
@@ -325,7 +323,7 @@ class CoprModule(object):
Returns:
The repository that a user wants to enable, disable, or remove.
"""
- repo_id = "copr:{0}:{1}:{2}".format(self.host, self.user, self.project)
+ repo_id = f"copr:{self.host}:{self.user}:{self.project}"
if repo_id not in self.base.repos:
if self._get_repo_with_old_id() is None:
return None
@@ -347,7 +345,7 @@ class CoprModule(object):
if self.check_mode:
return True
self._enable_repo(repo_filename_path)
- self._read_all_repos("copr:{0}:{1}:{2}".format(self.host, self.user, self.project))
+ self._read_all_repos(f"copr:{self.host}:{self.user}:{self.project}")
repo = self._get_copr_repo()
for repo_id in repo.cfg.sections():
repo_content_api = self._download_repo_info()
@@ -420,12 +418,10 @@ class CoprModule(object):
"""
self.need_root()
state = dict()
- repo_filename = "_copr:{0}:{1}:{2}.repo".format(self.host, self.user, self.project)
- state["repo"] = "{0}/{1}/{2}".format(self.host, self.user, self.project)
+ repo_filename = f"_copr:{self.host}:{self.user}:{self.project}.repo"
+ state["repo"] = f"{self.host}/{self.user}/{self.project}"
state["repo_filename"] = repo_filename
- repo_filename_path = "{0}/_copr:{1}:{2}:{3}.repo".format(
- self.base.conf.get_reposdir, self.host, self.user, self.project
- )
+ repo_filename_path = f"{self.base.conf.get_reposdir}/_copr:{self.host}:{self.user}:{self.project}.repo"
if self.state == "enabled":
enabled = self._enable_repo(repo_filename_path)
state["msg"] = "enabled"
@@ -466,7 +462,7 @@ class CoprModule(object):
"""
(distribution, version, codename) = distro.linux_distribution(full_distribution_name=False)
base = CoprModule.get_base()
- return "{0}-{1}-{2}".format(distribution, version, base.conf.arch)
+ return f"{distribution}-{version}-{base.conf.arch}"
@staticmethod
def _sanitize_username(user):
@@ -479,7 +475,7 @@ class CoprModule(object):
Modified user name if it is a group name with @.
"""
if user[0] == "@":
- return "group_{0}".format(user[1:])
+ return f"group_{user[1:]}"
return user
diff --git a/plugins/modules/cpanm.py b/plugins/modules/cpanm.py
index 39844d5f74..056b60163c 100644
--- a/plugins/modules/cpanm.py
+++ b/plugins/modules/cpanm.py
@@ -223,7 +223,7 @@ class CPANMinus(ModuleHelper):
line = out.split('\n')[0]
match = re.search(r"version\s+([\d\.]+)\s+", line)
if not match:
- self.do_raise("Failed to determine version number. First line of output: {0}".format(line))
+ self.do_raise(f"Failed to determine version number. First line of output: {line}")
self.vars.cpanm_version = match.group(1)
def _is_package_installed(self, name, locallib, version):
@@ -232,12 +232,12 @@ class CPANMinus(ModuleHelper):
if name is None or name.endswith('.tar.gz'):
return False
- version = "" if version is None else " " + version
+ version = "" if version is None else f" {version}"
- env = {"PERL5LIB": "%s/lib/perl5" % locallib} if locallib else {}
+ env = {"PERL5LIB": f"{locallib}/lib/perl5"} if locallib else {}
runner = CmdRunner(self.module, ["perl", "-le"], {"mod": cmd_runner_fmt.as_list()}, check_rc=False, environ_update=env)
with runner("mod", output_process=process) as ctx:
- return ctx.run(mod='use %s%s;' % (name, version))
+ return ctx.run(mod=f'use {name}{version};')
def sanitize_pkg_spec_version(self, pkg_spec, version):
if version is None:
@@ -249,9 +249,9 @@ class CPANMinus(ModuleHelper):
if pkg_spec.endswith('.git'):
if version.startswith('~'):
self.do_raise(msg="operator '~' not allowed in version parameter when installing from git repository")
- version = version if version.startswith('@') else '@' + version
+ version = version if version.startswith('@') else f"@{version}"
elif version[0] not in ('@', '~'):
- version = '~' + version
+ version = f"~{version}"
return pkg_spec + version
def __run__(self):
diff --git a/plugins/modules/cronvar.py b/plugins/modules/cronvar.py
index b67b94fe95..1d70d9d848 100644
--- a/plugins/modules/cronvar.py
+++ b/plugins/modules/cronvar.py
@@ -135,7 +135,7 @@ class CronVar(object):
self.cron_file = os.path.join('/etc/cron.d', cron_file)
parent_dir = os.path.dirname(self.cron_file)
if parent_dir and not os.path.isdir(parent_dir):
- module.fail_json(msg="Parent directory '{}' does not exist for cron_file: '{}'".format(parent_dir, cron_file))
+ module.fail_json(msg=f"Parent directory '{parent_dir}' does not exist for cron_file: '{cron_file}'")
else:
self.cron_file = None
@@ -170,7 +170,7 @@ class CronVar(object):
count += 1
def log_message(self, message):
- self.module.debug('ansible: "%s"' % message)
+ self.module.debug(f'ansible: "{message}"')
def write(self, backup_file=None):
"""
@@ -244,18 +244,18 @@ class CronVar(object):
def add_variable(self, name, value, insertbefore, insertafter):
if insertbefore is None and insertafter is None:
# Add the variable to the top of the file.
- self.lines.insert(0, "%s=%s" % (name, value))
+ self.lines.insert(0, f"{name}={value}")
else:
newlines = []
for l in self.lines:
try:
varname, dummy = self.parse_for_var(l) # Throws if not a var line
if varname == insertbefore:
- newlines.append("%s=%s" % (name, value))
+ newlines.append(f"{name}={value}")
newlines.append(l)
elif varname == insertafter:
newlines.append(l)
- newlines.append("%s=%s" % (name, value))
+ newlines.append(f"{name}={value}")
else:
raise CronVarError # Append.
except CronVarError:
@@ -274,7 +274,7 @@ class CronVar(object):
if varname != name:
raise CronVarError # Append.
if not remove:
- newlines.append("%s=%s" % (name, value))
+ newlines.append(f"{name}={value}")
except CronVarError:
newlines.append(l)
@@ -297,14 +297,14 @@ class CronVar(object):
if self.user:
if platform.system() == 'SunOS':
- return "su %s -c '%s -l'" % (shlex_quote(self.user), shlex_quote(self.cron_cmd))
+ return f"su {shlex_quote(self.user)} -c '{shlex_quote(self.cron_cmd)} -l'"
elif platform.system() == 'AIX':
- return "%s -l %s" % (shlex_quote(self.cron_cmd), shlex_quote(self.user))
+ return f"{shlex_quote(self.cron_cmd)} -l {shlex_quote(self.user)}"
elif platform.system() == 'HP-UX':
- return "%s %s %s" % (self.cron_cmd, '-l', shlex_quote(self.user))
+ return f"{self.cron_cmd} -l {shlex_quote(self.user)}"
elif pwd.getpwuid(os.getuid())[0] != self.user:
- user = '-u %s' % shlex_quote(self.user)
- return "%s %s %s" % (self.cron_cmd, user, '-l')
+ user = f'-u {shlex_quote(self.user)}'
+ return f"{self.cron_cmd} {user} -l"
def _write_execute(self, path):
"""
@@ -313,11 +313,10 @@ class CronVar(object):
user = ''
if self.user:
if platform.system() in ['SunOS', 'HP-UX', 'AIX']:
- return "chown %s %s ; su '%s' -c '%s %s'" % (
- shlex_quote(self.user), shlex_quote(path), shlex_quote(self.user), self.cron_cmd, shlex_quote(path))
+ return f"chown {shlex_quote(self.user)} {shlex_quote(path)} ; su '{shlex_quote(self.user)}' -c '{self.cron_cmd} {shlex_quote(path)}'"
elif pwd.getpwuid(os.getuid())[0] != self.user:
- user = '-u %s' % shlex_quote(self.user)
- return "%s %s %s" % (self.cron_cmd, user, shlex_quote(path))
+ user = f'-u {shlex_quote(self.user)}'
+ return f"{self.cron_cmd} {user} {shlex_quote(path)}"
# ==================================================
@@ -369,7 +368,7 @@ def main():
os.umask(int('022', 8))
cronvar = CronVar(module, user, cron_file)
- module.debug('cronvar instantiated - name: "%s"' % name)
+ module.debug(f'cronvar instantiated - name: "{name}"')
# --- user input validation ---
diff --git a/plugins/modules/crypttab.py b/plugins/modules/crypttab.py
index 4eb8e4b6c2..e325c1df7c 100644
--- a/plugins/modules/crypttab.py
+++ b/plugins/modules/crypttab.py
@@ -85,7 +85,7 @@ import os
import traceback
from ansible.module_utils.basic import AnsibleModule
-from ansible.module_utils.common.text.converters import to_bytes, to_native
+from ansible.module_utils.common.text.converters import to_bytes
def main():
@@ -115,7 +115,7 @@ def main():
**module.params)
if 'opts' in state and (backing_device is not None or password is not None):
- module.fail_json(msg="cannot update 'backing_device' or 'password' when state=%s" % state,
+ module.fail_json(msg=f"cannot update 'backing_device' or 'password' when state={state}",
**module.params)
for arg_name, arg in (('name', name),
@@ -123,15 +123,14 @@ def main():
('password', password),
('opts', opts)):
if arg is not None and (' ' in arg or '\t' in arg or arg == ''):
- module.fail_json(msg="invalid '%s': contains white space or is empty" % arg_name,
+ module.fail_json(msg=f"invalid '{arg_name}': contains white space or is empty",
**module.params)
try:
crypttab = Crypttab(path)
existing_line = crypttab.match(name)
except Exception as e:
- module.fail_json(msg="failed to open and parse crypttab file: %s" % to_native(e),
- exception=traceback.format_exc(), **module.params)
+ module.fail_json(msg=f"failed to open and parse crypttab file: {e}", exception=traceback.format_exc(), **module.params)
if 'present' in state and existing_line is None and backing_device is None:
module.fail_json(msg="'backing_device' required to add a new entry",
@@ -349,7 +348,7 @@ class Options(dict):
if v is None:
ret.append(k)
else:
- ret.append('%s=%s' % (k, v))
+ ret.append(f'{k}={v}')
return ','.join(ret)