Replace % and str.format() with f-strings (#875)

* Replace % and str.format() with f-strings.

* Apply suggestions from review.
This commit is contained in:
Felix Fontein
2025-05-01 11:50:10 +02:00
committed by GitHub
parent d8f838c365
commit 641e63b08c
86 changed files with 544 additions and 1036 deletions

View File

@@ -363,16 +363,14 @@ def select_backend(module, backend, provider):
# Fail if no backend has been found
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,
)

View File

@@ -31,17 +31,17 @@ class AcmeCertificateBackend(CertificateBackend):
)
if self.csr_content is None and not os.path.exists(self.csr_path):
raise CertificateError(
"The certificate signing request file %s does not exist" % self.csr_path
f"The certificate signing request file {self.csr_path} does not exist"
)
if not os.path.exists(self.accountkey_path):
raise CertificateError(
"The account key %s does not exist" % self.accountkey_path
f"The account key {self.accountkey_path} does not exist"
)
if not os.path.exists(self.challenge_path):
raise CertificateError(
"The challenge path %s does not exist" % self.challenge_path
f"The challenge path {self.challenge_path} does not exist"
)
self.acme_tiny_path = self.module.get_bin_path("acme-tiny", required=True)
@@ -66,7 +66,7 @@ class AcmeCertificateBackend(CertificateBackend):
except Exception:
pass
self.module.fail_json(
msg="failed to create temporary CSR file: %s" % to_native(err),
msg=f"failed to create temporary CSR file: {to_native(err)}",
exception=traceback.format_exc(),
)
f.close()

View File

@@ -56,9 +56,7 @@ class EntrustCertificateBackend(CertificateBackend):
)
if self.csr_content is None and not os.path.exists(self.csr_path):
raise CertificateError(
"The certificate signing request file {0} does not exist".format(
self.csr_path
)
f"The certificate signing request file {self.csr_path} does not exist"
)
self._ensure_csr_loaded()
@@ -77,7 +75,7 @@ class EntrustCertificateBackend(CertificateBackend):
self.module.fail_json(
msg=(
"Entrust provider does not currently support multiple validated organizations. Multiple organizations found in "
"Subject DN: '{0}'. ".format(self.csr.subject)
f"Subject DN: '{self.csr.subject}'. "
)
)
# If no organization in the CSR, explicitly tell ECS that it should be blank in issued cert, not defaulted to
@@ -98,11 +96,7 @@ class EntrustCertificateBackend(CertificateBackend):
],
)
except SessionConfigurationException as e:
module.fail_json(
msg="Failed to initialize Entrust Provider: {0}".format(
to_native(e.message)
)
)
module.fail_json(msg=f"Failed to initialize Entrust Provider: {e.message}")
def generate_certificate(self):
"""(Re-)Generate certificate."""
@@ -138,9 +132,7 @@ class EntrustCertificateBackend(CertificateBackend):
self.trackingId = result.get("trackingId")
except RestOperationException as e:
self.module.fail_json(
msg="Failed to request new certificate from Entrust Certificate Services (ECS): {0}".format(
to_native(e.message)
)
msg=f"Failed to request new certificate from Entrust Certificate Services (ECS): {e.message}"
)
self.cert_bytes = to_bytes(result.get("endEntityCert"))
@@ -159,9 +151,7 @@ class EntrustCertificateBackend(CertificateBackend):
cert_details = self._get_cert_details()
except RestOperationException as e:
self.module.fail_json(
msg="Failed to get status of existing certificate from Entrust Certificate Services (ECS): {0}.".format(
to_native(e.message)
)
msg=f"Failed to get status of existing certificate from Entrust Certificate Services (ECS): {e.message}."
)
# Always issue a new certificate if the certificate is expired, suspended or revoked
@@ -189,8 +179,8 @@ class EntrustCertificateBackend(CertificateBackend):
serial_number = None
expiry = None
if self.backend == "cryptography":
serial_number = "{0:X}".format(
cryptography_serial_number_of_cert(self.existing_certificate)
serial_number = (
f"{cryptography_serial_number_of_cert(self.existing_certificate):X}"
)
expiry = get_not_valid_after(self.existing_certificate)

View File

@@ -332,11 +332,9 @@ class CertificateInfoRetrievalCryptography(CertificateInfoRetrieval):
x509.BasicConstraints
)
result = []
result.append(
"CA:{0}".format("TRUE" if ext_keyusage_ext.value.ca else "FALSE")
)
result.append(f"CA:{'TRUE' if ext_keyusage_ext.value.ca else 'FALSE'}")
if ext_keyusage_ext.value.path_length is not None:
result.append("pathlen:{0}".format(ext_keyusage_ext.value.path_length))
result.append(f"pathlen:{ext_keyusage_ext.value.path_length}")
return sorted(result), ext_keyusage_ext.critical
except cryptography.x509.ExtensionNotFound:
return None, False
@@ -474,20 +472,17 @@ def select_backend(module, backend, content):
# 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})"
)
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, CertificateInfoRetrievalCryptography(module, content)
else:
raise ValueError("Unsupported value for backend: {0}".format(backend))
raise ValueError(f"Unsupported value for backend: {backend}")

