Skip to content

Commit

Permalink
Fstring cleanup (#1529)
Browse files Browse the repository at this point in the history
We've dropped support for Python <3.6, bulk migrate to fstrings and perform some general string cleanup

A combination of
* `black --preview`
* `flynt`
* some manual cleanup

Co-authored-by: Alina Buzachis <[email protected]>
  • Loading branch information
tremble and alinabuzachis authored May 8, 2023
1 parent 4b63a32 commit 8c0880b
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 26 deletions.
3 changes: 3 additions & 0 deletions changelogs/fragments/fstring-4.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# 1483 includes a fragment and links to 1529
trivial:
- bulk migration of ``%`` and ``.format()`` to fstrings (https://github.com/ansible-collections/amazon.aws/pull/1529).
8 changes: 4 additions & 4 deletions plugins/module_utils/ec2.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def get_sg_id(sg, boto3=None):
sec_group_id_list[:] = [sg for sg in unmatched if re.match("sg-[a-fA-F0-9]+$", sg)]
still_unmatched = [sg for sg in unmatched if not re.match("sg-[a-fA-F0-9]+$", sg)]
if len(still_unmatched) > 0:
raise ValueError("The following group names are not valid: %s" % ", ".join(still_unmatched))
raise ValueError(f"The following group names are not valid: {', '.join(still_unmatched)}")

sec_group_id_list += [get_sg_id(all_sg) for all_sg in all_sec_groups if get_sg_name(all_sg) in sec_group_name_list]

Expand Down Expand Up @@ -165,7 +165,7 @@ def add_ec2_tags(client, module, resource_id, tags_to_set, retry_codes=None):
Resources=[resource_id], Tags=tags_to_add
)
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(e, msg="Unable to add tags {0} to {1}".format(tags_to_set, resource_id))
module.fail_json_aws(e, msg=f"Unable to add tags {tags_to_set} to {resource_id}")
return True


Expand Down Expand Up @@ -195,7 +195,7 @@ def remove_ec2_tags(client, module, resource_id, tags_to_unset, retry_codes=None
Resources=[resource_id], Tags=tags_to_remove
)
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(e, msg="Unable to delete tags {0} from {1}".format(tags_to_unset, resource_id))
module.fail_json_aws(e, msg=f"Unable to delete tags {tags_to_unset} from {resource_id}")
return True


Expand Down Expand Up @@ -224,7 +224,7 @@ def describe_ec2_tags(client, module, resource_id, resource_type=None, retry_cod
)
return boto3_tag_list_to_ansible_dict(results.get("Tags", None))
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(e, msg="Failed to describe tags for EC2 Resource: {0}".format(resource_id))
module.fail_json_aws(e, msg=f"Failed to describe tags for EC2 Resource: {resource_id}")


def ensure_ec2_tags(client, module, resource_id, resource_type=None, tags=None, purge_tags=True, retry_codes=None):
Expand Down
42 changes: 24 additions & 18 deletions plugins/module_utils/modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,26 +110,30 @@ def __init__(self, **kwargs):
deprecated_vars = {"EC2_REGION", "EC2_SECURITY_TOKEN", "EC2_SECRET_KEY", "EC2_ACCESS_KEY", "EC2_URL", "S3_URL"}
if deprecated_vars.intersection(set(os.environ.keys())):
self._module.deprecate(
"Support for the 'EC2_REGION', 'EC2_ACCESS_KEY', 'EC2_SECRET_KEY', "
"'EC2_SECURITY_TOKEN', 'EC2_URL', and 'S3_URL' environment "
"variables has been deprecated. "
"These variables are currently used for all AWS services which can "
"cause confusion. We recomend using the relevant module "
"parameters or alternatively the 'AWS_REGION', 'AWS_ACCESS_KEY_ID', "
"'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN', and 'AWS_URL' "
"environment variables can be used instead.",
(
"Support for the 'EC2_REGION', 'EC2_ACCESS_KEY', 'EC2_SECRET_KEY', "
"'EC2_SECURITY_TOKEN', 'EC2_URL', and 'S3_URL' environment "
"variables has been deprecated. "
"These variables are currently used for all AWS services which can "
"cause confusion. We recomend using the relevant module "
"parameters or alternatively the 'AWS_REGION', 'AWS_ACCESS_KEY_ID', "
"'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN', and 'AWS_URL' "
"environment variables can be used instead."
),
date="2024-12-01",
collection_name="amazon.aws",
)

if "AWS_SECURITY_TOKEN" in os.environ.keys():
self._module.deprecate(
"Support for the 'AWS_SECURITY_TOKEN' environment variable "
"has been deprecated. This variable was based on the original "
"boto SDK, support for which has now been dropped. "
"We recommend using the 'session_token' module parameter "
"or alternatively the 'AWS_SESSION_TOKEN' environment variable "
"can be used instead.",
(
"Support for the 'AWS_SECURITY_TOKEN' environment variable "
"has been deprecated. This variable was based on the original "
"boto SDK, support for which has now been dropped. "
"We recommend using the 'session_token' module parameter "
"or alternatively the 'AWS_SESSION_TOKEN' environment variable "
"can be used instead."
),
date="2024-12-01",
collection_name="amazon.aws",
)
Expand Down Expand Up @@ -159,7 +163,7 @@ def _get_resource_action_list(self):
if found_operational_request:
operation_request = found_operational_request.group(0)[20:-1]
resource = re.search(r"https://.*?\.", ln).group(0)[8:-1]
actions.append("{0}:{1}".format(resource, operation_request))
actions.append(f"{resource}:{operation_request}")
return list(set(actions))

def exit_json(self, *args, **kwargs):
Expand Down Expand Up @@ -220,7 +224,7 @@ def fail_json_aws(self, exception, msg=None, **kwargs):
except_msg = to_native(exception)

if msg is not None:
message = "{0}: {1}".format(msg, except_msg)
message = f"{msg}: {except_msg}"
else:
message = except_msg

Expand Down Expand Up @@ -261,7 +265,8 @@ def require_boto3_at_least(self, desired, **kwargs):
"""
if not self.boto3_at_least(desired):
self._module.fail_json(
msg=missing_required_lib("boto3>={0}".format(desired), **kwargs), **self._gather_versions()
msg=missing_required_lib(f"boto3>={desired}", **kwargs),
**self._gather_versions(),
)

def boto3_at_least(self, desired):
Expand All @@ -282,7 +287,8 @@ def require_botocore_at_least(self, desired, **kwargs):
"""
if not self.botocore_at_least(desired):
self._module.fail_json(
msg=missing_required_lib("botocore>={0}".format(desired), **kwargs), **self._gather_versions()
msg=missing_required_lib(f"botocore>={desired}", **kwargs),
**self._gather_versions(),
)

def botocore_at_least(self, desired):
Expand Down
2 changes: 1 addition & 1 deletion plugins/module_utils/tagging.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def boto3_tag_list_to_ansible_dict(tags_list, tag_name_key_name=None, tag_value_
for k, v in tag_candidates.items():
if k in tags_list[0] and v in tags_list[0]:
return dict((tag[k], tag[v]) for tag in tags_list)
raise ValueError("Couldn't find tag key (candidates %s) in tag list %s" % (str(tag_candidates), str(tags_list)))
raise ValueError(f"Couldn't find tag key (candidates {str(tag_candidates)}) in tag list {str(tags_list)}")


def ansible_dict_to_boto3_tag_list(tags_dict, tag_name_key_name="Key", tag_value_key_name="Value"):
Expand Down
5 changes: 2 additions & 3 deletions plugins/module_utils/waiters.py
Original file line number Diff line number Diff line change
Expand Up @@ -953,8 +953,7 @@ def get_waiter(client, waiter_name):
try:
return waiters_by_name[(client.__class__.__name__, waiter_name)](client)
except KeyError:
available_waiters = ", ".join(repr(k) for k in waiters_by_name.keys())
raise NotImplementedError(
"Waiter {0} could not be found for client {1}. Available waiters: {2}".format(
waiter_name, type(client), ", ".join(repr(k) for k in waiters_by_name.keys())
)
f"Waiter {waiter_name} could not be found for client {type(client)}. Available waiters: {available_waiters}"
)

0 comments on commit 8c0880b

Please sign in to comment.