mirror of
https://github.com/ansible-collections/community.crypto.git
synced 2026-05-06 13:22:58 +00:00
Replace % and str.format() with f-strings (#875)
* Replace % and str.format() with f-strings. * Apply suggestions from review.
This commit is contained in:
@@ -229,8 +229,7 @@ def main():
|
||||
base64.urlsafe_b64decode(key)
|
||||
except Exception as e:
|
||||
module.fail_json(
|
||||
msg="Key for external_account_binding must be Base64 URL encoded (%s)"
|
||||
% e
|
||||
msg=f"Key for external_account_binding must be Base64 URL encoded ({e})"
|
||||
)
|
||||
module.params["external_account_binding"]["key"] = key
|
||||
|
||||
@@ -296,7 +295,7 @@ def main():
|
||||
)
|
||||
except KeyParsingError as e:
|
||||
raise ModuleFailException(
|
||||
"Error while parsing new account key: {msg}".format(msg=e.msg)
|
||||
f"Error while parsing new account key: {e.msg}"
|
||||
)
|
||||
# Verify that the account exists and has not been deactivated
|
||||
created, account_data = account.setup_account(allow_creation=False)
|
||||
|
||||
@@ -233,9 +233,7 @@ def get_orders_list(module, client, orders_url):
|
||||
if not res.get("orders"):
|
||||
if orders:
|
||||
module.warn(
|
||||
"When retrieving orders list part {0}, got empty result list".format(
|
||||
orders_url
|
||||
)
|
||||
f"When retrieving orders list part {orders_url}, got empty result list"
|
||||
)
|
||||
break
|
||||
# Add order URLs to result list
|
||||
|
||||
@@ -643,9 +643,7 @@ class ACMECertificateClient:
|
||||
)
|
||||
except ValueError as exc:
|
||||
self.module.warn(
|
||||
"Error while parsing criterium: {error}. Ignoring criterium.".format(
|
||||
error=exc
|
||||
)
|
||||
f"Error while parsing criterium: {exc}. Ignoring criterium."
|
||||
)
|
||||
|
||||
if self.profile is not None:
|
||||
@@ -654,9 +652,7 @@ class ACMECertificateClient:
|
||||
raise ModuleFailException(msg="The ACME CA does not support profiles.")
|
||||
if self.profile not in meta_profiles:
|
||||
raise ModuleFailException(
|
||||
msg="The ACME CA does not support selected profile {0!r}.".format(
|
||||
self.profile
|
||||
)
|
||||
msg=f"The ACME CA does not support selected profile {self.profile!r}."
|
||||
)
|
||||
|
||||
# Make sure account exists
|
||||
@@ -678,7 +674,7 @@ class ACMECertificateClient:
|
||||
self.changed = created or updated
|
||||
|
||||
if self.csr is not None and not os.path.exists(self.csr):
|
||||
raise ModuleFailException("CSR %s not found" % (self.csr))
|
||||
raise ModuleFailException(f"CSR {self.csr} not found")
|
||||
|
||||
# Extract list of identifiers from CSR
|
||||
self.identifiers = self.client.backend.get_ordered_csr_identifiers(
|
||||
@@ -758,9 +754,7 @@ class ACMECertificateClient:
|
||||
and self.challenge not in data[authz.identifier]
|
||||
):
|
||||
raise ModuleFailException(
|
||||
"Found no challenge of type '{0}' for identifier {1}!".format(
|
||||
self.challenge, type_identifier
|
||||
)
|
||||
f"Found no challenge of type '{self.challenge}' for identifier {type_identifier}!"
|
||||
)
|
||||
# Get DNS challenge data
|
||||
data_dns = {}
|
||||
@@ -812,9 +806,7 @@ class ACMECertificateClient:
|
||||
alt_cert = CertificateChain.download(self.client, alternate)
|
||||
except ModuleFailException as e:
|
||||
self.module.warn(
|
||||
"Error while downloading alternative certificate {0}: {1}".format(
|
||||
alternate, e
|
||||
)
|
||||
f"Error while downloading alternative certificate {alternate}: {e}"
|
||||
)
|
||||
continue
|
||||
alternate_chains.append(alt_cert)
|
||||
@@ -825,7 +817,7 @@ class ACMECertificateClient:
|
||||
for chain in chains:
|
||||
if matcher.match(chain):
|
||||
self.module.debug(
|
||||
"Found matching chain for criterium {0}".format(criterium_idx)
|
||||
f"Found matching chain for criterium {criterium_idx}"
|
||||
)
|
||||
return chain
|
||||
return None
|
||||
@@ -844,13 +836,11 @@ class ACMECertificateClient:
|
||||
)
|
||||
if authz is None:
|
||||
raise ModuleFailException(
|
||||
'Found no authorization information for "{identifier}"!'.format(
|
||||
identifier=combine_identifier(identifier_type, identifier)
|
||||
)
|
||||
f'Found no authorization information for "{combine_identifier(identifier_type, identifier)}"!'
|
||||
)
|
||||
if authz.status != "valid":
|
||||
authz.raise_error(
|
||||
'Status is "{status}" and not "valid"'.format(status=authz.status),
|
||||
f'Status is "{authz.status}" and not "valid"',
|
||||
module=self.module,
|
||||
)
|
||||
|
||||
@@ -911,7 +901,7 @@ class ACMECertificateClient:
|
||||
pass
|
||||
if authz.status != "deactivated":
|
||||
self.module.warn(
|
||||
warning="Could not deactivate authz object {0}.".format(authz.url)
|
||||
warning=f"Could not deactivate authz object {authz.url}."
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -98,9 +98,7 @@ def main():
|
||||
# ignore errors
|
||||
pass
|
||||
if authz.status != "deactivated":
|
||||
module.warn(
|
||||
warning="Could not deactivate authz object {0}.".format(authz.url)
|
||||
)
|
||||
module.warn(warning=f"Could not deactivate authz object {authz.url}.")
|
||||
|
||||
module.exit_json(changed=changed)
|
||||
except ModuleFailException as e:
|
||||
|
||||
@@ -414,9 +414,7 @@ def main():
|
||||
)
|
||||
if profile not in meta_profiles:
|
||||
raise ModuleFailException(
|
||||
msg="The ACME CA does not support selected profile {0!r}.".format(
|
||||
profile
|
||||
)
|
||||
msg=f"The ACME CA does not support selected profile {profile!r}."
|
||||
)
|
||||
|
||||
order = None
|
||||
|
||||
@@ -271,13 +271,10 @@ def main():
|
||||
|
||||
missing_challenge_authzs = [k for k, v in challenges.items() if v is None]
|
||||
if missing_challenge_authzs:
|
||||
missing_challenge_authzs = ", ".join(sorted(missing_challenge_authzs))
|
||||
raise ModuleFailException(
|
||||
"The challenge parameter must be supplied if there are pending authorizations."
|
||||
" The following authorizations are pending: {missing_challenge_authzs}".format(
|
||||
missing_challenge_authzs=", ".join(
|
||||
sorted(missing_challenge_authzs)
|
||||
),
|
||||
)
|
||||
f" The following authorizations are pending: {missing_challenge_authzs}"
|
||||
)
|
||||
|
||||
bad_challenge_authzs = [
|
||||
@@ -286,18 +283,15 @@ def main():
|
||||
if authz.find_challenge(challenges[authz.combined_identifier]) is None
|
||||
]
|
||||
if bad_challenge_authzs:
|
||||
raise ModuleFailException(
|
||||
"The following authorizations do not support the selected challenges: {authz_challenges_pairs}".format(
|
||||
authz_challenges_pairs=", ".join(
|
||||
sorted(
|
||||
"{authz} with {challenge}".format(
|
||||
authz=authz, challenge=challenges[authz]
|
||||
)
|
||||
for authz in bad_challenge_authzs
|
||||
)
|
||||
),
|
||||
authz_challenges_pairs = ", ".join(
|
||||
sorted(
|
||||
f"{authz} with {challenges[authz]}"
|
||||
for authz in bad_challenge_authzs
|
||||
)
|
||||
)
|
||||
raise ModuleFailException(
|
||||
f"The following authorizations do not support the selected challenges: {authz_challenges_pairs}"
|
||||
)
|
||||
|
||||
really_pending_authzs = [
|
||||
authz
|
||||
|
||||
@@ -231,7 +231,7 @@ def main():
|
||||
)
|
||||
except ModuleFailException as e:
|
||||
if module.params["treat_parsing_error_as_non_existing"]:
|
||||
complete(True, msg="Certificate cannot be parsed: {0}".format(e.msg))
|
||||
complete(True, msg=f"Certificate cannot be parsed: {e.msg}")
|
||||
e.do_fail(module)
|
||||
|
||||
result["parsable"] = True
|
||||
@@ -265,24 +265,18 @@ def main():
|
||||
)
|
||||
msg_append = ""
|
||||
if "explanationURL" in renewal_info:
|
||||
msg_append = ". Information on renewal interval: {0}".format(
|
||||
renewal_info["explanationURL"]
|
||||
)
|
||||
msg_append = f". Information on renewal interval: {renewal_info['explanationURL']}"
|
||||
result["supports_ari"] = True
|
||||
if now > window_end:
|
||||
complete(
|
||||
True,
|
||||
msg="The suggested renewal interval provided by ARI is in the past{0}".format(
|
||||
msg_append
|
||||
),
|
||||
msg=f"The suggested renewal interval provided by ARI is in the past{msg_append}",
|
||||
)
|
||||
if module.params["ari_algorithm"] == "start":
|
||||
if now > window_start:
|
||||
complete(
|
||||
True,
|
||||
msg="The suggested renewal interval provided by ARI has begun{0}".format(
|
||||
msg_append
|
||||
),
|
||||
msg=f"The suggested renewal interval provided by ARI has begun{msg_append}",
|
||||
)
|
||||
else:
|
||||
random_time = backend.interpolate_timestamp(
|
||||
@@ -291,10 +285,7 @@ def main():
|
||||
if now > random_time:
|
||||
complete(
|
||||
True,
|
||||
msg="The picked random renewal time {0} in sugested renewal internal provided by ARI is in the past{1}".format(
|
||||
random_time,
|
||||
msg_append,
|
||||
),
|
||||
msg=f"The picked random renewal time {random_time} in sugested renewal internal provided by ARI is in the past{msg_append}",
|
||||
)
|
||||
|
||||
if module.params["remaining_days"] is not None:
|
||||
@@ -302,7 +293,7 @@ def main():
|
||||
if remaining_days < module.params["remaining_days"]:
|
||||
complete(
|
||||
True,
|
||||
msg="The certificate expires in {0} days".format(remaining_days),
|
||||
msg=f"The certificate expires in {remaining_days} days",
|
||||
)
|
||||
|
||||
if module.params["remaining_percentage"] is not None:
|
||||
@@ -314,10 +305,8 @@ def main():
|
||||
if timestamp < now:
|
||||
complete(
|
||||
True,
|
||||
msg="The remaining percentage {0}% of the certificate's lifespan was reached on {1}".format(
|
||||
module.params["remaining_percentage"] * 100,
|
||||
timestamp,
|
||||
),
|
||||
msg=f"The remaining percentage {module.params['remaining_percentage'] * 100}%"
|
||||
f" of the certificate's lifespan was reached on {timestamp}",
|
||||
)
|
||||
|
||||
complete(False)
|
||||
|
||||
@@ -182,9 +182,7 @@ def main():
|
||||
private_key, private_key_content, passphrase=passphrase
|
||||
)
|
||||
except KeyParsingError as e:
|
||||
raise ModuleFailException(
|
||||
"Error while parsing private key: {msg}".format(msg=e.msg)
|
||||
)
|
||||
raise ModuleFailException(f"Error while parsing private key: {e.msg}")
|
||||
# Step 2: sign revokation request with private key
|
||||
jws_header = {
|
||||
"alg": private_key_data["alg"],
|
||||
|
||||
@@ -259,7 +259,7 @@ def main():
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
raise ModuleFailException("Error while loading private key: {0}".format(e))
|
||||
raise ModuleFailException(f"Error while loading private key: {e}")
|
||||
|
||||
# Some common attributes
|
||||
domain = to_text(challenge_data["resource"])
|
||||
@@ -276,7 +276,7 @@ def main():
|
||||
san = cryptography.x509.IPAddress(ipaddress.ip_address(identifier))
|
||||
else:
|
||||
raise ModuleFailException(
|
||||
'Unsupported identifier type "{0}"'.format(identifier_type)
|
||||
f'Unsupported identifier type "{identifier_type}"'
|
||||
)
|
||||
|
||||
# Generate regular self-signed certificate
|
||||
|
||||
@@ -212,18 +212,16 @@ def is_parent(module, cert, potential_parent):
|
||||
public_key.verify(cert.cert.signature, cert.cert.tbs_certificate_bytes)
|
||||
else:
|
||||
# Unknown public key type
|
||||
module.warn('Unknown public key type "{0}"'.format(public_key))
|
||||
module.warn(f'Unknown public key type "{public_key}"')
|
||||
return False
|
||||
return True
|
||||
except cryptography.exceptions.InvalidSignature:
|
||||
return False
|
||||
except cryptography.exceptions.UnsupportedAlgorithm:
|
||||
module.warn(
|
||||
'Unsupported algorithm "{0}"'.format(cert.cert.signature_hash_algorithm)
|
||||
)
|
||||
module.warn(f'Unsupported algorithm "{cert.cert.signature_hash_algorithm}"')
|
||||
return False
|
||||
except Exception as e:
|
||||
module.fail_json(msg="Unknown error on signature validation: {0}".format(e))
|
||||
module.fail_json(msg=f"Unknown error on signature validation: {e}")
|
||||
|
||||
|
||||
def parse_PEM_list(module, text, source, fail_on_error=True):
|
||||
@@ -239,9 +237,7 @@ def parse_PEM_list(module, text, source, fail_on_error=True):
|
||||
)
|
||||
result.append(Certificate(cert_pem, cert))
|
||||
except Exception as e:
|
||||
msg = "Cannot parse certificate #{0} from {1}: {2}".format(
|
||||
len(result) + 1, source, e
|
||||
)
|
||||
msg = f"Cannot parse certificate #{len(result) + 1} from {source}: {e}"
|
||||
if fail_on_error:
|
||||
module.fail_json(msg=msg)
|
||||
else:
|
||||
@@ -262,7 +258,7 @@ def load_PEM_list(module, path, fail_on_error=True):
|
||||
fail_on_error=fail_on_error,
|
||||
)
|
||||
except Exception as e:
|
||||
msg = "Cannot read certificate file {0}: {1}".format(path, e)
|
||||
msg = f"Cannot read certificate file {path}: {e}"
|
||||
if fail_on_error:
|
||||
module.fail_json(msg=msg)
|
||||
else:
|
||||
@@ -357,9 +353,9 @@ def main():
|
||||
if not is_parent(module, chain[i - 1], parent):
|
||||
module.fail_json(
|
||||
msg=(
|
||||
"Cannot verify input chain: certificate #{2}: {3} is not issuer "
|
||||
+ "of certificate #{0}: {1}"
|
||||
).format(i, format_cert(chain[i - 1]), i + 1, format_cert(parent))
|
||||
f"Cannot verify input chain: certificate #{i + 1}: {format_cert(parent)} is not issuer "
|
||||
f"of certificate #{i}: {format_cert(chain[i - 1])}"
|
||||
)
|
||||
)
|
||||
|
||||
# Load intermediate certificates
|
||||
@@ -392,9 +388,7 @@ def main():
|
||||
current = intermediate
|
||||
else:
|
||||
module.fail_json(
|
||||
msg="Cannot complete chain. Stuck at certificate {0}".format(
|
||||
format_cert(current)
|
||||
)
|
||||
msg=f"Cannot complete chain. Stuck at certificate {format_cert(current)}"
|
||||
)
|
||||
|
||||
# Return results
|
||||
|
||||
@@ -665,16 +665,12 @@ class EcsCertificate:
|
||||
],
|
||||
)
|
||||
except SessionConfigurationException as e:
|
||||
module.fail_json(
|
||||
msg="Failed to initialize Entrust Provider: {0}".format(to_native(e))
|
||||
)
|
||||
module.fail_json(msg=f"Failed to initialize Entrust Provider: {e}")
|
||||
try:
|
||||
self.ecs_client.GetAppVersion()
|
||||
except RestOperationException as e:
|
||||
module.fail_json(
|
||||
msg="Please verify credential information. Received exception when testing ECS connection: {0}".format(
|
||||
to_native(e.message)
|
||||
)
|
||||
msg=f"Please verify credential information. Received exception when testing ECS connection: {e.message}"
|
||||
)
|
||||
|
||||
# Conversion of the fields that go into the 'tracking' parameter of the request object
|
||||
@@ -744,7 +740,7 @@ class EcsCertificate:
|
||||
try:
|
||||
# Use serial_number to identify if certificate is an Entrust Certificate
|
||||
# with an associated tracking ID
|
||||
serial_number = "{0:X}".format(self.cert.serial_number)
|
||||
serial_number = f"{self.cert.serial_number:X}"
|
||||
cert_results = self.ecs_client.GetCertificates(
|
||||
serialNumber=serial_number
|
||||
).get("certificates", {})
|
||||
@@ -764,9 +760,7 @@ class EcsCertificate:
|
||||
self.cert_days = calculate_cert_days(self.cert_details.get("expiresAfter"))
|
||||
except RestOperationException as e:
|
||||
module.fail_json(
|
||||
'Failed to get details of certificate with tracking_id="{0}", Error: '.format(
|
||||
self.tracking_id
|
||||
),
|
||||
f'Failed to get details of certificate with tracking_id="{self.tracking_id}", Error: ',
|
||||
to_native(e.message),
|
||||
)
|
||||
|
||||
@@ -782,10 +776,9 @@ class EcsCertificate:
|
||||
and module.params["tracking_id"] != self.tracking_id
|
||||
):
|
||||
module.warn(
|
||||
'tracking_id parameter of "{0}" provided, but will be ignored. Valid certificate was present in path "{1}" with '
|
||||
'tracking_id of "{2}".'.format(
|
||||
module.params["tracking_id"], self.path, self.tracking_id
|
||||
)
|
||||
f'tracking_id parameter of "{module.params["tracking_id"]}" provided, but will be ignored.'
|
||||
f' Valid certificate was present in path "{self.path}" with '
|
||||
f'tracking_id of "{self.tracking_id}".'
|
||||
)
|
||||
|
||||
# If we did not end up setting tracking_id based on existing cert, get from module params
|
||||
@@ -822,10 +815,10 @@ class EcsCertificate:
|
||||
# We will be performing a reissue operation.
|
||||
if self.request_type != "new" and not self.tracking_id:
|
||||
module.warn(
|
||||
'No existing Entrust certificate found in path={0} and no tracking_id was provided, setting request_type to "new" for this task'
|
||||
"run. Future playbook runs that point to the pathination file in {1} will use request_type={2}".format(
|
||||
self.path, self.path, self.request_type
|
||||
)
|
||||
f"No existing Entrust certificate found in path={self.path}"
|
||||
' and no tracking_id was provided, setting request_type to "new" for this task'
|
||||
"run. Future playbook runs that point to the pathination file"
|
||||
f" in {self.path} will use request_type={self.request_type}"
|
||||
)
|
||||
self.request_type = "new"
|
||||
elif self.request_type == "new" and self.tracking_id:
|
||||
@@ -860,9 +853,7 @@ class EcsCertificate:
|
||||
self.set_cert_details(module)
|
||||
except RestOperationException as e:
|
||||
module.fail_json(
|
||||
msg="Failed to request new certificate from Entrust (ECS) {0}".format(
|
||||
e.message
|
||||
)
|
||||
msg=f"Failed to request new certificate from Entrust (ECS) {e.message}"
|
||||
)
|
||||
|
||||
if self.request_type != "validate_only":
|
||||
@@ -1020,9 +1011,7 @@ def main():
|
||||
MINIMAL_CRYPTOGRAPHY_VERSION
|
||||
):
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
),
|
||||
msg=missing_required_lib(f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
|
||||
@@ -1033,9 +1022,7 @@ def main():
|
||||
or module.params["request_type"] == "validate_only"
|
||||
):
|
||||
module.fail_json(
|
||||
msg='The tracking_id field is invalid when request_type="{0}".'.format(
|
||||
module.params["request_type"]
|
||||
)
|
||||
msg=f'The tracking_id field is invalid when request_type="{module.params["request_type"]}".'
|
||||
)
|
||||
|
||||
# A reissued request can not specify an expiration date or lifetime
|
||||
@@ -1053,15 +1040,12 @@ def main():
|
||||
module_params_csr = module.params["csr"]
|
||||
if module_params_csr is None:
|
||||
module.fail_json(
|
||||
msg="The csr field is required when request_type={0}".format(
|
||||
module.params["request_type"]
|
||||
)
|
||||
msg=f"The csr field is required when request_type={module.params['request_type']}"
|
||||
)
|
||||
elif not os.path.exists(module_params_csr):
|
||||
module.fail_json(
|
||||
msg="The csr field of {0} was not a valid path. csr is required when request_type={1}".format(
|
||||
module_params_csr, module.params["request_type"]
|
||||
)
|
||||
msg=f"The csr field of {module_params_csr} was not a valid path."
|
||||
f" csr is required when request_type={module.params['request_type']}"
|
||||
)
|
||||
|
||||
if module.params["ou"] and len(module.params["ou"]) > 1:
|
||||
@@ -1088,9 +1072,7 @@ def main():
|
||||
if module.params["cert_expiry"]:
|
||||
if not validate_cert_expiry(module.params["cert_expiry"]):
|
||||
module.fail_json(
|
||||
msg='The "cert_expiry" parameter of "{0}" is not a valid date or date-time'.format(
|
||||
module.params["cert_expiry"]
|
||||
)
|
||||
msg=f'The "cert_expiry" parameter of "{module.params["cert_expiry"]}" is not a valid date or date-time'
|
||||
)
|
||||
|
||||
certificate = EcsCertificate(module)
|
||||
|
||||
@@ -275,15 +275,13 @@ class EcsDomain:
|
||||
)
|
||||
except SessionConfigurationException as e:
|
||||
module.fail_json(
|
||||
msg="Failed to initialize Entrust Provider: {0}".format(to_native(e))
|
||||
msg=f"Failed to initialize Entrust Provider: {to_native(e)}"
|
||||
)
|
||||
try:
|
||||
self.ecs_client.GetAppVersion()
|
||||
except RestOperationException as e:
|
||||
module.fail_json(
|
||||
msg="Please verify credential information. Received exception when testing ECS connection: {0}".format(
|
||||
to_native(e.message)
|
||||
)
|
||||
msg=f"Please verify credential information. Received exception when testing ECS connection: {e.message}"
|
||||
)
|
||||
|
||||
def set_domain_details(self, domain_details):
|
||||
@@ -405,9 +403,7 @@ class EcsDomain:
|
||||
self.set_domain_details(result)
|
||||
except RestOperationException as e:
|
||||
module.fail_json(
|
||||
msg="Failed to request domain validation from Entrust (ECS) {0}".format(
|
||||
e.message
|
||||
)
|
||||
msg=f"Failed to request domain validation from Entrust (ECS) {e.message}"
|
||||
)
|
||||
|
||||
def dump(self):
|
||||
@@ -467,9 +463,7 @@ def main():
|
||||
and module.params["verification_method"] != "email"
|
||||
):
|
||||
module.fail_json(
|
||||
msg='The verification_email field is invalid when verification_method="{0}".'.format(
|
||||
module.params["verification_method"]
|
||||
)
|
||||
msg=f'The verification_email field is invalid when verification_method="{module.params["verification_method"]}".'
|
||||
)
|
||||
|
||||
domain = EcsDomain(module)
|
||||
|
||||
@@ -369,8 +369,7 @@ def main():
|
||||
if get_certificate_chain and sys.version_info < (3, 10):
|
||||
module.fail_json(
|
||||
msg="get_certificate_chain=true can only be used with Python 3.10 (Python 3.13+ officially supports this). "
|
||||
"The Python version used to run the get_certificate module is %s"
|
||||
% sys.version
|
||||
f"The Python version used to run the get_certificate module is {sys.version}"
|
||||
)
|
||||
|
||||
backend = module.params.get("select_crypto_backend")
|
||||
@@ -388,16 +387,14 @@ def main():
|
||||
# Success?
|
||||
if backend == "auto":
|
||||
module.fail_json(
|
||||
msg=(
|
||||
"Cannot detect the required Python library " "cryptography (>= {0})"
|
||||
).format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
msg=f"Cannot detect the required Python library cryptography (>= {MINIMAL_CRYPTOGRAPHY_VERSION})"
|
||||
)
|
||||
|
||||
if backend == "cryptography":
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"
|
||||
),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
@@ -437,14 +434,12 @@ def main():
|
||||
# Note: get_server_certificate does not support SNI!
|
||||
cert = get_server_certificate((host, port), ca_certs=ca_cert)
|
||||
except Exception as e:
|
||||
module.fail_json(
|
||||
msg="Failed to get cert from {0}:{1}, error: {2}".format(host, port, e)
|
||||
)
|
||||
module.fail_json(msg=f"Failed to get cert from {host}:{port}, error: {e}")
|
||||
else:
|
||||
# Python >= 2.7.9
|
||||
try:
|
||||
if proxy_host:
|
||||
connect = "CONNECT %s:%s HTTP/1.0\r\n\r\n" % (host, port)
|
||||
connect = f"CONNECT {host}:{port} HTTP/1.0\r\n\r\n"
|
||||
sock = socket()
|
||||
atexit.register(sock.close)
|
||||
sock.connect((proxy_host, proxy_port))
|
||||
@@ -489,9 +484,7 @@ def main():
|
||||
# If tls_ctx_option_attr is not an integer
|
||||
else:
|
||||
module.fail_json(
|
||||
msg="Failed to determine the numeric value for {0}".format(
|
||||
tls_ctx_option_str
|
||||
)
|
||||
msg=f"Failed to determine the numeric value for {tls_ctx_option_str}"
|
||||
)
|
||||
# If the item is an integer
|
||||
elif isinstance(tls_ctx_option, int):
|
||||
@@ -500,9 +493,7 @@ def main():
|
||||
# If the item is not a string nor integer
|
||||
else:
|
||||
module.fail_json(
|
||||
msg="tls_ctx_options must be a string or integer, got {0!r}".format(
|
||||
tls_ctx_option
|
||||
)
|
||||
msg=f"tls_ctx_options must be a string or integer, got {tls_ctx_option!r}"
|
||||
)
|
||||
tls_ctx_option_int = (
|
||||
0 # make pylint happy; this code is actually unreachable
|
||||
@@ -513,9 +504,7 @@ def main():
|
||||
ctx.options |= tls_ctx_option_int
|
||||
except Exception:
|
||||
module.fail_json(
|
||||
msg="Failed to add {0} to CTX options".format(
|
||||
tls_ctx_option_str or tls_ctx_option_int
|
||||
)
|
||||
msg=f"Failed to add {tls_ctx_option_str or tls_ctx_option_int} to CTX options"
|
||||
)
|
||||
|
||||
tls_sock = ctx.wrap_socket(sock, server_hostname=server_name or host)
|
||||
@@ -568,15 +557,11 @@ def main():
|
||||
except Exception as e:
|
||||
if proxy_host:
|
||||
module.fail_json(
|
||||
msg="Failed to get cert via proxy {0}:{1} from {2}:{3}, error: {4}".format(
|
||||
proxy_host, proxy_port, host, port, e
|
||||
)
|
||||
msg=f"Failed to get cert via proxy {proxy_host}:{proxy_port} from {host}:{port}, error: {e}"
|
||||
)
|
||||
else:
|
||||
module.fail_json(
|
||||
msg="Failed to get cert from {0}:{1}, error: {2}".format(
|
||||
host, port, e
|
||||
)
|
||||
msg=f"Failed to get cert from {host}:{port}, error: {e}"
|
||||
)
|
||||
|
||||
result["cert"] = cert
|
||||
|
||||
@@ -493,9 +493,7 @@ class Handler:
|
||||
return b64decode(to_native(passphrase))
|
||||
except Exception as exc:
|
||||
self._module.fail_json(
|
||||
"Error while base64-decoding '{parameter_name}': {exc}".format(
|
||||
parameter_name=parameter_name, exc=exc
|
||||
)
|
||||
f"Error while base64-decoding '{parameter_name}': {exc}"
|
||||
)
|
||||
|
||||
def _run_command(self, command, data=None):
|
||||
@@ -531,10 +529,10 @@ class Handler:
|
||||
|
||||
if result[RETURN_CODE] != 0:
|
||||
raise ValueError(
|
||||
"Error while generating LUKS name for %s: %s" % (device, result[STDERR])
|
||||
f"Error while generating LUKS name for {device}: {result[STDERR]}"
|
||||
)
|
||||
dev_uuid = result[STDOUT].strip()
|
||||
return "luks-%s" % dev_uuid
|
||||
return f"luks-{dev_uuid}"
|
||||
|
||||
|
||||
class CryptHandler(Handler):
|
||||
@@ -551,7 +549,7 @@ class CryptHandler(Handler):
|
||||
result = self._run_command([self._lsblk_bin, device, "-nlo", "type,name"])
|
||||
if result[RETURN_CODE] != 0:
|
||||
raise ValueError(
|
||||
"Error while obtaining LUKS name for %s: %s" % (device, result[STDERR])
|
||||
f"Error while obtaining LUKS name for {device}: {result[STDERR]}"
|
||||
)
|
||||
|
||||
for line in result[STDOUT].splitlines(False):
|
||||
@@ -595,9 +593,9 @@ class CryptHandler(Handler):
|
||||
"""check if a keyslot is set"""
|
||||
result = self._run_command([self._cryptsetup_bin, "luksDump", device])
|
||||
if result[RETURN_CODE] != 0:
|
||||
raise ValueError("Error while dumping LUKS header from %s" % (device,))
|
||||
result_luks1 = "Key Slot %d: ENABLED" % (keyslot) in result[STDOUT]
|
||||
result_luks2 = " %d: luks2" % (keyslot) in result[STDOUT]
|
||||
raise ValueError(f"Error while dumping LUKS header from {device}")
|
||||
result_luks1 = f"Key Slot {keyslot}: ENABLED" in result[STDOUT]
|
||||
result_luks2 = f" {keyslot}: luks2" in result[STDOUT]
|
||||
return result_luks1 or result_luks2
|
||||
|
||||
def _add_pbkdf_options(self, options, pbkdf):
|
||||
@@ -657,9 +655,7 @@ class CryptHandler(Handler):
|
||||
|
||||
result = self._run_command(args, data=passphrase)
|
||||
if result[RETURN_CODE] != 0:
|
||||
raise ValueError(
|
||||
"Error while creating LUKS on %s: %s" % (device, result[STDERR])
|
||||
)
|
||||
raise ValueError(f"Error while creating LUKS on {device}: {result[STDERR]}")
|
||||
|
||||
def run_luks_open(
|
||||
self,
|
||||
@@ -696,14 +692,13 @@ class CryptHandler(Handler):
|
||||
result = self._run_command(args, data=passphrase)
|
||||
if result[RETURN_CODE] != 0:
|
||||
raise ValueError(
|
||||
"Error while opening LUKS container on %s: %s"
|
||||
% (device, result[STDERR])
|
||||
f"Error while opening LUKS container on {device}: {result[STDERR]}"
|
||||
)
|
||||
|
||||
def run_luks_close(self, name):
|
||||
result = self._run_command([self._cryptsetup_bin, "close", name])
|
||||
if result[RETURN_CODE] != 0:
|
||||
raise ValueError("Error while closing LUKS container %s" % (name))
|
||||
raise ValueError(f"Error while closing LUKS container {name}")
|
||||
|
||||
def run_luks_remove(self, device):
|
||||
wipefs_bin = self._module.get_bin_path("wipefs", True)
|
||||
@@ -714,8 +709,7 @@ class CryptHandler(Handler):
|
||||
result = self._run_command([wipefs_bin, "--all", device])
|
||||
if result[RETURN_CODE] != 0:
|
||||
raise ValueError(
|
||||
"Error while wiping LUKS container signatures for %s: %s"
|
||||
% (device, result[STDERR])
|
||||
f"Error while wiping LUKS container signatures for {device}: {result[STDERR]}"
|
||||
)
|
||||
|
||||
# For LUKS2, sometimes both `cryptsetup erase` and `wipefs` do **not**
|
||||
@@ -725,8 +719,7 @@ class CryptHandler(Handler):
|
||||
wipe_luks_headers(device)
|
||||
except Exception as exc:
|
||||
raise ValueError(
|
||||
"Error while wiping LUKS container signatures for %s: %s"
|
||||
% (device, exc)
|
||||
f"Error while wiping LUKS container signatures for {device}: {exc}"
|
||||
)
|
||||
|
||||
def run_luks_add_key(
|
||||
@@ -766,8 +759,7 @@ class CryptHandler(Handler):
|
||||
result = self._run_command(args, data=b"".join(data) or None)
|
||||
if result[RETURN_CODE] != 0:
|
||||
raise ValueError(
|
||||
"Error while adding new LUKS keyslot to %s: %s"
|
||||
% (device, result[STDERR])
|
||||
f"Error while adding new LUKS keyslot to {device}: {result[STDERR]}"
|
||||
)
|
||||
|
||||
def run_luks_remove_key(
|
||||
@@ -779,7 +771,7 @@ class CryptHandler(Handler):
|
||||
if not force_remove_last_key:
|
||||
result = self._run_command([self._cryptsetup_bin, "luksDump", device])
|
||||
if result[RETURN_CODE] != 0:
|
||||
raise ValueError("Error while dumping LUKS header from %s" % (device,))
|
||||
raise ValueError(f"Error while dumping LUKS header from {device}")
|
||||
keyslot_count = 0
|
||||
keyslot_area = False
|
||||
keyslot_re = re.compile(r"^Key Slot [0-9]+: ENABLED")
|
||||
@@ -802,9 +794,8 @@ class CryptHandler(Handler):
|
||||
keyslot_area = False
|
||||
if keyslot_count < 2:
|
||||
self._module.fail_json(
|
||||
msg="LUKS device %s has less than two active keyslots. "
|
||||
"To be able to remove a key, please set "
|
||||
"`force_remove_last_key` to `true`." % device
|
||||
msg=f"LUKS device {device} has less than two active keyslots. "
|
||||
"To be able to remove a key, please set `force_remove_last_key` to `true`."
|
||||
)
|
||||
|
||||
if keyslot is None:
|
||||
@@ -820,7 +811,7 @@ class CryptHandler(Handler):
|
||||
result = self._run_command(args, data=passphrase)
|
||||
if result[RETURN_CODE] != 0:
|
||||
raise ValueError(
|
||||
"Error while removing LUKS key from %s: %s" % (device, result[STDERR])
|
||||
f"Error while removing LUKS key from {device}: {result[STDERR]}"
|
||||
)
|
||||
|
||||
def luks_test_key(self, device, keyfile, passphrase, keyslot=None):
|
||||
@@ -859,8 +850,7 @@ class CryptHandler(Handler):
|
||||
return False
|
||||
|
||||
raise ValueError(
|
||||
"Error while testing whether keyslot exists on %s: %s"
|
||||
% (device, result[STDERR])
|
||||
f"Error while testing whether keyslot exists on {device}: {result[STDERR]}"
|
||||
)
|
||||
|
||||
|
||||
@@ -921,8 +911,7 @@ class ConditionsHandler(Handler):
|
||||
# the container is already open but with different name:
|
||||
# suspicious. back off
|
||||
self._module.fail_json(
|
||||
msg="LUKS container is already opened "
|
||||
"under different name '%s'." % name
|
||||
msg=f"LUKS container is already opened under different name '{name}'."
|
||||
)
|
||||
|
||||
# container is opened and the names match
|
||||
@@ -1069,13 +1058,11 @@ class ConditionsHandler(Handler):
|
||||
|
||||
if luks_type == "luks1" and not 0 <= self._module.params[param] <= 7:
|
||||
self._module.fail_json(
|
||||
msg="%s must be between 0 and 7 when using LUKS1."
|
||||
% self._module.params[param]
|
||||
msg=f"{self._module.params[param]} must be between 0 and 7 when using LUKS1."
|
||||
)
|
||||
elif luks_type == "luks2" and not 0 <= self._module.params[param] <= 31:
|
||||
self._module.fail_json(
|
||||
msg="%s must be between 0 and 31 when using LUKS2."
|
||||
% self._module.params[param]
|
||||
msg=f"{self._module.params[param]} must be between 0 and 31 when using LUKS2."
|
||||
)
|
||||
|
||||
|
||||
@@ -1151,7 +1138,7 @@ def run_module():
|
||||
statinfo = os.stat(module.params["device"])
|
||||
mode = statinfo.st_mode
|
||||
if not stat.S_ISBLK(mode) and not stat.S_ISCHR(mode):
|
||||
raise Exception("{0} is not a device".format(module.params["device"]))
|
||||
raise Exception(f"{module.params['device']} is not a device")
|
||||
except Exception as e:
|
||||
module.fail_json(msg=str(e))
|
||||
|
||||
@@ -1202,7 +1189,7 @@ def run_module():
|
||||
module.params["pbkdf"],
|
||||
)
|
||||
except ValueError as e:
|
||||
module.fail_json(msg="luks_device error: %s" % e)
|
||||
module.fail_json(msg=f"luks_device error: {e}")
|
||||
result["changed"] = True
|
||||
if module.check_mode:
|
||||
module.exit_json(**result)
|
||||
@@ -1219,7 +1206,7 @@ def run_module():
|
||||
try:
|
||||
name = crypt.generate_luks_name(conditions.device)
|
||||
except ValueError as e:
|
||||
module.fail_json(msg="luks_device error: %s" % e)
|
||||
module.fail_json(msg=f"luks_device error: {e}")
|
||||
if not module.check_mode:
|
||||
try:
|
||||
crypt.run_luks_open(
|
||||
@@ -1235,7 +1222,7 @@ def run_module():
|
||||
name,
|
||||
)
|
||||
except ValueError as e:
|
||||
module.fail_json(msg="luks_device error: %s" % e)
|
||||
module.fail_json(msg=f"luks_device error: {e}")
|
||||
result["name"] = name
|
||||
result["changed"] = True
|
||||
if module.check_mode:
|
||||
@@ -1247,14 +1234,14 @@ def run_module():
|
||||
try:
|
||||
name = crypt.get_container_name_by_device(conditions.device)
|
||||
except ValueError as e:
|
||||
module.fail_json(msg="luks_device error: %s" % e)
|
||||
module.fail_json(msg=f"luks_device error: {e}")
|
||||
else:
|
||||
name = module.params["name"]
|
||||
if not module.check_mode:
|
||||
try:
|
||||
crypt.run_luks_close(name)
|
||||
except ValueError as e:
|
||||
module.fail_json(msg="luks_device error: %s" % e)
|
||||
module.fail_json(msg=f"luks_device error: {e}")
|
||||
result["name"] = name
|
||||
result["changed"] = True
|
||||
if module.check_mode:
|
||||
@@ -1274,7 +1261,7 @@ def run_module():
|
||||
module.params["pbkdf"],
|
||||
)
|
||||
except ValueError as e:
|
||||
module.fail_json(msg="luks_device error: %s" % e)
|
||||
module.fail_json(msg=f"luks_device error: {e}")
|
||||
result["changed"] = True
|
||||
if module.check_mode:
|
||||
module.exit_json(**result)
|
||||
@@ -1292,7 +1279,7 @@ def run_module():
|
||||
force_remove_last_key=last_key,
|
||||
)
|
||||
except ValueError as e:
|
||||
module.fail_json(msg="luks_device error: %s" % e)
|
||||
module.fail_json(msg=f"luks_device error: {e}")
|
||||
result["changed"] = True
|
||||
if module.check_mode:
|
||||
module.exit_json(**result)
|
||||
@@ -1303,7 +1290,7 @@ def run_module():
|
||||
try:
|
||||
crypt.run_luks_remove(conditions.device)
|
||||
except ValueError as e:
|
||||
module.fail_json(msg="luks_device error: %s" % e)
|
||||
module.fail_json(msg=f"luks_device error: {e}")
|
||||
result["changed"] = True
|
||||
if module.check_mode:
|
||||
module.exit_json(**result)
|
||||
|
||||
@@ -360,7 +360,7 @@ class Certificate(OpensshModule):
|
||||
elif LooseVersion(ssh_version) < LooseVersion("7.6"):
|
||||
self.module.fail_json(
|
||||
msg="Signing with CA key in ssh agent requires ssh 7.6 or newer."
|
||||
+ " Your version is: %s" % ssh_version
|
||||
+ f" Your version is: {ssh_version}"
|
||||
)
|
||||
|
||||
def _exists(self):
|
||||
@@ -371,10 +371,8 @@ class Certificate(OpensshModule):
|
||||
self.original_data = OpensshCertificate.load(self.path)
|
||||
except (TypeError, ValueError) as e:
|
||||
if self.regenerate in ("never", "fail"):
|
||||
self.module.fail_json(
|
||||
msg="Unable to read existing certificate: %s" % to_native(e)
|
||||
)
|
||||
self.module.warn("Unable to read existing certificate: %s" % to_native(e))
|
||||
self.module.fail_json(msg=f"Unable to read existing certificate: {e}")
|
||||
self.module.warn(f"Unable to read existing certificate: {e}")
|
||||
|
||||
def _set_time_parameters(self):
|
||||
try:
|
||||
@@ -486,15 +484,13 @@ class Certificate(OpensshModule):
|
||||
self._safe_secure_move([(temp_certificate, self.path)])
|
||||
except OSError as e:
|
||||
self.module.fail_json(
|
||||
msg="Unable to write certificate to %s: %s" % (self.path, to_native(e))
|
||||
msg=f"Unable to write certificate to {self.path}: {e}"
|
||||
)
|
||||
|
||||
try:
|
||||
self.data = OpensshCertificate.load(self.path)
|
||||
except (TypeError, ValueError) as e:
|
||||
self.module.fail_json(
|
||||
msg="Unable to read new certificate: %s" % to_native(e)
|
||||
)
|
||||
self.module.fail_json(msg=f"Unable to read new certificate: {e}")
|
||||
|
||||
def _generate_temp_certificate(self):
|
||||
key_copy = os.path.join(self.module.tmpdir, os.path.basename(self.public_key))
|
||||
@@ -502,9 +498,7 @@ class Certificate(OpensshModule):
|
||||
try:
|
||||
self.module.preserved_copy(self.public_key, key_copy)
|
||||
except OSError as e:
|
||||
self.module.fail_json(
|
||||
msg="Unable to stage temporary key: %s" % to_native(e)
|
||||
)
|
||||
self.module.fail_json(msg=f"Unable to stage temporary key: {e}")
|
||||
self.module.add_cleanup_file(key_copy)
|
||||
|
||||
self.ssh_keygen.generate_certificate(
|
||||
@@ -535,7 +529,7 @@ class Certificate(OpensshModule):
|
||||
os.remove(self.path)
|
||||
except OSError as e:
|
||||
self.module.fail_json(
|
||||
msg="Unable to remove existing certificate: %s" % to_native(e)
|
||||
msg=f"Unable to remove existing certificate: {to_native(e)}"
|
||||
)
|
||||
|
||||
@property
|
||||
|
||||
@@ -337,8 +337,7 @@ def main():
|
||||
if not os.path.isdir(base_dir):
|
||||
module.fail_json(
|
||||
name=base_dir,
|
||||
msg="The directory %s does not exist or the file is not a directory"
|
||||
% base_dir,
|
||||
msg=f"The directory {base_dir} does not exist or the file is not a directory",
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
@@ -341,9 +341,7 @@ def main():
|
||||
with open(module.params["path"], "rb") as f:
|
||||
data = f.read()
|
||||
except (IOError, OSError) as e:
|
||||
module.fail_json(
|
||||
msg="Error while reading CSR file from disk: {0}".format(e)
|
||||
)
|
||||
module.fail_json(msg=f"Error while reading CSR file from disk: {e}")
|
||||
|
||||
backend, module_backend = select_backend(
|
||||
module, module.params["select_crypto_backend"], data, validate_signature=True
|
||||
|
||||
@@ -285,7 +285,7 @@ class DHParameterOpenSSL(DHParameterBase):
|
||||
try:
|
||||
module.atomic_move(os.path.abspath(tmpsrc), os.path.abspath(self.path))
|
||||
except Exception as e:
|
||||
module.fail_json(msg="Failed to write to file %s: %s" % (self.path, str(e)))
|
||||
module.fail_json(msg=f"Failed to write to file {self.path}: {str(e)}")
|
||||
|
||||
def _check_params_valid(self, module):
|
||||
"""Check if the params are in the correct state"""
|
||||
@@ -381,8 +381,7 @@ def main():
|
||||
if not os.path.isdir(base_dir):
|
||||
module.fail_json(
|
||||
name=base_dir,
|
||||
msg="The directory '%s' does not exist or the file is not a directory"
|
||||
% base_dir,
|
||||
msg=f"The directory '{base_dir}' does not exist or the file is not a directory",
|
||||
)
|
||||
|
||||
if module.params["state"] == "present":
|
||||
@@ -405,9 +404,9 @@ def main():
|
||||
if backend == "auto":
|
||||
module.fail_json(
|
||||
msg=(
|
||||
"Cannot detect either the required Python library cryptography (>= {0}) "
|
||||
f"Cannot detect either the required Python library cryptography (>= {MINIMAL_CRYPTOGRAPHY_VERSION}) "
|
||||
"or the OpenSSL binary openssl"
|
||||
).format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
)
|
||||
)
|
||||
|
||||
if backend == "openssl":
|
||||
@@ -416,7 +415,7 @@ def main():
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"
|
||||
),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
|
||||
@@ -737,24 +737,20 @@ def select_backend(module, backend):
|
||||
# Success?
|
||||
if backend == "auto":
|
||||
module.fail_json(
|
||||
msg=(
|
||||
"Cannot detect the required Python library cryptography (>= {0})"
|
||||
).format(
|
||||
MINIMAL_CRYPTOGRAPHY_VERSION,
|
||||
)
|
||||
msg=f"Cannot detect the required Python library cryptography (>= {MINIMAL_CRYPTOGRAPHY_VERSION})"
|
||||
)
|
||||
|
||||
if backend == "cryptography":
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"
|
||||
),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
return backend, PkcsCryptography(module)
|
||||
else:
|
||||
raise ValueError("Unsupported value for backend: {0}".format(backend))
|
||||
raise ValueError(f"Unsupported value for backend: {backend}")
|
||||
|
||||
|
||||
def main():
|
||||
@@ -812,8 +808,7 @@ def main():
|
||||
if not os.path.isdir(base_dir):
|
||||
module.fail_json(
|
||||
name=base_dir,
|
||||
msg="The directory '%s' does not exist or the path is not a directory"
|
||||
% base_dir,
|
||||
msg=f"The directory '{base_dir}' does not exist or the path is not a directory",
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -862,7 +857,7 @@ def main():
|
||||
result = pkcs12.dump()
|
||||
result["changed"] = changed
|
||||
if os.path.exists(module.params["path"]):
|
||||
file_mode = "%04o" % stat.S_IMODE(os.stat(module.params["path"]).st_mode)
|
||||
file_mode = f"{stat.S_IMODE(os.stat(module.params['path']).st_mode):04o}"
|
||||
result["mode"] = file_mode
|
||||
|
||||
module.exit_json(**result)
|
||||
|
||||
@@ -268,8 +268,7 @@ def main():
|
||||
if not os.path.isdir(base_dir):
|
||||
module.fail_json(
|
||||
name=base_dir,
|
||||
msg="The directory %s does not exist or the file is not a directory"
|
||||
% base_dir,
|
||||
msg=f"The directory {base_dir} does not exist or the file is not a directory",
|
||||
)
|
||||
|
||||
backend, module_backend = select_backend(
|
||||
|
||||
@@ -146,8 +146,7 @@ def main():
|
||||
if not os.path.isdir(base_dir):
|
||||
module.fail_json(
|
||||
name=base_dir,
|
||||
msg="The directory %s does not exist or the file is not a directory"
|
||||
% base_dir,
|
||||
msg=f"The directory {base_dir} does not exist or the file is not a directory",
|
||||
)
|
||||
|
||||
module_backend = select_backend(module=module)
|
||||
|
||||
@@ -242,8 +242,7 @@ def main():
|
||||
data = f.read()
|
||||
except (IOError, OSError) as e:
|
||||
module.fail_json(
|
||||
msg="Error while reading private key file from disk: {0}".format(e),
|
||||
**result,
|
||||
msg=f"Error while reading private key file from disk: {e}", **result
|
||||
)
|
||||
|
||||
result["can_load_key"] = True
|
||||
|
||||
@@ -301,7 +301,7 @@ class PublicKey(OpenSSLObject):
|
||||
|
||||
if self.privatekey_content is None and not os.path.exists(self.privatekey_path):
|
||||
raise PublicKeyError(
|
||||
"The private key %s does not exist" % self.privatekey_path
|
||||
f"The private key {self.privatekey_path} does not exist"
|
||||
)
|
||||
|
||||
if not self.check(module, perms_required=False) or self.force:
|
||||
@@ -461,9 +461,7 @@ def main():
|
||||
# Success?
|
||||
if backend == "auto":
|
||||
module.fail_json(
|
||||
msg=(
|
||||
"Cannot detect the required Python library " "cryptography (>= {0})"
|
||||
).format(minimal_cryptography_version)
|
||||
msg=f"Cannot detect the required Python library cryptography (>= {minimal_cryptography_version})",
|
||||
)
|
||||
|
||||
if module.params["format"] == "OpenSSH" and backend != "cryptography":
|
||||
@@ -473,7 +471,7 @@ def main():
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(minimal_cryptography_version)
|
||||
f"cryptography >= {minimal_cryptography_version}"
|
||||
),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
@@ -482,8 +480,7 @@ def main():
|
||||
if not os.path.isdir(base_dir):
|
||||
module.fail_json(
|
||||
name=base_dir,
|
||||
msg="The directory '%s' does not exist or the file is not a directory"
|
||||
% base_dir,
|
||||
msg=f"The directory '{base_dir}' does not exist or the file is not a directory",
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
@@ -190,8 +190,7 @@ def main():
|
||||
data = f.read()
|
||||
except (IOError, OSError) as e:
|
||||
module.fail_json(
|
||||
msg="Error while reading public key file from disk: {0}".format(e),
|
||||
**result,
|
||||
msg=f"Error while reading public key file from disk: {e}", **result
|
||||
)
|
||||
|
||||
backend, module_backend = select_backend(
|
||||
|
||||
@@ -230,9 +230,7 @@ class SignatureCryptography(SignatureBase):
|
||||
|
||||
if signature is None:
|
||||
self.module.fail_json(
|
||||
msg="Unsupported key type. Your cryptography version is {0}".format(
|
||||
CRYPTOGRAPHY_VERSION
|
||||
)
|
||||
msg=f"Unsupported key type. Your cryptography version is {CRYPTOGRAPHY_VERSION}"
|
||||
)
|
||||
|
||||
result["signature"] = base64.b64encode(signature)
|
||||
@@ -261,7 +259,7 @@ def main():
|
||||
if not os.path.isfile(module.params["path"]):
|
||||
module.fail_json(
|
||||
name=module.params["path"],
|
||||
msg="The file {0} does not exist".format(module.params["path"]),
|
||||
msg=f"The file {module.params['path']} does not exist",
|
||||
)
|
||||
|
||||
backend = module.params["select_crypto_backend"]
|
||||
@@ -279,16 +277,14 @@ def main():
|
||||
# Success?
|
||||
if backend == "auto":
|
||||
module.fail_json(
|
||||
msg=(
|
||||
"Cannot detect the required Python library " "cryptography (>= {0})"
|
||||
).format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
msg=f"Cannot detect the required Python library cryptography (>= {MINIMAL_CRYPTOGRAPHY_VERSION})",
|
||||
)
|
||||
try:
|
||||
if backend == "cryptography":
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"
|
||||
),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
|
||||
@@ -252,9 +252,7 @@ class SignatureInfoCryptography(SignatureInfoBase):
|
||||
|
||||
if not verified:
|
||||
self.module.fail_json(
|
||||
msg="Unsupported key type. Your cryptography version is {0}".format(
|
||||
CRYPTOGRAPHY_VERSION
|
||||
)
|
||||
msg=f"Unsupported key type. Your cryptography version is {CRYPTOGRAPHY_VERSION}"
|
||||
)
|
||||
result["valid"] = valid
|
||||
return result
|
||||
@@ -282,7 +280,7 @@ def main():
|
||||
if not os.path.isfile(module.params["path"]):
|
||||
module.fail_json(
|
||||
name=module.params["path"],
|
||||
msg="The file {0} does not exist".format(module.params["path"]),
|
||||
msg=f"The file {module.params['path']} does not exist",
|
||||
)
|
||||
|
||||
backend = module.params["select_crypto_backend"]
|
||||
@@ -300,17 +298,14 @@ def main():
|
||||
# Success?
|
||||
if backend == "auto":
|
||||
module.fail_json(
|
||||
msg=(
|
||||
"Cannot detect any of the required Python libraries "
|
||||
"cryptography (>= {0})"
|
||||
).format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
msg=f"Cannot detect any of the required Python libraries cryptography (>= {MINIMAL_CRYPTOGRAPHY_VERSION})"
|
||||
)
|
||||
try:
|
||||
if backend == "cryptography":
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"
|
||||
),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
|
||||
@@ -386,8 +386,7 @@ def main():
|
||||
if not os.path.isdir(base_dir):
|
||||
module.fail_json(
|
||||
name=base_dir,
|
||||
msg="The directory %s does not exist or the file is not a directory"
|
||||
% base_dir,
|
||||
msg=f"The directory {base_dir} does not exist or the file is not a directory",
|
||||
)
|
||||
|
||||
provider = module.params["provider"]
|
||||
|
||||
@@ -152,16 +152,12 @@ def parse_certificate(input, strict=False):
|
||||
pems = split_pem_list(to_text(input))
|
||||
if len(pems) > 1 and strict:
|
||||
raise ValueError(
|
||||
"The input contains {count} PEM objects, expecting only one since strict=true".format(
|
||||
count=len(pems)
|
||||
)
|
||||
f"The input contains {len(pems)} PEM objects, expecting only one since strict=true"
|
||||
)
|
||||
pem_header_type, content = extract_pem(pems[0], strict=strict)
|
||||
if strict and pem_header_type not in ("CERTIFICATE", "X509 CERTIFICATE"):
|
||||
raise ValueError(
|
||||
"type is {type!r}, expecting CERTIFICATE or X509 CERTIFICATE".format(
|
||||
type=pem_header_type
|
||||
)
|
||||
f"type is {pem_header_type!r}, expecting CERTIFICATE or X509 CERTIFICATE"
|
||||
)
|
||||
input = base64.b64decode(content)
|
||||
else:
|
||||
@@ -187,18 +183,14 @@ class X509CertificateConvertModule(OpenSSLObject):
|
||||
try:
|
||||
self.input = base64.b64decode(self.input)
|
||||
except Exception as exc:
|
||||
module.fail_json(
|
||||
msg="Cannot Base64 decode src_content: {exc}".format(exc=exc)
|
||||
)
|
||||
module.fail_json(msg=f"Cannot Base64 decode src_content: {exc}")
|
||||
else:
|
||||
try:
|
||||
with open(self.src_path, "rb") as f:
|
||||
self.input = f.read()
|
||||
except Exception as exc:
|
||||
module.fail_json(
|
||||
msg="Failure while reading file {fn}: {exc}".format(
|
||||
fn=self.src_path, exc=exc
|
||||
)
|
||||
msg=f"Failure while reading file {self.src_path}: {exc}"
|
||||
)
|
||||
|
||||
self.format = module.params["format"]
|
||||
@@ -210,7 +202,7 @@ class X509CertificateConvertModule(OpenSSLObject):
|
||||
self.input, strict=self.strict
|
||||
)
|
||||
except Exception as exc:
|
||||
module.fail_json(msg="Error while parsing PEM: {exc}".format(exc=exc))
|
||||
module.fail_json(msg=f"Error while parsing PEM: {exc}")
|
||||
|
||||
if module.params["verify_cert_parsable"]:
|
||||
self.verify_cert_parsable(module)
|
||||
@@ -237,16 +229,14 @@ class X509CertificateConvertModule(OpenSSLObject):
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"
|
||||
),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
try:
|
||||
load_der_x509_certificate(self.input, default_backend())
|
||||
except Exception as exc:
|
||||
module.fail_json(
|
||||
msg="Error while parsing certificate: {exc}".format(exc=exc)
|
||||
)
|
||||
module.fail_json(msg=f"Error while parsing certificate: {exc}")
|
||||
|
||||
def needs_conversion(self):
|
||||
if self.dest_content is None or self.dest_content_format is None:
|
||||
@@ -263,11 +253,9 @@ class X509CertificateConvertModule(OpenSSLObject):
|
||||
if self.format == "der":
|
||||
return self.input
|
||||
data = to_bytes(base64.b64encode(self.input))
|
||||
lines = [to_bytes("{0}{1}{2}".format(PEM_START, self.wanted_pem_type, PEM_END))]
|
||||
lines = [to_bytes(f"{PEM_START}{self.wanted_pem_type}{PEM_END}")]
|
||||
lines += [data[i : i + 64] for i in range(0, len(data), 64)]
|
||||
lines.append(
|
||||
to_bytes("{0}{1}{2}\n".format(PEM_END_START, self.wanted_pem_type, PEM_END))
|
||||
)
|
||||
lines.append(to_bytes(f"{PEM_END_START}{self.wanted_pem_type}{PEM_END}\n"))
|
||||
return b"\n".join(lines)
|
||||
|
||||
def generate(self, module):
|
||||
@@ -323,8 +311,7 @@ def main():
|
||||
if not os.path.isdir(base_dir):
|
||||
module.fail_json(
|
||||
name=base_dir,
|
||||
msg="The directory %s does not exist or the file is not a directory"
|
||||
% base_dir,
|
||||
msg=f"The directory {base_dir} does not exist or the file is not a directory",
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
@@ -431,9 +431,7 @@ def main():
|
||||
with open(module.params["path"], "rb") as f:
|
||||
data = f.read()
|
||||
except (IOError, OSError) as e:
|
||||
module.fail_json(
|
||||
msg="Error while reading certificate file from disk: {0}".format(e)
|
||||
)
|
||||
module.fail_json(msg=f"Error while reading certificate file from disk: {e}")
|
||||
|
||||
backend, module_backend = select_backend(
|
||||
module, module.params["select_crypto_backend"], data
|
||||
@@ -444,12 +442,10 @@ def main():
|
||||
for k, v in valid_at.items():
|
||||
if not isinstance(v, string_types):
|
||||
module.fail_json(
|
||||
msg="The value for valid_at.{0} must be of type string (got {1})".format(
|
||||
k, type(v)
|
||||
)
|
||||
msg=f"The value for valid_at.{k} must be of type string (got {type(v)})"
|
||||
)
|
||||
valid_at[k] = get_relative_time_option(
|
||||
v, "valid_at.{0}".format(k), with_timezone=CRYPTOGRAPHY_TIMEZONE
|
||||
v, f"valid_at.{k}", with_timezone=CRYPTOGRAPHY_TIMEZONE
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
@@ -560,9 +560,7 @@ class CRL(OpenSSLObject):
|
||||
|
||||
self.digest = select_message_digest(module.params["digest"])
|
||||
if self.digest is None:
|
||||
raise CRLError(
|
||||
'The digest "{0}" is not supported'.format(module.params["digest"])
|
||||
)
|
||||
raise CRLError(f'The digest "{module.params["digest"]}" is not supported')
|
||||
|
||||
self.module = module
|
||||
|
||||
@@ -578,7 +576,7 @@ class CRL(OpenSSLObject):
|
||||
"invalidity_date": None,
|
||||
"invalidity_date_critical": False,
|
||||
}
|
||||
path_prefix = "revoked_certificates[{0}].".format(i)
|
||||
path_prefix = f"revoked_certificates[{i}]."
|
||||
if rc["path"] is not None or rc["content"] is not None:
|
||||
# Load certificate from file or content
|
||||
try:
|
||||
@@ -591,15 +589,11 @@ class CRL(OpenSSLObject):
|
||||
except OpenSSLObjectError as e:
|
||||
if rc["content"] is not None:
|
||||
module.fail_json(
|
||||
msg="Cannot parse certificate from {0}content: {1}".format(
|
||||
path_prefix, to_native(e)
|
||||
)
|
||||
msg=f"Cannot parse certificate from {path_prefix}content: {e}"
|
||||
)
|
||||
else:
|
||||
module.fail_json(
|
||||
msg='Cannot read certificate "{1}" from {0}path: {2}'.format(
|
||||
path_prefix, rc["path"], to_native(e)
|
||||
)
|
||||
msg=f'Cannot read certificate "{rc["path"]}" from {path_prefix}path: {e}'
|
||||
)
|
||||
else:
|
||||
# Specify serial_number (and potentially issuer) directly
|
||||
@@ -668,23 +662,17 @@ class CRL(OpenSSLObject):
|
||||
return check_type_int(value)
|
||||
except TypeError as exc:
|
||||
self.module.fail_json(
|
||||
msg="Error while parsing revoked_certificates[{idx}].serial_number as an integer: {exc}".format(
|
||||
idx=index + 1,
|
||||
exc=to_native(exc),
|
||||
)
|
||||
msg=f"Error while parsing revoked_certificates[{index + 1}].serial_number as an integer: {exc}"
|
||||
)
|
||||
if self.serial_numbers_format == "hex-octets":
|
||||
try:
|
||||
return parse_serial(check_type_str(value))
|
||||
except (TypeError, ValueError) as exc:
|
||||
self.module.fail_json(
|
||||
msg="Error while parsing revoked_certificates[{idx}].serial_number as an colon-separated hex octet string: {exc}".format(
|
||||
idx=index + 1,
|
||||
exc=to_native(exc),
|
||||
)
|
||||
msg=f"Error while parsing revoked_certificates[{index + 1}].serial_number as an colon-separated hex octet string: {exc}"
|
||||
)
|
||||
raise RuntimeError(
|
||||
"Unexpected value %s of serial_numbers" % (self.serial_numbers_format,)
|
||||
f"Unexpected value {self.serial_numbers_format} of serial_numbers"
|
||||
)
|
||||
|
||||
def _get_info(self, data):
|
||||
@@ -1026,9 +1014,7 @@ def main():
|
||||
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
),
|
||||
msg=missing_required_lib(f"cryptography >= {MINIMAL_CRYPTOGRAPHY_VERSION}"),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
|
||||
|
||||
@@ -207,18 +207,14 @@ def main():
|
||||
with open(module.params["path"], "rb") as f:
|
||||
data = f.read()
|
||||
except (IOError, OSError) as e:
|
||||
module.fail_json(
|
||||
msg="Error while reading CRL file from disk: {0}".format(e)
|
||||
)
|
||||
module.fail_json(msg=f"Error while reading CRL file from disk: {e}")
|
||||
else:
|
||||
data = module.params["content"].encode("utf-8")
|
||||
if not identify_pem_format(data):
|
||||
try:
|
||||
data = base64.b64decode(module.params["content"])
|
||||
except (binascii.Error, TypeError) as e:
|
||||
module.fail_json(
|
||||
msg="Error while Base64 decoding content: {0}".format(e)
|
||||
)
|
||||
module.fail_json(msg=f"Error while Base64 decoding content: {e}")
|
||||
|
||||
try:
|
||||
result = get_crl_info(
|
||||
|
||||
Reference in New Issue
Block a user