View File

@@ -93,21 +93,17 @@ class OwnCACertificateBackendCryptography(CertificateBackend):
)
if self.csr_content is None and not os.path.exists(self.csr_path):
raise CertificateError(
"The certificate signing request file {0} does not exist".format(
self.csr_path
)
f"The certificate signing request file {self.csr_path} does not exist"
)
if self.ca_cert_content is None and not os.path.exists(self.ca_cert_path):
raise CertificateError(
"The CA certificate file {0} does not exist".format(self.ca_cert_path)
f"The CA certificate file {self.ca_cert_path} does not exist"
)
if self.ca_privatekey_content is None and not os.path.exists(
self.ca_privatekey_path
):
raise CertificateError(
"The CA private key file {0} does not exist".format(
self.ca_privatekey_path
)
f"The CA private key file {self.ca_privatekey_path} does not exist"
)
self._ensure_csr_loaded()
@@ -134,8 +130,7 @@ class OwnCACertificateBackendCryptography(CertificateBackend):
if cryptography_key_needs_digest_for_signing(self.ca_private_key):
if self.digest is None:
raise CertificateError(
"The digest %s is not supported with the cryptography backend"
% module.params["ownca_digest"]
f"The digest {module.params['ownca_digest']} is not supported with the cryptography backend"
)
else:
self.digest = None

View File

@@ -67,13 +67,11 @@ class SelfSignedCertificateBackendCryptography(CertificateBackend):
if self.csr_path is not None and not os.path.exists(self.csr_path):
raise CertificateError(
"The certificate signing request file {0} does not exist".format(
self.csr_path
)
f"The certificate signing request file {self.csr_path} does not exist"
)
if self.privatekey_content is None and not os.path.exists(self.privatekey_path):
raise CertificateError(
"The private key file {0} does not exist".format(self.privatekey_path)
f"The private key file {self.privatekey_path} does not exist"
)
self._module = module
@@ -90,9 +88,7 @@ class SelfSignedCertificateBackendCryptography(CertificateBackend):
digest = self.digest
if digest is None:
self.module.fail_json(
msg='Unsupported digest "{0}"'.format(
module.params["selfsigned_digest"]
)
msg=f'Unsupported digest "{module.params["selfsigned_digest"]}"'
)
try:
self.csr = csr.sign(self.privatekey, digest, default_backend())
@@ -109,8 +105,7 @@ class SelfSignedCertificateBackendCryptography(CertificateBackend):
if cryptography_key_needs_digest_for_signing(self.privatekey):
if self.digest is None:
raise CertificateError(
"The digest %s is not supported with the cryptography backend"
% module.params["selfsigned_digest"]
f"The digest {module.params['selfsigned_digest']} is not supported with the cryptography backend"
)
else:
self.digest = None

View File

@@ -58,7 +58,7 @@ class CRLInfoRetrieval:
else:
self.crl = x509.load_der_x509_crl(self.content, default_backend())
except ValueError as e:
self.module.fail_json(msg="Error while decoding CRL: {0}".format(e))
self.module.fail_json(msg=f"Error while decoding CRL: {e}")
result = {
"changed": False,
@@ -96,9 +96,7 @@ class CRLInfoRetrieval:
def get_crl_info(module, content, list_revoked_certificates=True):
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,
)

View File

