Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bulk migration to Python 3.6 f-strings (3) #1527

Merged
merged 3 commits into from
May 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelogs/fragments/fstring-3.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# 1483 includes a fragment and links to 1527
trivial:
- bulk migration of ``%`` and ``.format()`` to fstrings (https://github.com/ansible-collections/amazon.aws/pull/1527).
18 changes: 9 additions & 9 deletions plugins/module_utils/acm.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def delete_certificate(self, *args, arn=None):
if len(args) < 3:
self.module.fail_json(msg="Missing required certificate arn to delete.")
arn = args[2]
error = "Couldn't delete certificate %s" % arn
error = f"Couldn't delete certificate {arn}"
self.delete_certificate_with_backoff(arn, module=self.module, error=error)

def get_certificates(self, *args, domain_name=None, statuses=None, arn=None, only_tags=None, **kwargs):
Expand Down Expand Up @@ -154,7 +154,7 @@ def _filter_certificate(cert):
cert_data = self.describe_certificate_with_backoff(
certificate["CertificateArn"],
module=self.module,
error="Couldn't obtain certificate metadata for domain %s" % certificate["DomainName"],
error=f"Couldn't obtain certificate metadata for domain {certificate['DomainName']}",
ignore_error_codes=["ResourceNotFoundException"],
)
if cert_data is None:
Expand All @@ -165,7 +165,7 @@ def _filter_certificate(cert):
cert_info = self.get_certificate_with_backoff(
certificate["CertificateArn"],
module=self.module,
error="Couldn't obtain certificate data for domain %s" % certificate["DomainName"],
error=f"Couldn't obtain certificate data for domain {certificate['DomainName']}",
ignore_error_codes=["ResourceNotFoundException"],
)
if cert_info is None:
Expand All @@ -176,7 +176,7 @@ def _filter_certificate(cert):
tags = self.list_certificate_tags_with_backoff(
certificate["CertificateArn"],
module=self.module,
error="Couldn't obtain tags for domain %s" % certificate["DomainName"],
error=f"Couldn't obtain tags for domain {certificate['DomainName']}",
ignore_error_codes=["ResourceNotFoundException"],
)
if tags is None:
Expand All @@ -196,7 +196,7 @@ def get_domain_of_cert(self, arn, **kwargs):
"""
if arn is None:
self.module.fail_json(msg="Internal error with ACM domain fetching, no certificate ARN specified")
error = "Couldn't obtain certificate data for arn %s" % arn
error = f"Couldn't obtain certificate data for arn {arn}"
cert_data = self.describe_certificate_with_backoff(certificate_arn=arn, module=self.module, error=error)
return cert_data["DomainName"]

Expand All @@ -217,7 +217,7 @@ def import_certificate(self, *args, certificate, private_key, arn=None, certific
# I'm not sure whether the API guarentees that the ARN will not change
# I'm failing just in case.
# If I'm wrong, I'll catch it in the integration tests.
self.module.fail_json(msg="ARN changed with ACM update, from %s to %s" % (original_arn, arn))
self.module.fail_json(msg=f"ARN changed with ACM update, from {original_arn} to {arn}")

# tag that cert
try:
Expand All @@ -227,9 +227,9 @@ def import_certificate(self, *args, certificate, private_key, arn=None, certific
self.delete_certificate_with_backoff(arn)
except (BotoCoreError, ClientError):
self.module.warn(
"Certificate %s exists, and is not tagged. So Ansible will not see it on the next run." % arn
f"Certificate {arn} exists, and is not tagged. So Ansible will not see it on the next run."
)
self.module.fail_json_aws(e, msg="Couldn't tag certificate %s, couldn't delete it either" % arn)
self.module.fail_json_aws(e, msg="Couldn't tag certificate %s" % arn)
self.module.fail_json_aws(e, msg=f"Couldn't tag certificate {arn}, couldn't delete it either")
self.module.fail_json_aws(e, msg=f"Couldn't tag certificate {arn}")

return arn
2 changes: 1 addition & 1 deletion plugins/module_utils/backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ def get_backup_resource_tags(module, backup_client):
try:
response = backup_client.list_tags(ResourceArn=resource)
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(e, msg="Failed to list tags on the resource {0}".format(resource))
module.fail_json_aws(e, msg=f"Failed to list tags on the resource {resource}")

return response["Tags"]
2 changes: 1 addition & 1 deletion plugins/module_utils/cloudfront_facts.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def __getattr__(self, name):
keyed = self.CLOUDFRONT_CLIENT_PAGINATE_API_MAPPING[name].get("keyed", False)
return partial(self.paginate_list_cloudfront_property, client_method, key, keyed, error)

raise CloudFrontFactsServiceManagerFailure("Method {0} is not currently supported".format(name))
raise CloudFrontFactsServiceManagerFailure(f"Method {name} is not currently supported")

def summary(self):
summary_dict = {}
Expand Down
10 changes: 4 additions & 6 deletions plugins/module_utils/direct_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def delete_connection(client, connection_id):
AWSRetry.jittered_backoff()(client.delete_connection)(connectionId=connection_id)
except botocore.exceptions.ClientError as e:
raise DirectConnectError(
msg="Failed to delete DirectConnection {0}.".format(connection_id),
msg=f"Failed to delete DirectConnection {connection_id}.",
last_traceback=traceback.format_exc(),
exception=e,
)
Expand All @@ -64,8 +64,7 @@ def associate_connection_and_lag(client, connection_id, lag_id):
AWSRetry.jittered_backoff()(client.associate_connection_with_lag)(connectionId=connection_id, lagId=lag_id)
except botocore.exceptions.ClientError as e:
raise DirectConnectError(
msg="Failed to associate Direct Connect connection {0}"
" with link aggregation group {1}.".format(connection_id, lag_id),
msg=f"Failed to associate Direct Connect connection {connection_id} with link aggregation group {lag_id}.",
last_traceback=traceback.format_exc(),
exception=e,
)
Expand All @@ -76,8 +75,7 @@ def disassociate_connection_and_lag(client, connection_id, lag_id):
AWSRetry.jittered_backoff()(client.disassociate_connection_from_lag)(connectionId=connection_id, lagId=lag_id)
except botocore.exceptions.ClientError as e:
raise DirectConnectError(
msg="Failed to disassociate Direct Connect connection {0}"
" from link aggregation group {1}.".format(connection_id, lag_id),
msg=f"Failed to disassociate Direct Connect connection {connection_id} from link aggregation group {lag_id}.",
last_traceback=traceback.format_exc(),
exception=e,
)
Expand All @@ -88,7 +86,7 @@ def delete_virtual_interface(client, virtual_interface):
AWSRetry.jittered_backoff()(client.delete_virtual_interface)(virtualInterfaceId=virtual_interface)
except botocore.exceptions.ClientError as e:
raise DirectConnectError(
msg="Could not delete virtual interface {0}".format(virtual_interface),
msg=f"Could not delete virtual interface {virtual_interface}",
last_traceback=traceback.format_exc(),
exception=e,
)
4 changes: 2 additions & 2 deletions plugins/module_utils/elbv2.py
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,7 @@ def __init__(self, connection, connection_ec2, module):

if self.elb is not None and self.elb["Type"] != "application":
self.module.fail_json(
msg="The load balancer type you are trying to manage is not application. Try elb_network_lb module instead."
msg="The load balancer type you are trying to manage is not application. Try elb_network_lb module instead.",
)

def _elb_create_params(self):
Expand Down Expand Up @@ -699,7 +699,7 @@ def __init__(self, connection, connection_ec2, module):

if self.elb is not None and self.elb["Type"] != "network":
self.module.fail_json(
msg="The load balancer type you are trying to manage is not network. Try elb_application_lb module instead."
msg="The load balancer type you are trying to manage is not network. Try elb_application_lb module instead.",
)

def _elb_create_params(self):
Expand Down
2 changes: 1 addition & 1 deletion plugins/module_utils/iam.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def get_aws_account_info(module):

if account_id is None or partition is None:
module.fail_json(
msg="Failed to get AWS account information, Try allowing sts:GetCallerIdentity or iam:GetUser permissions."
msg="Failed to get AWS account information, Try allowing sts:GetCallerIdentity or iam:GetUser permissions.",
)

return (to_native(account_id), to_native(partition))
6 changes: 4 additions & 2 deletions plugins/module_utils/policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,10 @@ def sort_json_policy_dict(policy_dict):
"""

ansible_warnings.deprecate(
"amazon.aws.module_utils.policy.sort_json_policy_dict has been deprecated, consider using "
"amazon.aws.module_utils.policy.compare_policies instead",
(
"amazon.aws.module_utils.policy.sort_json_policy_dict has been deprecated, consider using "
"amazon.aws.module_utils.policy.compare_policies instead"
),
version="8.0.0",
collection_name="amazon.aws",
)
Expand Down
4 changes: 2 additions & 2 deletions plugins/module_utils/route53.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def manage_tags(module, client, resource_type, resource_id, new_tags, purge_tags
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(
e,
msg="Failed to update tags on {0}".format(resource_type),
msg=f"Failed to update tags on {resource_type}",
resource_id=resource_id,
change_params=change_params,
)
Expand All @@ -59,7 +59,7 @@ def get_tags(module, client, resource_type, resource_id):
botocore.exceptions.BotoCoreError,
botocore.exceptions.ClientError,
) as e: # pylint: disable=duplicate-except
module.fail_json_aws(e, msg="Failed to fetch tags on {0}".format(resource_type), resource_id=resource_id)
module.fail_json_aws(e, msg=f"Failed to fetch tags on {resource_type}", resource_id=resource_id)

tags = boto3_tag_list_to_ansible_dict(tagset["ResourceTagSet"]["Tags"])
return tags
8 changes: 4 additions & 4 deletions plugins/module_utils/s3.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def calculate_checksum_with_file(client, parts, bucket, obj, versionId, filename
digests.append(md5(f.read(int(head["ContentLength"]))).digest())

digest_squared = b"".join(digests)
return '"{0}-{1}"'.format(md5(digest_squared).hexdigest(), len(digests))
return f'"{md5(digest_squared).hexdigest()}-{len(digests)}"'


def calculate_checksum_with_content(client, parts, bucket, obj, versionId, content):
Expand All @@ -51,7 +51,7 @@ def calculate_checksum_with_content(client, parts, bucket, obj, versionId, conte
offset += length

digest_squared = b"".join(digests)
return '"{0}-{1}"'.format(md5(digest_squared).hexdigest(), len(digests))
return f'"{md5(digest_squared).hexdigest()}-{len(digests)}"'


def calculate_etag(module, filename, etag, s3, bucket, obj, version=None):
Expand All @@ -66,7 +66,7 @@ def calculate_etag(module, filename, etag, s3, bucket, obj, version=None):
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(e, msg="Failed to get head object")
else: # Compute the MD5 sum normally
return '"{0}"'.format(module.md5(filename))
return f'"{module.md5(filename)}"'


def calculate_etag_content(module, content, etag, s3, bucket, obj, version=None):
Expand All @@ -81,7 +81,7 @@ def calculate_etag_content(module, content, etag, s3, bucket, obj, version=None)
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
module.fail_json_aws(e, msg="Failed to get head object")
else: # Compute the MD5 sum normally
return '"{0}"'.format(md5(content).hexdigest())
return f'"{md5(content).hexdigest()}"'


def validate_bucket_name(name):
Expand Down
4 changes: 2 additions & 2 deletions plugins/module_utils/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,8 +238,8 @@ def signed_request(

# Make auth header with that info

authorization_header = "{0} Credential={1}/{2}, SignedHeaders={3}, Signature={4}".format(
algorithm, access_key, credential_scope, signed_headers, signature
authorization_header = (
f"{algorithm} Credential={access_key}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}"
)

# PERFORM THE REQUEST!
Expand Down