@@ -163,7 +163,7 @@ class CertificateSigningRequestBackend:
if not self.subjectAltName and module.params["use_common_name_for_san"]:
for sub in self.subject:
if sub[0] in ("commonName", "CN"):
self.subjectAltName = ["DNS:%s" % sub[1]]
self.subjectAltName = [f"DNS:{sub[1]}"]
self.using_common_name_for_san = True
break
@@ -174,7 +174,7 @@ class CertificateSigningRequestBackend:
)
except Exception as e:
raise CertificateSigningRequestError(
"Cannot parse subject_key_identifier: {0}".format(e)
f"Cannot parse subject_key_identifier: {e}"
)
if self.authority_key_identifier is not None:
@@ -184,7 +184,7 @@ class CertificateSigningRequestBackend:
)
except Exception as e:
raise CertificateSigningRequestError(
"Cannot parse authority_key_identifier: {0}".format(e)
f"Cannot parse authority_key_identifier: {e}"
)
self.existing_csr = None
@@ -337,9 +337,7 @@ def parse_crl_distribution_points(module, crl_distribution_points):
result.append(cryptography.x509.DistributionPoint(**params))
except (OpenSSLObjectError, ValueError) as e:
raise OpenSSLObjectError(
"Error while parsing CRL distribution point #{index}: {error}".format(
index=index, error=e
)
f"Error while parsing CRL distribution point #{index}: {e}"
)
return result
@@ -446,9 +444,7 @@ class CertificateSigningRequestCryptographyBackend(CertificateSigningRequestBack
critical=self.name_constraints_critical,
)
except TypeError as e:
raise OpenSSLObjectError(
"Error while parsing name constraint: {0}".format(e)
)
raise OpenSSLObjectError(f"Error while parsing name constraint: {e}")
if self.create_subject_key_identifier:
csr = csr.add_extension(
@@ -494,7 +490,7 @@ class CertificateSigningRequestCryptographyBackend(CertificateSigningRequestBack
digest = select_message_digest(self.digest)
if digest is None:
raise CertificateSigningRequestError(
'Unsupported digest "{0}"'.format(self.digest)
f'Unsupported digest "{self.digest}"'
)
try:
self.csr = csr.sign(self.privatekey, digest, self.cryptography_backend)
@@ -518,7 +514,7 @@ class CertificateSigningRequestCryptographyBackend(CertificateSigningRequestBack
# https://github.com/kjd/idna/commit/ebefacd3134d0f5da4745878620a6a1cba86d130
# and then
# https://github.com/kjd/idna/commit/ea03c7b5db7d2a99af082e0239da2b68aeea702a).
msg = "Error while creating CSR: {0}\n".format(e)
msg = f"Error while creating CSR: {e}\n"
if self.using_common_name_for_san:
self.module.fail_json(
msg=msg
@@ -813,23 +809,20 @@ def select_backend(module, backend):
# 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})"
)
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, CertificateSigningRequestCryptographyBackend(module)
else:
raise Exception("Unsupported value for backend: {0}".format(backend))
raise Exception(f"Unsupported value for backend: {backend}")
def get_csr_argument_spec():

View File

@@ -258,9 +258,9 @@ class CSRInfoRetrievalCryptography(CSRInfoRetrieval):
ext_keyusage_ext = self.csr.extensions.get_extension_for_class(
x509.BasicConstraints
)
result = ["CA:{0}".format("TRUE" if ext_keyusage_ext.value.ca else "FALSE")]
result = [f"CA:{'TRUE' if ext_keyusage_ext.value.ca else 'FALSE'}"]
if ext_keyusage_ext.value.path_length is not None:
result.append("pathlen:{0}".format(ext_keyusage_ext.value.path_length))
result.append(f"pathlen:{ext_keyusage_ext.value.path_length}")
return sorted(result), ext_keyusage_ext.critical
except cryptography.x509.ExtensionNotFound:
return None, False
@@ -380,16 +380,14 @@ def select_backend(module, backend, content, validate_signature=True):
# 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,
)
@@ -397,4 +395,4 @@ def select_backend(module, backend, content, validate_signature=True):
module, content, validate_signature=validate_signature
)
else:
raise ValueError("Unsupported value for backend: {0}".format(backend))
raise ValueError(f"Unsupported value for backend: {backend}")

View File

@@ -273,7 +273,7 @@ class PrivateKeyCryptographyBackend(PrivateKeyBackend):
ecclass = cryptography.hazmat.primitives.asymmetric.ec.__dict__.get(ectype)
if ecclass is None:
self.module.fail_json(
msg="Your cryptography version does not support {0}".format(ectype)
msg=f"Your cryptography version does not support {ectype}"
)
return ecclass
@@ -385,9 +385,7 @@ class PrivateKeyCryptographyBackend(PrivateKeyBackend):
if self.type == "ECC" and self.curve in self.curves:
if self.curves[self.curve]["deprecated"]:
self.module.warn(
"Elliptic curves of type {0} should not be used for new keys!".format(
self.curve
)
f"Elliptic curves of type {self.curve} should not be used for new keys!"
)
self.private_key = (
cryptography.hazmat.primitives.asymmetric.ec.generate_private_key(
@@ -397,9 +395,7 @@ class PrivateKeyCryptographyBackend(PrivateKeyBackend):
)
except cryptography.exceptions.UnsupportedAlgorithm:
self.module.fail_json(
msg="Cryptography backend does not support the algorithm required for {0}".format(
self.type
)
msg=f"Cryptography backend does not support the algorithm required for {self.type}"
)
def get_private_key_data(self):
@@ -426,9 +422,7 @@ class PrivateKeyCryptographyBackend(PrivateKeyBackend):
)
except AttributeError:
self.module.fail_json(
msg='Cryptography backend does not support the selected output format "{0}"'.format(
self.format
)
msg=f'Cryptography backend does not support the selected output format "{self.format}"'
)
# Select key encryption
@@ -454,15 +448,11 @@ class PrivateKeyCryptographyBackend(PrivateKeyBackend):
)
except ValueError:
self.module.fail_json(
msg='Cryptography backend cannot serialize the private key in the required format "{0}"'.format(
self.format
)
msg=f'Cryptography backend cannot serialize the private key in the required format "{self.format}"'
)
except Exception:
self.module.fail_json(
msg='Error while serializing the private key in the required format "{0}"'.format(
self.format
),
msg=f'Error while serializing the private key in the required format "{self.format}"',
exception=traceback.format_exc(),
)
@@ -611,21 +601,19 @@ 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, PrivateKeyCryptographyBackend(module)
else:
raise Exception("Unsupported value for backend: {0}".format(backend))
raise Exception(f"Unsupported value for backend: {backend}")
def get_privatekey_argument_spec():

View File

@@ -161,9 +161,7 @@ class PrivateKeyConvertCryptographyBackend(PrivateKeyConvertBackend):
)
except AttributeError:
self.module.fail_json(
msg='Cryptography backend does not support the selected output format "{0}"'.format(
self.format
)
msg=f'Cryptography backend does not support the selected output format "{self.format}"'
)
# Select key encryption
@@ -186,15 +184,11 @@ class PrivateKeyConvertCryptographyBackend(PrivateKeyConvertBackend):
)
except ValueError:
self.module.fail_json(
msg='Cryptography backend cannot serialize the private key in the required format "{0}"'.format(
self.format
)
msg=f'Cryptography backend cannot serialize the private key in the required format "{self.format}"'
)
except Exception:
self.module.fail_json(
msg='Error while serializing the private key in the required format "{0}"'.format(
self.format
),
msg=f'Error while serializing the private key in the required format "{self.format}"',
exception=traceback.format_exc(),
)
@@ -285,9 +279,7 @@ class PrivateKeyConvertCryptographyBackend(PrivateKeyConvertBackend):
def select_backend(module):
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,
)
return PrivateKeyConvertCryptographyBackend(module)

View File

@@ -173,7 +173,7 @@ def _is_cryptography_key_consistent(
return False
# For X25519 and X448, there's no test yet.
if warn_func is not None:
warn_func("Cannot determine consistency for key of type %s" % type(key))
warn_func(f"Cannot determine consistency for key of type {type(key)}")
return None
@@ -338,16 +338,14 @@ def select_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,
)
@@ -359,4 +357,4 @@ def select_backend(
check_consistency=check_consistency,
)
else:
raise ValueError("Unsupported value for backend: {0}".format(backend))
raise ValueError(f"Unsupported value for backend: {backend}")

View File

@@ -84,7 +84,7 @@ def _get_cryptography_public_key_info(key):
key_public_data["y"] = public_numbers.y
key_public_data["exponent_size"] = key.curve.key_size
else:
key_type = "unknown ({0})".format(type(key))
key_type = f"unknown ({type(key)})"
return key_type, key_public_data
@@ -174,17 +174,14 @@ def select_backend(module, backend, content=None, key=None):
# 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})"
)
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,
)
@@ -192,4 +189,4 @@ def select_backend(module, backend, content=None, key=None):
module, content=content, key=key
)
else:
raise ValueError("Unsupported value for backend: {0}".format(backend))
raise ValueError(f"Unsupported value for backend: {backend}")