1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-02-04 07:51:50 +00:00

modules [jk]*: use f-strings (#10970)

* modules [jk]*: use f-strings

* add changelog frag

* Apply suggestions from code review

* typing insanity
This commit is contained in:
Alexei Znamensky 2025-10-26 19:54:15 +13:00 committed by GitHub
parent 8120e9347e
commit 4a6a449fbd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
46 changed files with 363 additions and 408 deletions

View file

@ -0,0 +1,46 @@
minor_changes:
- jabber - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- java_cert - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- java_keystore - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- jboss - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- jenkins_build - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- jenkins_build_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- jenkins_credential - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- jenkins_job - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- jenkins_job_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- jenkins_node - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- jenkins_plugin - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- jenkins_script - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- jira - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- kdeconfig - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- kernel_blacklist - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_authentication - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_authentication_required_actions - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_authz_authorization_scope - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_authz_custom_policy - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_authz_permission - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_authz_permission_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_client - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_client_rolemapping - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_client_rolescope - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_clientscope - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_clientsecret_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_clientsecret_regenerate - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_clienttemplate - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_component - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_component_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_group - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_identity_provider - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_realm - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_realm_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_realm_key - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_realm_keys_metadata_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_realm_rolemapping - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_role - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_user - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_user_federation - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_user_rolemapping - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keycloak_userprofile - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keyring - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- keyring_info - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).
- kibana_plugin - use f-strings for string templating (https://github.com/ansible-collections/community.general/pull/10970).

View file

@ -95,7 +95,6 @@ except ImportError:
HAS_XMPP = False
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_native
def main():
@ -138,9 +137,9 @@ def main():
try:
conn = xmpp.Client(server, debug=[])
if not conn.connect(server=(host, port)):
module.fail_json(rc=1, msg='Failed to connect to server: %s' % (server))
module.fail_json(rc=1, msg=f'Failed to connect to server: {server}')
if not conn.auth(user, password, 'Ansible'):
module.fail_json(rc=1, msg='Failed to authorize %s on: %s' % (user, server))
module.fail_json(rc=1, msg=f'Failed to authorize {user} on: {server}')
# some old servers require this, also the sleep following send
conn.sendInitPresence(requestRoster=0)
@ -160,7 +159,7 @@ def main():
time.sleep(1)
conn.disconnect()
except Exception as e:
module.fail_json(msg="unable to send msg: %s" % to_native(e), exception=traceback.format_exc())
module.fail_json(msg=f"unable to send msg: {e}", exception=traceback.format_exc())
module.exit_json(changed=False, to=to, user=user, msg=msg.getBody())

View file

@ -264,7 +264,7 @@ def _get_first_certificate_from_x509_file(module, pem_certificate_file, pem_cert
if extract_rc != 0:
# this time it is a real failure
module.fail_json(msg="Internal module failure, cannot extract certificate, error: %s" % extract_stderr,
module.fail_json(msg=f"Internal module failure, cannot extract certificate, error: {extract_stderr}",
rc=extract_rc, cmd=extract_cmd)
return extract_rc
@ -286,7 +286,7 @@ def _get_digest_from_x509_file(module, pem_certificate_file, openssl_bin):
(dgst_rc, dgst_stdout, dgst_stderr) = module.run_command(dgst_cmd, check_rc=False)
if dgst_rc != 0:
module.fail_json(msg="Internal module failure, cannot compute digest for certificate, error: %s" % dgst_stderr,
module.fail_json(msg=f"Internal module failure, cannot compute digest for certificate, error: {dgst_stderr}",
rc=dgst_rc, cmd=dgst_cmd)
return dgst_stdout.split(' ')[0]
@ -310,7 +310,7 @@ def _export_public_cert_from_pkcs12(module, executable, pkcs_file, alias, passwo
(export_rc, export_stdout, export_err) = module.run_command(export_cmd, data=password, check_rc=False)
if export_rc != 0:
module.fail_json(msg="Internal module failure, cannot extract public certificate from PKCS12, message: %s" % export_stdout,
module.fail_json(msg=f"Internal module failure, cannot extract public certificate from PKCS12, message: {export_stdout}",
stderr=export_err,
rc=export_rc)
@ -339,7 +339,7 @@ def build_proxy_options():
proxy_opts = []
if proxy_host:
proxy_opts.extend(["-J-Dhttps.proxyHost=%s" % proxy_host, "-J-Dhttps.proxyPort=%s" % proxy_port])
proxy_opts.extend([f"-J-Dhttps.proxyHost={proxy_host}", f"-J-Dhttps.proxyPort={proxy_port}"])
if no_proxy is not None:
# For Java's nonProxyHosts property, items are separated by '|',
@ -349,7 +349,7 @@ def build_proxy_options():
# The property name is http.nonProxyHosts, there is no
# separate setting for HTTPS.
proxy_opts.extend(["-J-Dhttp.nonProxyHosts=%s" % non_proxy_hosts])
proxy_opts.extend([f"-J-Dhttp.nonProxyHosts={non_proxy_hosts}"])
return proxy_opts
@ -363,13 +363,13 @@ def _download_cert_url(module, executable, url, port):
""" Fetches the certificate from the remote URL using `keytool -printcert...`
The PEM formatted string is returned """
proxy_opts = build_proxy_options()
fetch_cmd = [executable, "-printcert", "-rfc", "-sslserver"] + proxy_opts + ["%s:%d" % (url, port)]
fetch_cmd = [executable, "-printcert", "-rfc", "-sslserver"] + proxy_opts + [f"{url}:{port}"]
# Fetch SSL certificate from remote host.
(fetch_rc, fetch_out, fetch_err) = module.run_command(fetch_cmd, check_rc=False)
if fetch_rc != 0:
module.fail_json(msg="Internal module failure, cannot download certificate, error: %s" % fetch_err,
module.fail_json(msg=f"Internal module failure, cannot download certificate, error: {fetch_err}",
rc=fetch_rc, cmd=fetch_cmd)
return fetch_out
@ -401,14 +401,14 @@ def import_pkcs12_path(module, executable, pkcs12_path, pkcs12_pass, pkcs12_alia
import_cmd += _get_keystore_type_keytool_parameters(keystore_type)
secret_data = "%s\n%s" % (keystore_pass, pkcs12_pass)
secret_data = f"{keystore_pass}\n{pkcs12_pass}"
# Password of a new keystore must be entered twice, for confirmation
if not os.path.exists(keystore_path):
secret_data = "%s\n%s" % (keystore_pass, secret_data)
secret_data = f"{keystore_pass}\n{secret_data}"
# Use local certificate from local path and import it to a java keystore
(import_rc, import_out, import_err) = module.run_command(import_cmd, data=secret_data, check_rc=False)
diff = {'before': '\n', 'after': '%s\n' % keystore_alias}
diff = {'before': '\n', 'after': f'{keystore_alias}\n'}
if import_rc != 0 or not os.path.exists(keystore_path):
module.fail_json(msg=import_out, rc=import_rc, cmd=import_cmd, error=import_err)
@ -439,9 +439,9 @@ def import_cert_path(module, executable, path, keystore_path, keystore_pass, ali
# Use local certificate from local path and import it to a java keystore
(import_rc, import_out, import_err) = module.run_command(import_cmd,
data="%s\n%s" % (keystore_pass, keystore_pass),
data=f"{keystore_pass}\n{keystore_pass}",
check_rc=False)
diff = {'before': '\n', 'after': '%s\n' % alias}
diff = {'before': '\n', 'after': f'{alias}\n'}
if import_rc != 0:
module.fail_json(msg=import_out, rc=import_rc, cmd=import_cmd, error=import_err)
@ -467,7 +467,7 @@ def delete_cert(module, executable, keystore_path, keystore_pass, alias, keystor
# Delete SSL certificate from keystore
(del_rc, del_out, del_err) = module.run_command(del_cmd, data=keystore_pass, check_rc=True)
diff = {'before': '%s\n' % alias, 'after': None}
diff = {'before': f'{alias}\n', 'after': None}
if del_rc != 0:
module.fail_json(msg=del_out, rc=del_rc, cmd=del_cmd, error=del_err)
@ -488,7 +488,7 @@ def test_keystore(module, keystore_path):
if not os.path.exists(keystore_path) and not os.path.isfile(keystore_path):
# Keystore doesn't exist we want to create it
module.fail_json(changed=False, msg="Module require existing keystore at keystore_path '%s'" % keystore_path)
module.fail_json(changed=False, msg=f"Module require existing keystore at keystore_path '{keystore_path}'")
def main():
@ -546,8 +546,7 @@ def main():
if path and not cert_alias:
module.fail_json(changed=False,
msg="Using local path import from %s requires alias argument."
% keystore_path)
msg=f"Using local path import from {keystore_path} requires alias argument.")
test_keytool(module, executable)

View file

@ -183,7 +183,7 @@ import re
import tempfile
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_bytes, to_native
from ansible.module_utils.common.text.converters import to_bytes
try:
from cryptography.hazmat.primitives.serialization.pkcs12 import serialize_key_and_certificates
@ -257,7 +257,7 @@ class JavaKeystore:
backend=backend
)
except (OSError, ValueError) as e:
self.module.fail_json(msg="Unable to read the provided certificate: %s" % to_native(e))
self.module.fail_json(msg=f"Unable to read the provided certificate: {e}")
fp = cert.fingerprint(hashes.SHA256()).hex().upper()
fingerprint = ':'.join([fp[i:i + 2] for i in range(0, len(fp), 2)])
@ -281,9 +281,7 @@ class JavaKeystore:
current_certificate_match = re.search(r"=([\w:]+)", current_certificate_fingerprint_out)
if not current_certificate_match:
return self.module.fail_json(
msg="Unable to find the current certificate fingerprint in %s" % (
current_certificate_fingerprint_out
),
msg=f"Unable to find the current certificate fingerprint in {current_certificate_fingerprint_out}",
cmd=current_certificate_fingerprint_cmd,
rc=rc
)
@ -299,12 +297,11 @@ class JavaKeystore:
(rc, stored_certificate_fingerprint_out, stored_certificate_fingerprint_err) = self.module.run_command(
stored_certificate_fingerprint_cmd, data=self.password, check_rc=False)
if rc != 0:
if "keytool error: java.lang.Exception: Alias <%s> does not exist" % self.name \
if f"keytool error: java.lang.Exception: Alias <{self.name}> does not exist" \
in stored_certificate_fingerprint_out:
return "alias mismatch"
if re.match(
r'keytool error: java\.io\.IOException: ' +
'[Kk]eystore( was tampered with, or)? password was incorrect',
r"keytool error: java\.io\.IOException: [Kk]eystore( was tampered with, or)? password was incorrect",
stored_certificate_fingerprint_out
):
return "password mismatch"
@ -321,7 +318,7 @@ class JavaKeystore:
stored_certificate_match = re.search(r"SHA256: ([\w:]+)", stored_certificate_fingerprint_out)
if not stored_certificate_match:
return self.module.fail_json(
msg="Unable to find the stored certificate fingerprint in %s" % stored_certificate_fingerprint_out,
msg=f"Unable to find the stored certificate fingerprint in {stored_certificate_fingerprint_out}",
cmd=stored_certificate_fingerprint_cmd,
rc=rc
)
@ -370,11 +367,11 @@ class JavaKeystore:
)
except (OSError, TypeError, ValueError, UnsupportedAlgorithm) as e:
self.module.fail_json(
msg="The following error occurred while loading the provided private_key: %s" % to_native(e)
msg=f"The following error occurred while loading the provided private_key: {e}"
)
except (OSError, ValueError, UnsupportedAlgorithm) as e:
self.module.fail_json(
msg="The following error occurred while loading the provided private_key: %s" % to_native(e)
msg=f"The following error occurred while loading the provided private_key: {e}"
)
try:
with open(self.certificate_path, 'rb') as cert_file:
@ -384,7 +381,7 @@ class JavaKeystore:
)
except (OSError, ValueError, UnsupportedAlgorithm) as e:
self.module.fail_json(
msg="The following error occurred while loading the provided certificate: %s" % to_native(e)
msg=f"The following error occurred while loading the provided certificate: {e}"
)
if self.password:
@ -414,8 +411,8 @@ class JavaKeystore:
if self.keypass:
export_p12_cmd.append("-passin")
export_p12_cmd.append("stdin")
cmd_stdin = "%s\n" % self.keypass
cmd_stdin += "%s\n%s" % (self.password, self.password)
cmd_stdin = f"{self.keypass}\n"
cmd_stdin += f"{self.password}\n{self.password}"
(rc, export_p12_out, export_p12_err) = self.module.run_command(
export_p12_cmd, data=cmd_stdin, environ_update=None, check_rc=False
@ -464,13 +461,13 @@ class JavaKeystore:
keystore_backup = None
if self.exists():
keystore_backup = self.keystore_path + '.tmpbak'
keystore_backup = f"{self.keystore_path}.tmpbak"
# Preserve properties of the source file
self.module.preserved_copy(self.keystore_path, keystore_backup)
os.remove(self.keystore_path)
(rc, import_keystore_out, import_keystore_err) = self.module.run_command(
import_keystore_cmd, data='%s\n%s\n%s' % (self.password, self.password, self.password), check_rc=False
import_keystore_cmd, data=f'{self.password}\n{self.password}\n{self.password}', check_rc=False
)
self.result = dict(msg=import_keystore_out, cmd=import_keystore_cmd, rc=rc)

View file

@ -86,15 +86,15 @@ DEFAULT_DEPLOY_PATH = '/var/lib/jbossas/standalone/deployments'
def is_deployed(deploy_path, deployment):
return os.path.exists(os.path.join(deploy_path, "%s.deployed" % deployment))
return os.path.exists(os.path.join(deploy_path, f"{deployment}.deployed"))
def is_undeployed(deploy_path, deployment):
return os.path.exists(os.path.join(deploy_path, "%s.undeployed" % deployment))
return os.path.exists(os.path.join(deploy_path, f"{deployment}.undeployed"))
def is_failed(deploy_path, deployment):
return os.path.exists(os.path.join(deploy_path, "%s.failed" % deployment))
return os.path.exists(os.path.join(deploy_path, f"{deployment}.failed"))
def main():
@ -122,7 +122,7 @@ def main():
if state == 'absent' and src:
module.warn('Parameter src is ignored when state=absent')
elif state == 'present' and not os.path.exists(src):
module.fail_json(msg='Source file %s does not exist.' % src)
module.fail_json(msg=f'Source file {src} does not exist.')
deployed = is_deployed(deploy_path, deployment)
@ -145,34 +145,34 @@ def main():
if state == 'present' and not deployed:
if is_failed(deploy_path, deployment):
# Clean up old failed deployment
os.remove(os.path.join(deploy_path, "%s.failed" % deployment))
os.remove(os.path.join(deploy_path, f"{deployment}.failed"))
module.preserved_copy(src, os.path.join(deploy_path, deployment))
while not deployed:
deployed = is_deployed(deploy_path, deployment)
if is_failed(deploy_path, deployment):
module.fail_json(msg='Deploying %s failed.' % deployment)
module.fail_json(msg=f'Deploying {deployment} failed.')
time.sleep(1)
result['changed'] = True
if state == 'present' and deployed:
if module.sha1(src) != module.sha1(os.path.join(deploy_path, deployment)):
os.remove(os.path.join(deploy_path, "%s.deployed" % deployment))
os.remove(os.path.join(deploy_path, f"{deployment}.deployed"))
module.preserved_copy(src, os.path.join(deploy_path, deployment))
deployed = False
while not deployed:
deployed = is_deployed(deploy_path, deployment)
if is_failed(deploy_path, deployment):
module.fail_json(msg='Deploying %s failed.' % deployment)
module.fail_json(msg=f'Deploying {deployment} failed.')
time.sleep(1)
result['changed'] = True
if state == 'absent' and deployed:
os.remove(os.path.join(deploy_path, "%s.deployed" % deployment))
os.remove(os.path.join(deploy_path, f"{deployment}.deployed"))
while deployed:
deployed = not is_undeployed(deploy_path, deployment)
if is_failed(deploy_path, deployment):
module.fail_json(msg='Undeploying %s failed.' % deployment)
module.fail_json(msg=f'Undeploying {deployment} failed.')
time.sleep(1)
result['changed'] = True

View file

@ -156,7 +156,6 @@ except ImportError:
python_jenkins_installed = False
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_native
class JenkinsBuild:
@ -197,13 +196,13 @@ class JenkinsBuild:
else:
return jenkins.Jenkins(self.jenkins_url)
except Exception as e:
self.module.fail_json(msg='Unable to connect to Jenkins server, %s' % to_native(e))
self.module.fail_json(msg=f'Unable to connect to Jenkins server, {e}')
def get_next_build(self):
try:
build_number = self.server.get_job_info(self.name)['nextBuildNumber']
except Exception as e:
self.module.fail_json(msg='Unable to get job info from Jenkins server, %s' % to_native(e),
self.module.fail_json(msg=f'Unable to get job info from Jenkins server, {e}',
exception=traceback.format_exc())
return build_number
@ -217,7 +216,7 @@ class JenkinsBuild:
response["result"] = "ABSENT"
return response
except Exception as e:
self.module.fail_json(msg='Unable to fetch build information, %s' % to_native(e),
self.module.fail_json(msg=f'Unable to fetch build information, {e}',
exception=traceback.format_exc())
def present_build(self):
@ -229,7 +228,7 @@ class JenkinsBuild:
else:
self.server.build_job(self.name, self.args)
except Exception as e:
self.module.fail_json(msg='Unable to create build for %s: %s' % (self.jenkins_url, to_native(e)),
self.module.fail_json(msg=f'Unable to create build for {self.jenkins_url}: {e}',
exception=traceback.format_exc())
def stopped_build(self):
@ -239,7 +238,7 @@ class JenkinsBuild:
if build_info['building'] is True:
self.server.stop_build(self.name, self.build_number)
except Exception as e:
self.module.fail_json(msg='Unable to stop build for %s: %s' % (self.jenkins_url, to_native(e)),
self.module.fail_json(msg=f'Unable to stop build for {self.jenkins_url}: {e}',
exception=traceback.format_exc())
else:
if build_info['building'] is False:
@ -249,7 +248,7 @@ class JenkinsBuild:
try:
self.server.delete_build(self.name, self.build_number)
except Exception as e:
self.module.fail_json(msg='Unable to delete build for %s: %s' % (self.jenkins_url, to_native(e)),
self.module.fail_json(msg=f'Unable to delete build for {self.jenkins_url}: {e}',
exception=traceback.format_exc())
def get_result(self):

View file

@ -111,7 +111,6 @@ except ImportError:
python_jenkins_installed = False
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_native
class JenkinsBuildInfo:
@ -145,7 +144,7 @@ class JenkinsBuildInfo:
else:
return jenkins.Jenkins(self.jenkins_url)
except Exception as e:
self.module.fail_json(msg='Unable to connect to Jenkins server, %s' % to_native(e))
self.module.fail_json(msg=f'Unable to connect to Jenkins server, {e}')
def get_build_status(self):
try:
@ -159,7 +158,7 @@ class JenkinsBuildInfo:
response["result"] = "ABSENT"
return response
except Exception as e:
self.module.fail_json(msg='Unable to fetch build information, %s' % to_native(e),
self.module.fail_json(msg=f'Unable to fetch build information, {e}',
exception=traceback.format_exc())
def get_result(self):

View file

@ -334,7 +334,7 @@ with deps.declare("urllib3", reason="urllib3 is required to embed files into req
def validate_file_exist(module, path):
if path and not os.path.exists(path):
module.fail_json(msg="File not found: {}".format(path))
module.fail_json(msg=f"File not found: {path}")
# Gets the Jenkins crumb for CSRF protection which is required for API calls
@ -345,7 +345,7 @@ def get_jenkins_crumb(module, headers):
if "/job" in url:
url = url.split("/job")[0]
crumb_url = "{}/crumbIssuer/api/json".format(url)
crumb_url = f"{url}/crumbIssuer/api/json"
response, info = fetch_url(module, crumb_url, headers=headers)
@ -416,15 +416,11 @@ def target_exists(module, check_domain=False):
headers = {"Authorization": basic_auth_header(user, token)}
if module.params["type"] == "scope" or check_domain:
target_url = "{}/credentials/store/{}/domain/{}/api/json".format(
url, location, scope if check_domain else name
)
target_url = f"{url}/credentials/store/{location}/domain/{scope if check_domain else name}/api/json"
elif module.params["type"] == "token":
return False # Can't check token
else:
target_url = "{}/credentials/store/{}/domain/{}/credential/{}/api/json".format(
url, location, scope, name
)
target_url = f"{url}/credentials/store/{location}/domain/{scope}/credential/{name}/api/json"
response, info = fetch_url(module, target_url, headers=headers)
status = info.get("status", 0)
@ -435,9 +431,7 @@ def target_exists(module, check_domain=False):
return False
else:
module.fail_json(
msg="Unexpected status code {} when checking {} existence.".format(
status, name
)
msg=f"Unexpected status code {status} when checking {name} existence."
)
@ -455,21 +449,15 @@ def delete_target(module, headers):
try:
if type == "token":
delete_url = "{}/user/{}/descriptorByName/jenkins.security.ApiTokenProperty/revoke".format(
url, user
)
delete_url = f"{url}/user/{user}/descriptorByName/jenkins.security.ApiTokenProperty/revoke"
body = urlencode({"tokenUuid": id})
elif type == "scope":
delete_url = "{}/credentials/store/{}/domain/{}/doDelete".format(
url, location, id
)
delete_url = f"{url}/credentials/store/{location}/domain/{id}/doDelete"
else:
delete_url = (
"{}/credentials/store/{}/domain/{}/credential/{}/doDelete".format(
url, location, scope, id
)
f"{url}/credentials/store/{location}/domain/{scope}/credential/{id}/doDelete"
)
response, info = fetch_url(
@ -483,13 +471,11 @@ def delete_target(module, headers):
status = info.get("status", 0)
if not status == 200:
module.fail_json(
msg="Failed to delete: HTTP {}, {}, {}".format(
status, response, headers
)
msg=f"Failed to delete: HTTP {status}, {response}, {headers}"
)
except Exception as e:
module.fail_json(msg="Exception during delete: {}".format(str(e)))
module.fail_json(msg=f"Exception during delete: {e}")
# Function to read the private key for types texts and ssh_key
@ -499,7 +485,7 @@ def read_privateKey(module):
private_key = f.read().strip()
return private_key
except Exception as e:
module.fail_json(msg="Failed to read private key file: {}".format(str(e)))
module.fail_json(msg=f"Failed to read private key file: {e}")
# Function to builds multipart form-data body and content-type header for file credential upload.
@ -514,7 +500,7 @@ def embed_file_into_body(module, file_path, credentials):
with open(file_path, "rb") as f:
file_bytes = f.read()
except Exception as e:
module.fail_json(msg="Failed to read file: {}".format(str(e)))
module.fail_json(msg=f"Failed to read file: {e}")
return "", "" # Return for test purposes
credentials.update(
@ -639,7 +625,7 @@ def run_module():
# Check if the credential/domain doesn't exist and the user wants to delete
if not does_exist and state == "absent" and not type == "token":
result["changed"] = False
result["msg"] = "{} does not exist.".format(id)
result["msg"] = f"{id} does not exist."
module.exit_json(**result)
if state == "present":
@ -649,20 +635,18 @@ def run_module():
delete_target(module, headers)
elif does_exist and not force:
result["changed"] = False
result["msg"] = "{} already exists. Use force=True to update.".format(id)
result["msg"] = f"{id} already exists. Use force=True to update."
module.exit_json(**result)
if type == "token":
post_url = "{}/user/{}/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken".format(
url, jenkins_user
)
post_url = f"{url}/user/{jenkins_user}/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken"
body = "newTokenName={}".format(name)
body = f"newTokenName={name}"
elif type == "scope":
post_url = "{}/credentials/store/{}/createDomain".format(url, location)
post_url = f"{url}/credentials/store/{location}/createDomain"
specifications = []
@ -714,9 +698,7 @@ def run_module():
elif private_key_path:
validate_file_exist(module, private_key_path)
post_url = "{}/credentials/store/{}/domain/{}/createCredentials".format(
url, location, scope
)
post_url = f"{url}/credentials/store/{location}/domain/{scope}/createCredentials"
cred_class = {
"user_and_pass": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl",
@ -771,9 +753,7 @@ def run_module():
)
except Exception as e:
module.fail_json(
msg="Failed to read or encode keystore file: {}".format(
str(e)
)
msg=f"Failed to read or encode keystore file: {e}"
)
credentials.update(
@ -793,7 +773,7 @@ def run_module():
private_key = f.read()
except Exception as e:
module.fail_json(
msg="Failed to read PEM files: {}".format(str(e))
msg=f"Failed to read PEM files: {e}"
)
credentials.update(
@ -820,29 +800,27 @@ def run_module():
delete_target(module, headers)
module.exit_json(changed=True, msg="{} deleted successfully.".format(id))
module.exit_json(changed=True, msg=f"{id} deleted successfully.")
if (
not type == "scope" and not scope == "_"
): # Check if custom scope exists if adding to a custom scope
if not target_exists(module, True):
module.fail_json(msg="Domain {} doesn't exists".format(scope))
module.fail_json(msg=f"Domain {scope} doesn't exists")
try:
response, info = fetch_url(
module, post_url, headers=headers, data=body, method="POST"
)
except Exception as e:
module.fail_json(msg="Request to {} failed: {}".format(post_url, str(e)))
module.fail_json(msg=f"Request to {post_url} failed: {e}")
status = info.get("status", 0)
if not status == 200:
body = response.read() if response else b""
module.fail_json(
msg="Failed to {} credential".format(
"add/update" if state == "present" else "delete"
),
msg=f"Failed to {'add/update' if state == 'present' else 'delete'} credential",
details=body.decode("utf-8", errors="ignore"),
)

View file

@ -216,7 +216,7 @@ class JenkinsJob(object):
else:
return jenkins.Jenkins(self.jenkins_url)
except Exception as e:
self.module.fail_json(msg='Unable to connect to Jenkins server, %s' % to_native(e), exception=traceback.format_exc())
self.module.fail_json(msg=f'Unable to connect to Jenkins server, {e}', exception=traceback.format_exc())
def get_job_status(self):
try:
@ -227,13 +227,13 @@ class JenkinsJob(object):
return to_native(response['color'])
except Exception as e:
self.module.fail_json(msg='Unable to fetch job information, %s' % to_native(e), exception=traceback.format_exc())
self.module.fail_json(msg=f'Unable to fetch job information, {e}', exception=traceback.format_exc())
def job_exists(self):
try:
return bool(self.server.job_exists(self.name))
except Exception as e:
self.module.fail_json(msg='Unable to validate if job exists, %s for %s' % (to_native(e), self.jenkins_url),
self.module.fail_json(msg=f'Unable to validate if job exists, {e} for {self.jenkins_url}',
exception=traceback.format_exc())
def get_config(self):
@ -296,7 +296,7 @@ class JenkinsJob(object):
self.switch_state()
except Exception as e:
self.module.fail_json(msg='Unable to reconfigure job, %s for %s' % (to_native(e), self.jenkins_url),
self.module.fail_json(msg=f'Unable to reconfigure job, {e} for {self.jenkins_url}',
exception=traceback.format_exc())
def create_job(self):
@ -310,7 +310,7 @@ class JenkinsJob(object):
if not self.module.check_mode:
self.server.create_job(self.name, config_file)
except Exception as e:
self.module.fail_json(msg='Unable to create job, %s for %s' % (to_native(e), self.jenkins_url),
self.module.fail_json(msg=f'Unable to create job, {e} for {self.jenkins_url}',
exception=traceback.format_exc())
def absent_job(self):
@ -321,7 +321,7 @@ class JenkinsJob(object):
try:
self.server.delete_job(self.name)
except Exception as e:
self.module.fail_json(msg='Unable to delete job, %s for %s' % (to_native(e), self.jenkins_url),
self.module.fail_json(msg=f'Unable to delete job, {e} for {self.jenkins_url}',
exception=traceback.format_exc())
def get_result(self):

View file

@ -150,7 +150,6 @@ except ImportError:
HAS_JENKINS = False
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_native
def get_jenkins_connection(module):
@ -246,7 +245,7 @@ def main():
jobs = get_jobs(module)
except jenkins.JenkinsException as err:
module.fail_json(
msg='Unable to connect to Jenkins server, %s' % to_native(err),
msg=f'Unable to connect to Jenkins server, {err}',
exception=traceback.format_exc())
module.exit_json(changed=False, jobs=jobs)

View file

@ -150,7 +150,6 @@ import traceback
from xml.etree import ElementTree as et
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.community.general.plugins.module_utils import deps
with deps.declare(
@ -186,7 +185,7 @@ class JenkinsNode:
if self.labels is not None:
for label in self.labels:
if " " in label:
self.module.fail_json("labels must not contain spaces: got invalid label {}".format(label))
self.module.fail_json(f"labels must not contain spaces: got invalid label {label}")
self.instance = self.get_jenkins_instance()
self.result = {
@ -212,7 +211,7 @@ class JenkinsNode:
else:
return jenkins.Jenkins(self.url)
except Exception as e:
self.module.fail_json(msg='Unable to connect to Jenkins server, %s' % to_native(e))
self.module.fail_json(msg=f'Unable to connect to Jenkins server, {e}')
def configure_node(self, present):
if not present:
@ -275,7 +274,7 @@ class JenkinsNode:
# handling redirects returned when posting to resources. If the node is
# created OK then can ignore the error.
if not self.instance.node_exists(self.name):
self.module.fail_json(msg="Create node failed: %s" % to_native(e), exception=traceback.format_exc())
self.module.fail_json(msg=f"Create node failed: {e}", exception=traceback.format_exc())
# TODO: Remove authorization workaround.
self.result['warnings'].append(
@ -309,7 +308,7 @@ class JenkinsNode:
# handling redirects returned when posting to resources. If the node is
# deleted OK then can ignore the error.
if self.instance.node_exists(self.name):
self.module.fail_json(msg="Delete node failed: %s" % to_native(e), exception=traceback.format_exc())
self.module.fail_json(msg=f"Delete node failed: {e}", exception=traceback.format_exc())
# TODO: Remove authorization workaround.
self.result['warnings'].append(
@ -347,7 +346,7 @@ class JenkinsNode:
offline = get_offline()
if offline:
self.module.fail_json(msg="Enable node failed: %s" % to_native(e), exception=traceback.format_exc())
self.module.fail_json(msg=f"Enable node failed: {e}", exception=traceback.format_exc())
# TODO: Remove authorization workaround.
self.result['warnings'].append(
@ -417,7 +416,7 @@ class JenkinsNode:
offline, _offline_message = get_offline_info()
if not offline:
self.module.fail_json(msg="Disable node failed: %s" % to_native(e), exception=traceback.format_exc())
self.module.fail_json(msg=f"Disable node failed: {e}", exception=traceback.format_exc())
# TODO: Remove authorization workaround.
self.result['warnings'].append(

View file

@ -386,7 +386,7 @@ class JenkinsPlugin(object):
def _csrf_enabled(self):
csrf_data = self._get_json_data(
"%s/%s" % (self.url, "api/json"), 'CSRF')
f"{self.url}/api/json", 'CSRF')
if 'useCrumbs' not in csrf_data:
self.module.fail_json(
@ -404,7 +404,7 @@ class JenkinsPlugin(object):
json_data = json.loads(to_native(r.read()))
except Exception as e:
self.module.fail_json(
msg="Cannot parse %s JSON data." % what,
msg=f"Cannot parse {what} JSON data.",
details=to_native(e))
return json_data
@ -412,16 +412,16 @@ class JenkinsPlugin(object):
def _get_urls_data(self, urls, what=None, msg_status=None, msg_exception=None, **kwargs):
# Compose default messages
if msg_status is None:
msg_status = "Cannot get %s" % what
msg_status = f"Cannot get {what}"
if msg_exception is None:
msg_exception = "Retrieval of %s failed." % what
msg_exception = f"Retrieval of {what} failed."
errors = {}
for url in urls:
err_msg = None
try:
self.module.debug("fetching url: %s" % url)
self.module.debug(f"fetching url: {url}")
is_jenkins_call = url.startswith(self.url)
self.module.params['force_basic_auth'] = is_jenkins_call
@ -433,11 +433,11 @@ class JenkinsPlugin(object):
if info['status'] == 200:
return response
else:
err_msg = ("%s. fetching url %s failed. response code: %s" % (msg_status, url, info['status']))
err_msg = f"{msg_status}. fetching url {url} failed. response code: {info['status']}"
if info['status'] > 400: # extend error message
err_msg = "%s. response body: %s" % (err_msg, info['body'])
err_msg = f"{err_msg}. response body: {info['body']}"
except Exception as e:
err_msg = "%s. fetching url %s failed. error msg: %s" % (msg_status, url, to_native(e))
err_msg = f"{msg_status}. fetching url {url} failed. error msg: {e}"
finally:
if err_msg is not None:
self.module.debug(err_msg)
@ -451,10 +451,10 @@ class JenkinsPlugin(object):
dont_fail=False, **kwargs):
# Compose default messages
if msg_status is None:
msg_status = "Cannot get %s" % what
msg_status = f"Cannot get {what}"
if msg_exception is None:
msg_exception = "Retrieval of %s failed." % what
msg_exception = f"Retrieval of {what} failed."
# Get the URL data
try:
@ -481,7 +481,7 @@ class JenkinsPlugin(object):
def _get_crumb(self):
crumb_data = self._get_json_data(
"%s/%s" % (self.url, "crumbIssuer/api/json"), 'Crumb')
f"{self.url}/crumbIssuer/api/json", 'Crumb')
if 'crumbRequestField' in crumb_data and 'crumb' in crumb_data:
self.crumb[crumb_data['crumbRequestField']] = crumb_data['crumb']
@ -492,7 +492,7 @@ class JenkinsPlugin(object):
def _get_installed_plugins(self):
plugins_data = self._get_json_data(
"%s/%s" % (self.url, "pluginManager/api/json?depth=1"),
f"{self.url}/pluginManager/api/json?depth=1",
'list of plugins')
# Check if we got valid data
@ -555,8 +555,7 @@ class JenkinsPlugin(object):
if not self.module.check_mode:
# Install the plugin (with dependencies)
install_script = (
'd = Jenkins.instance.updateCenter.getPlugin("%s")'
'.deploy(); d.get();' % self.params['name'])
f"""d = Jenkins.instance.updateCenter.getPlugin("{self.params['name']}").deploy(); d.get();""")
if self.params['with_dependencies']:
install_script = (
@ -571,15 +570,13 @@ class JenkinsPlugin(object):
# Send the installation request
r = self._get_url_data(
"%s/scriptText" % self.url,
f"{self.url}/scriptText",
msg_status="Cannot install plugin.",
msg_exception="Plugin installation has failed.",
data=data,
dont_fail=True)
hpi_file = '%s/plugins/%s.hpi' % (
self.params['jenkins_home'],
self.params['name'])
hpi_file = f"{self.params['jenkins_home']}/plugins/{self.params['name']}.hpi"
if os.path.isfile(hpi_file):
os.remove(hpi_file)
@ -587,9 +584,7 @@ class JenkinsPlugin(object):
def install(self):
changed = False
plugin_file = (
'%s/plugins/%s.jpi' % (
self.params['jenkins_home'],
self.params['name']))
f"{self.params['jenkins_home']}/plugins/{self.params['name']}.jpi")
if not self.is_installed and self.params['version'] in [None, 'latest']:
try:
@ -684,7 +679,7 @@ class JenkinsPlugin(object):
urls = []
for base_url in self.params['updates_url']:
for update_segment in self.params['latest_plugins_url_segments']:
urls.append("{0}/{1}/{2}.hpi".format(base_url, update_segment, self.params['name']))
urls.append(f"{base_url}/{update_segment}/{self.params['name']}.hpi")
return urls
def _get_latest_compatible_plugin_version(self, plugin_name=None):
@ -694,11 +689,11 @@ class JenkinsPlugin(object):
raw_version = info.get("x-jenkins")
self.jenkins_version = self.parse_version(raw_version)
name = plugin_name or self.params['name']
cache_path = "{}/ansible_jenkins_plugin_cache.json".format(self.params['jenkins_home'])
cache_path = f"{self.params['jenkins_home']}/ansible_jenkins_plugin_cache.json"
plugin_version_urls = []
for base_url in self.params['updates_url']:
for update_json in self.params['plugin_versions_url_segment']:
plugin_version_urls.append("{}/{}".format(base_url, update_json))
plugin_version_urls.append(f"{base_url}/{update_json}")
try: # Check if file is saved localy
if os.path.exists(cache_path):
@ -725,7 +720,7 @@ class JenkinsPlugin(object):
plugin_versions = plugin_data.get("plugins", {}).get(name)
if not plugin_versions:
self.module.fail_json(msg="Plugin '{}' not found.".format(name))
self.module.fail_json(msg=f"Plugin '{name}' not found.")
sorted_versions = list(reversed(plugin_versions.items()))
@ -735,22 +730,21 @@ class JenkinsPlugin(object):
return 'latest' if idx == 0 else version_title
self.module.warn(
"No compatible version found for plugin '{}'. "
"Installing latest version.".format(name))
f"No compatible version found for plugin '{name}'. Installing latest version.")
return 'latest'
def _get_versioned_plugin_urls(self):
urls = []
for base_url in self.params['updates_url']:
for versioned_segment in self.params['versioned_plugins_url_segments']:
urls.append("{0}/{1}/{2}/{3}/{2}.hpi".format(base_url, versioned_segment, self.params['name'], self.params['version']))
urls.append(f"{base_url}/{versioned_segment}/{self.params['name']}/{self.params['version']}/{self.params['name']}.hpi")
return urls
def _get_update_center_urls(self):
urls = []
for base_url in self.params['updates_url']:
for update_json in self.params['update_json_url_segment']:
urls.append("{0}/{1}".format(base_url, update_json))
urls.append(f"{base_url}/{update_json}")
return urls
def _get_versioned_dependencies(self):
@ -791,7 +785,7 @@ class JenkinsPlugin(object):
os.close(tmp_update_fd)
except IOError as e:
self.module.fail_json(
msg="Cannot close the tmp updates file %s." % tmp_updates_file,
msg=f"Cannot close the tmp updates file {tmp_updates_file}.",
details=to_native(e))
else:
tmp_updates_file = updates_file
@ -805,11 +799,11 @@ class JenkinsPlugin(object):
data = json.loads(f.readline())
except IOError as e:
self.module.fail_json(
msg="Cannot open%s updates file." % (" temporary" if tmp_updates_file != updates_file else ""),
msg=f"Cannot open{' temporary' if tmp_updates_file != updates_file else ''} updates file.",
details=to_native(e))
except Exception as e:
self.module.fail_json(
msg="Cannot load JSON data from the%s updates file." % (" temporary" if tmp_updates_file != updates_file else ""),
msg=f"Cannot load JSON data from the{' temporary' if tmp_updates_file != updates_file else ''} updates file.",
details=to_native(e))
# Move the updates file to the right place if we could read it
@ -843,7 +837,7 @@ class JenkinsPlugin(object):
os.close(tmp_f_fd)
except IOError as e:
self.module.fail_json(
msg='Cannot close the temporal plugin file %s.' % tmp_f,
msg=f'Cannot close the temporal plugin file {tmp_f}.',
details=to_native(e))
# Move the file onto the right place
@ -877,7 +871,7 @@ class JenkinsPlugin(object):
# Perform the action
if not self.module.check_mode:
self._pm_query(action, "%sning" % action.capitalize())
self._pm_query(action, f"{action.capitalize()}ning")
changed = True
@ -900,22 +894,21 @@ class JenkinsPlugin(object):
# Perform the action
if not self.module.check_mode:
self._pm_query(
"make%sd" % action.capitalize(),
"%sing" % action[:-1].capitalize())
f"make{action.capitalize()}d",
f"{action[:-1].capitalize()}ing")
changed = True
return changed
def _pm_query(self, action, msg):
url = "%s/pluginManager/plugin/%s/%s" % (
self.params['url'], self.params['name'], action)
url = f"{self.params['url']}/pluginManager/plugin/{self.params['name']}/{action}"
# Send the request
self._get_url_data(
url,
msg_status="Plugin not found. %s" % url,
msg_exception="%s has failed." % msg,
msg_status=f"Plugin not found. {url}",
msg_exception=f"{msg} has failed.",
method="POST")
@staticmethod
@ -971,7 +964,7 @@ def main():
module.params['timeout'] = float(module.params['timeout'])
except ValueError as e:
module.fail_json(
msg='Cannot convert %s to float.' % module.params['timeout'],
msg=f"Cannot convert {module.params['timeout']} to float.",
details=to_native(e))
# Instantiate the JenkinsPlugin object
jp = JenkinsPlugin(module)

View file

@ -112,11 +112,11 @@ from ansible.module_utils.common.text.converters import to_native
def is_csrf_protection_enabled(module):
resp, info = fetch_url(module,
module.params['url'] + '/api/json',
f"{module.params['url']}/api/json",
timeout=module.params['timeout'],
method='GET')
if info["status"] != 200:
module.fail_json(msg="HTTP error " + str(info["status"]) + " " + info["msg"], output='')
module.fail_json(msg=f"HTTP error {info['status']} {info['msg']}", output='')
content = to_native(resp.read())
return json.loads(content).get('useCrumbs', False)
@ -124,12 +124,12 @@ def is_csrf_protection_enabled(module):
def get_crumb(module, cookies):
resp, info = fetch_url(module,
module.params['url'] + '/crumbIssuer/api/json',
f"{module.params['url']}/crumbIssuer/api/json",
method='GET',
timeout=module.params['timeout'],
cookies=cookies)
if info["status"] != 200:
module.fail_json(msg="HTTP error " + str(info["status"]) + " " + info["msg"], output='')
module.fail_json(msg=f"HTTP error {info['status']} {info['msg']}", output='')
content = to_native(resp.read())
return json.loads(content)
@ -161,7 +161,7 @@ def main():
try:
script_contents = Template(module.params['script']).substitute(module.params['args'])
except KeyError as err:
module.fail_json(msg="Error with templating variable: %s" % err, output='')
module.fail_json(msg=f"Error with templating variable: {err}", output='')
else:
script_contents = module.params['script']
@ -173,7 +173,7 @@ def main():
headers = {crumb['crumbRequestField']: crumb['crumb']}
resp, info = fetch_url(module,
module.params['url'] + "/scriptText",
f"{module.params['url']}/scriptText",
data=urlencode({'script': script_contents}),
headers=headers,
method="POST",
@ -181,12 +181,12 @@ def main():
cookies=cookies)
if info["status"] != 200:
module.fail_json(msg="HTTP error " + str(info["status"]) + " " + info["msg"], output='')
module.fail_json(msg=f"HTTP error {info['status']} {info['msg']}", output='')
result = to_native(resp.read())
if 'Exception:' in result and 'at java.lang.Thread' in result:
module.fail_json(msg="script failed with stacktrace:\n " + result, output='')
module.fail_json(msg=f"script failed with stacktrace:\n {result}", output='')
module.exit_json(
output=result,

View file

@ -567,7 +567,7 @@ class JIRA(StateModuleHelper):
if self.vars.account_id:
self.vars.fields['assignee'] = {'accountId': self.vars.account_id}
self.vars.uri = self.vars.uri.strip('/')
self.vars.set('restbase', self.vars.uri + '/rest/api/2')
self.vars.set('restbase', f"{self.vars.uri}/rest/api/2")
@cause_changes(when="success")
def operation_create(self):
@ -584,7 +584,7 @@ class JIRA(StateModuleHelper):
createfields.update(self.vars.fields)
data = {'fields': createfields}
url = self.vars.restbase + '/issue/'
url = f"{self.vars.restbase}/issue/"
self.vars.meta = self.post(url, data)
@cause_changes(when="success")
@ -600,7 +600,7 @@ class JIRA(StateModuleHelper):
if self.vars.fields:
data.update(self.vars.fields)
url = self.vars.restbase + '/issue/' + self.vars.issue + '/comment'
url = f"{self.vars.restbase}/issue/{self.vars.issue}/comment"
self.vars.meta = self.post(url, data)
@cause_changes(when="success")
@ -616,7 +616,7 @@ class JIRA(StateModuleHelper):
if self.vars.fields:
data.update(self.vars.fields)
url = self.vars.restbase + '/issue/' + self.vars.issue + '/worklog'
url = f"{self.vars.restbase}/issue/{self.vars.issue}/worklog"
self.vars.meta = self.post(url, data)
@cause_changes(when="success")
@ -624,7 +624,7 @@ class JIRA(StateModuleHelper):
data = {
'fields': self.vars.fields
}
url = self.vars.restbase + '/issue/' + self.vars.issue
url = f"{self.vars.restbase}/issue/{self.vars.issue}"
self.vars.meta = self.put(url, data)
@cause_changes(when="success")
@ -632,27 +632,27 @@ class JIRA(StateModuleHelper):
data = {
"update": self.vars.fields,
}
url = self.vars.restbase + '/issue/' + self.vars.issue
url = f"{self.vars.restbase}/issue/{self.vars.issue}"
self.vars.meta = self.put(url, data)
def operation_fetch(self):
url = self.vars.restbase + '/issue/' + self.vars.issue
url = f"{self.vars.restbase}/issue/{self.vars.issue}"
self.vars.meta = self.get(url)
def operation_search(self):
url = self.vars.restbase + '/search?jql=' + pathname2url(self.vars.jql)
url = f"{self.vars.restbase}/search?jql={pathname2url(self.vars.jql)}"
if self.vars.fields:
fields = self.vars.fields.keys()
url = url + '&fields=' + '&fields='.join([pathname2url(f) for f in fields])
url = f"{url}&fields={'&fields='.join([pathname2url(f) for f in fields])}"
if self.vars.maxresults:
url = url + '&maxResults=' + str(self.vars.maxresults)
url = f"{url}&maxResults={self.vars.maxresults}"
self.vars.meta = self.get(url)
@cause_changes(when="success")
def operation_transition(self):
# Find the transition id
turl = self.vars.restbase + '/issue/' + self.vars.issue + "/transitions"
turl = f"{self.vars.restbase}/issue/{self.vars.issue}/transitions"
tmeta = self.get(turl)
tid = None
@ -673,9 +673,9 @@ class JIRA(StateModuleHelper):
break
else:
if target is not None:
raise ValueError("Failed find valid transition for '%s'" % target)
raise ValueError(f"Failed find valid transition for '{target}'")
else:
raise ValueError("Failed find valid transition for ID '%s'" % tid)
raise ValueError(f"Failed find valid transition for ID '{tid}'")
fields = dict(self.vars.fields)
if self.vars.summary is not None:
@ -692,7 +692,7 @@ class JIRA(StateModuleHelper):
"add": {"body": self.vars.comment}
}],
}})
url = self.vars.restbase + '/issue/' + self.vars.issue + "/transitions"
url = f"{self.vars.restbase}/issue/{self.vars.issue}/transitions"
self.vars.meta = self.post(url, data)
@cause_changes(when="success")
@ -702,7 +702,7 @@ class JIRA(StateModuleHelper):
'inwardIssue': {'key': self.vars.inwardissue},
'outwardIssue': {'key': self.vars.outwardissue},
}
url = self.vars.restbase + '/issueLink/'
url = f"{self.vars.restbase}/issueLink/"
self.vars.meta = self.post(url, data)
@cause_changes(when="success")
@ -716,11 +716,11 @@ class JIRA(StateModuleHelper):
mime = v.attachment.get('mimetype')
if not os.path.isfile(filename):
raise ValueError('The provided filename does not exist: %s' % filename)
raise ValueError(f'The provided filename does not exist: {filename}')
content_type, data = self._prepare_attachment(filename, content, mime)
url = v.restbase + '/issue/' + v.issue + '/attachments'
url = f"{v.restbase}/issue/{v.issue}/attachments"
return True, self.post(
url, data, content_type=content_type, additional_headers={"X-Atlassian-Token": "no-check"}
)
@ -759,20 +759,20 @@ class JIRA(StateModuleHelper):
try:
content = base64.b64decode(content)
except binascii.Error as e:
raise Exception("Unable to base64 decode file content: %s" % e)
raise Exception(f"Unable to base64 decode file content: {e}")
lines = [
"--{0}".format(boundary),
'Content-Disposition: form-data; name="file"; filename={0}'.format(escape_quotes(name)),
"Content-Type: {0}".format("{0}/{1}".format(main_type, sub_type)),
f"--{boundary}",
f'Content-Disposition: form-data; name="file"; filename={escape_quotes(name)}',
f"Content-Type: {main_type}/{sub_type}",
'',
to_text(content),
"--{0}--".format(boundary),
f"--{boundary}--",
""
]
return (
"multipart/form-data; boundary={0}".format(boundary),
f"multipart/form-data; boundary={boundary}",
"\r\n".join(lines)
)
@ -802,14 +802,14 @@ class JIRA(StateModuleHelper):
if self.vars.token is not None:
headers.update({
"Content-Type": content_type,
"Authorization": "Bearer %s" % self.vars.token,
"Authorization": f"Bearer {self.vars.token}",
})
else:
auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(self.vars.username, self.vars.password),
auth = to_text(base64.b64encode(to_bytes(f'{self.vars.username}:{self.vars.password}',
errors='surrogate_or_strict')))
headers.update({
"Content-Type": content_type,
"Authorization": "Basic %s" % auth,
"Authorization": f"Basic {auth}",
})
response, info = fetch_url(
@ -821,13 +821,7 @@ class JIRA(StateModuleHelper):
try:
error = json.loads(info['body'])
except Exception:
msg = 'The request "{method} {url}" returned the unexpected status code {status} {msg}\n{body}'.format(
status=info['status'],
msg=info['msg'],
body=info.get('body'),
url=url,
method=method,
)
msg = f'The request "{method} {url}" returned the unexpected status code {info["status"]} {info["msg"]}\n{info.get("body")}'
self.module.fail_json(msg=to_native(msg), exception=traceback.format_exc())
if error:
msg = []

View file

@ -212,7 +212,7 @@ def run_module(module, tmpdir, kwriteconfig):
try:
module.atomic_move(b_tmpfile, os.path.abspath(b_path))
except IOError:
module.ansible.fail_json(msg='Unable to move temporary file %s to %s, IOError' % (tmpfile, result['path']), traceback=traceback.format_exc())
module.ansible.fail_json(msg=f"Unable to move temporary file {tmpfile} to {result['path']}, IOError", traceback=traceback.format_exc())
if result['changed']:
module.set_fs_attributes_if_different(file_args, result['changed'])

View file

@ -65,7 +65,7 @@ class Blacklist(StateModuleHelper):
)
def __init_module__(self):
self.pattern = re.compile(r'^blacklist\s+{0}$'.format(re.escape(self.vars.name)))
self.pattern = re.compile(rf'^blacklist\s+{re.escape(self.vars.name)}$')
self.vars.filename = self.vars.blacklist_file
self.vars.set('file_exists', os.path.exists(self.vars.filename), output=False, change=True)
if not self.vars.file_exists:
@ -97,13 +97,13 @@ class Blacklist(StateModuleHelper):
if self.vars.is_blacklisted:
return
self.vars.is_blacklisted = True
self.vars.lines = self.vars.lines + ['blacklist %s' % self.vars.name]
self.vars.lines = self.vars.lines + [f'blacklist {self.vars.name}']
def __quit_module__(self):
if self.has_changed() and not self.module.check_mode:
bkp = self.module.backup_local(self.vars.filename)
with open(self.vars.filename, "w") as fd:
fd.writelines(["{0}\n".format(x) for x in self.vars.lines])
fd.writelines([f"{x}\n" for x in self.vars.lines])
self.module.add_cleanup_file(bkp)

View file

@ -288,7 +288,7 @@ def create_or_update_executions(kc, config, realm='master'):
exec_found = True
if new_exec['index'] is None:
new_exec_index = exec_index
before += str(existing_executions[exec_index]) + '\n'
before += f"{existing_executions[exec_index]}\n"
execution = existing_executions[exec_index].copy()
# Remove exec from list in case 2 exec with same name
existing_executions[exec_index].clear()
@ -297,13 +297,13 @@ def create_or_update_executions(kc, config, realm='master'):
execution = kc.get_executions_representation(config, realm=realm)[exec_index]
exec_found = True
exec_index = new_exec_index
after += str(new_exec) + '\n'
after += f"{new_exec}\n"
elif new_exec["displayName"] is not None:
kc.create_subflow(new_exec["displayName"], flow_alias_parent, realm=realm, flowType=new_exec["subFlowType"])
execution = kc.get_executions_representation(config, realm=realm)[exec_index]
exec_found = True
exec_index = new_exec_index
after += str(new_exec) + '\n'
after += f"{new_exec}\n"
if exec_found:
changed = True
if exec_index != -1:
@ -326,11 +326,10 @@ def create_or_update_executions(kc, config, realm='master'):
kc.update_authentication_executions(flow_alias_parent, updated_exec, realm=realm)
diff = exec_index - new_exec_index
kc.change_execution_priority(updated_exec["id"], diff, realm=realm)
after += str(kc.get_executions_representation(config, realm=realm)[new_exec_index]) + '\n'
after += f"{kc.get_executions_representation(config, realm=realm)[new_exec_index]}\n"
return changed, dict(before=before, after=after)
except Exception as e:
kc.module.fail_json(msg='Could not create or update executions for authentication flow %s in realm %s: %s'
% (config["alias"], realm, str(e)))
kc.module.fail_json(msg=f"Could not create or update executions for authentication flow {config['alias']} in realm {realm}: {e}")
def main():
@ -404,7 +403,7 @@ def main():
result['diff'] = dict(before='', after='')
result['changed'] = False
result['end_state'] = {}
result['msg'] = new_auth_repr["alias"] + ' absent'
result['msg'] = f"{new_auth_repr['alias']} absent"
module.exit_json(**result)
elif state == 'present':
@ -425,7 +424,7 @@ def main():
# If the authentication still not exist on the server, raise an exception.
if auth_repr is None:
result['msg'] = "Authentication just created not found: " + str(new_auth_repr)
result['msg'] = f"Authentication just created not found: {new_auth_repr}"
module.fail_json(**result)
# Configure the executions for the flow
@ -456,7 +455,7 @@ def main():
auth_repr = kc.create_empty_auth_flow(config=new_auth_repr, realm=realm)
# If the authentication still not exist on the server, raise an exception.
if auth_repr is None:
result['msg'] = "Authentication just created not found: " + str(new_auth_repr)
result['msg'] = f"Authentication just created not found: {new_auth_repr}"
module.fail_json(**result)
# Configure the executions for the flow
@ -487,8 +486,7 @@ def main():
# delete it
kc.delete_authentication_flow_by_id(id=auth_repr["id"], realm=realm)
result['msg'] = 'Authentication flow: {alias} id: {id} is deleted'.format(alias=new_auth_repr['alias'],
id=auth_repr["id"])
result['msg'] = f"Authentication flow: {new_auth_repr['alias']} id: {auth_repr['id']} is deleted"
module.exit_json(**result)

View file

@ -305,15 +305,13 @@ def main():
# Check if name is provided
if 'name' not in desired_required_action or desired_required_action['name'] is None:
module.fail_json(
msg='Unable to register required action %s in realm %s: name not included'
% (desired_required_action['alias'], realm)
msg=f"Unable to register required action {desired_required_action['alias']} in realm {realm}: name not included"
)
# Check if provider ID is provided
if 'providerId' not in desired_required_action or desired_required_action['providerId'] is None:
module.fail_json(
msg='Unable to register required action %s in realm %s: providerId not included'
% (desired_required_action['alias'], realm)
msg=f"Unable to register required action {desired_required_action['alias']} in realm {realm}: providerId not included"
)
register_required_actions.append(desired_required_action)

View file

@ -178,8 +178,7 @@ def main():
# "clientId"
cid = kc.get_client_id(client_id, realm=realm)
if not cid:
module.fail_json(msg='Invalid client %s for realm %s' %
(client_id, realm))
module.fail_json(msg=f'Invalid client {client_id} for realm {realm}')
# Get current state of the Authorization Scope using its name as the search
# filter. This returns False if it is not found.
@ -267,8 +266,7 @@ def main():
elif not before_authz_scope and state == 'absent':
result['changed'] = False
else:
module.fail_json(msg='Unable to determine what to do with authorization scope %s of client %s in realm %s' % (
name, client_id, realm))
module.fail_json(msg=f'Unable to determine what to do with authorization scope {name} of client {client_id} in realm {realm}')
module.exit_json(**result)

View file

@ -161,8 +161,7 @@ def main():
cid = kc.get_client_id(client_id, realm=realm)
if not cid:
module.fail_json(msg='Invalid client %s for realm %s' %
(client_id, realm))
module.fail_json(msg=f'Invalid client {client_id} for realm {realm}')
before_authz_custom_policy = kc.get_authz_policy_by_name(
name=name, client_id=cid, realm=realm)
@ -173,31 +172,31 @@ def main():
# Modifying existing custom policies is not possible
if before_authz_custom_policy and state == 'present':
result['msg'] = "Custom policy %s already exists" % (name)
result['msg'] = f"Custom policy {name} already exists"
result['changed'] = False
result['end_state'] = desired_authz_custom_policy
elif not before_authz_custom_policy and state == 'present':
if module.check_mode:
result['msg'] = "Would create custom policy %s" % (name)
result['msg'] = f"Would create custom policy {name}"
else:
kc.create_authz_custom_policy(
payload=desired_authz_custom_policy, policy_type=policy_type, client_id=cid, realm=realm)
result['msg'] = "Custom policy %s created" % (name)
result['msg'] = f"Custom policy {name} created"
result['changed'] = True
result['end_state'] = desired_authz_custom_policy
elif before_authz_custom_policy and state == 'absent':
if module.check_mode:
result['msg'] = "Would remove custom policy %s" % (name)
result['msg'] = f"Would remove custom policy {name}"
else:
kc.remove_authz_custom_policy(
policy_id=before_authz_custom_policy['id'], client_id=cid, realm=realm)
result['msg'] = "Custom policy %s removed" % (name)
result['msg'] = f"Custom policy {name} removed"
result['changed'] = True
result['end_state'] = {}
elif not before_authz_custom_policy and state == 'absent':
result['msg'] = "Custom policy %s does not exist" % (name)
result['msg'] = f"Custom policy {name} does not exist"
result['changed'] = False
result['end_state'] = {}

View file

@ -294,8 +294,7 @@ def main():
# Get id of the client based on client_id
cid = kc.get_client_id(client_id, realm=realm)
if not cid:
module.fail_json(msg='Invalid client %s for realm %s' %
(client_id, realm))
module.fail_json(msg=f'Invalid client {client_id} for realm {realm}')
# Get current state of the permission using its name as the search
# filter. This returns False if it is not found.
@ -324,7 +323,7 @@ def main():
if resources:
r = kc.get_authz_resource_by_name(resources[0], cid, realm)
if not r:
module.fail_json(msg='Unable to find authorization resource with name %s for client %s in realm %s' % (resources[0], cid, realm))
module.fail_json(msg=f'Unable to find authorization resource with name {resources[0]} for client {cid} in realm {realm}')
else:
payload['resources'].append(r['_id'])
@ -336,7 +335,7 @@ def main():
for scope in scopes:
s = kc.get_authz_authorization_scope_by_name(scope, cid, realm)
if r and not s['id'] in resource_scopes:
module.fail_json(msg='Resource %s does not include scope %s for client %s in realm %s' % (resources[0], scope, client_id, realm))
module.fail_json(msg=f'Resource {resources[0]} does not include scope {scope} for client {client_id} in realm {realm}')
else:
payload['scopes'].append(s['id'])
@ -345,7 +344,7 @@ def main():
for resource in resources:
r = kc.get_authz_resource_by_name(resource, cid, realm)
if not r:
module.fail_json(msg='Unable to find authorization resource with name %s for client %s in realm %s' % (resource, cid, realm))
module.fail_json(msg=f'Unable to find authorization resource with name {resource} for client {cid} in realm {realm}')
else:
payload['resources'].append(r['_id'])
@ -357,7 +356,7 @@ def main():
if p:
payload['policies'].append(p['id'])
else:
module.fail_json(msg='Unable to find authorization policy with name %s for client %s in realm %s' % (policy, client_id, realm))
module.fail_json(msg=f'Unable to find authorization policy with name {policy} for client {client_id} in realm {realm}')
# Add "id" to payload for update operations
if permission:
@ -367,8 +366,8 @@ def main():
# existing permission's type - something that can't be done without a
# full delete -> (re)create cycle.
if permission['type'] != payload['type']:
module.fail_json(msg='Modifying the type of permission (scope/resource) is not supported: \
permission %s of client %s in realm %s unchanged' % (permission['id'], cid, realm))
module.fail_json(msg=(f"Modifying the type of permission (scope/resource) is not supported: "
f"permission {permission['id']} of client {cid} in realm {realm} unchanged"))
# Updating an authorization permission is tricky for several reasons.
# Firstly, the current permission is retrieved using a _policy_ endpoint,
@ -419,8 +418,7 @@ def main():
elif not permission and state == 'absent':
result['changed'] = False
else:
module.fail_json(msg='Unable to determine what to do with permission %s of client %s in realm %s' % (
name, client_id, realm))
module.fail_json(msg=f'Unable to determine what to do with permission {name} of client {client_id} in realm {realm}')
module.exit_json(**result)

View file

@ -155,8 +155,7 @@ def main():
# Get id of the client based on client_id
cid = kc.get_client_id(client_id, realm=realm)
if not cid:
module.fail_json(msg='Invalid client %s for realm %s' %
(client_id, realm))
module.fail_json(msg=f'Invalid client {client_id} for realm {realm}')
# Get current state of the permission using its name as the search
# filter. This returns False if it is not found.

View file

@ -827,7 +827,7 @@ def check_optional_scopes_not_default(desired_client, clientScopesBehavior, modu
return
for scope in desired_client['optionalClientScopes']:
if scope in desired_client['defaultClientScopes']:
module.fail_json(msg='Client scope %s cannot be both default and optional' % scope)
module.fail_json(msg=f'Client scope {scope} cannot be both default and optional')
def normalise_cr(clientrep, remove_ids=False):
@ -941,7 +941,7 @@ def get_authentication_flow_id(flow_name, realm, kc):
flow = kc.get_authentication_flow_by_alias(flow_name, realm)
if flow:
return flow["id"]
kc.module.fail_json(msg='Authentification flow %s not found in realm %s' % (flow_name, realm))
kc.module.fail_json(msg=f'Authentification flow {flow_name} not found in realm {realm}')
def flow_binding_from_dict_to_model(newClientFlowBinding, realm, kc):
@ -1353,7 +1353,7 @@ def main():
result['end_state'] = sanitize_cr(after_client)
result['msg'] = 'Client %s has been created.' % desired_client['clientId']
result['msg'] = f"Client {desired_client['clientId']} has been created."
module.exit_json(**result)
else:
@ -1367,7 +1367,7 @@ def main():
if before_norm == desired_norm:
result['changed'] = False
result['end_state'] = sanitize_cr(before_client)
result['msg'] = 'No changes required for Client %s.' % desired_client['clientId']
result['msg'] = f"No changes required for Client {desired_client['clientId']}."
module.exit_json(**result)
# Process an update
@ -1397,7 +1397,7 @@ def main():
result['end_state'] = sanitize_cr(after_client)
result['msg'] = 'Client %s has been updated.' % desired_client['clientId']
result['msg'] = f"Client {desired_client['clientId']} has been updated."
module.exit_json(**result)
else:
@ -1416,7 +1416,7 @@ def main():
result['end_state'] = {}
result['msg'] = 'Client %s has been deleted.' % before_client['clientId']
result['msg'] = f"Client {before_client['clientId']} has been deleted."
module.exit_json(**result)

View file

@ -314,11 +314,11 @@ def main():
if group_rep is not None:
gid = group_rep['id']
else:
module.fail_json(msg='Could not fetch group %s:' % group_name)
module.fail_json(msg=f'Could not fetch group {group_name}:')
if cid is None:
cid = kc.get_client_id(client_id, realm=realm)
if cid is None:
module.fail_json(msg='Could not fetch client %s:' % client_id)
module.fail_json(msg=f'Could not fetch client {client_id}:')
if roles is None:
module.exit_json(msg="Nothing to do (no roles specified).")
else:
@ -331,12 +331,12 @@ def main():
if role_id is not None:
role['id'] = role_id
else:
module.fail_json(msg='Could not fetch role %s:' % (role['name']))
module.fail_json(msg=f"Could not fetch role {role['name']}:")
# Fetch missing role_name
else:
role['name'] = kc.get_client_group_rolemapping_by_id(gid, cid, role['id'], realm=realm)['name']
if role['name'] is None:
module.fail_json(msg='Could not fetch role %s' % (role['id']))
module.fail_json(msg=f"Could not fetch role {role['id']}")
# Get effective client-level role mappings
available_roles_before = kc.get_client_group_available_rolemappings(gid, cid, realm=realm)
@ -376,7 +376,7 @@ def main():
if module.check_mode:
module.exit_json(**result)
kc.add_group_rolemapping(gid, cid, update_roles, realm=realm)
result['msg'] = 'Roles %s assigned to group %s.' % (update_roles, group_name)
result['msg'] = f'Roles {update_roles} assigned to group {group_name}.'
assigned_roles_after = kc.get_client_group_composite_rolemappings(gid, cid, realm=realm)
result['end_state'] = assigned_roles_after
module.exit_json(**result)
@ -388,14 +388,14 @@ def main():
if module.check_mode:
module.exit_json(**result)
kc.delete_group_rolemapping(gid, cid, update_roles, realm=realm)
result['msg'] = 'Roles %s removed from group %s.' % (update_roles, group_name)
result['msg'] = f'Roles {update_roles} removed from group {group_name}.'
assigned_roles_after = kc.get_client_group_composite_rolemappings(gid, cid, realm=realm)
result['end_state'] = assigned_roles_after
module.exit_json(**result)
# Do nothing
else:
result['changed'] = False
result['msg'] = 'Nothing to do, roles %s are %s with group %s.' % (roles, 'mapped' if state == 'present' else 'not mapped', group_name)
result['msg'] = f"Nothing to do, roles {roles} are {'mapped' if state == 'present' else 'not mapped'} with group {group_name}."
module.exit_json(**result)

View file

@ -191,18 +191,18 @@ def main():
objRealm = kc.get_realm_by_id(realm)
if not objRealm:
module.fail_json(msg="Failed to retrive realm '{realm}'".format(realm=realm))
module.fail_json(msg=f"Failed to retrive realm '{realm}'")
objClient = kc.get_client_by_clientid(clientid, realm)
if not objClient:
module.fail_json(msg="Failed to retrive client '{realm}.{clientid}'".format(realm=realm, clientid=clientid))
module.fail_json(msg=f"Failed to retrive client '{realm}.{clientid}'")
if objClient["fullScopeAllowed"] and state == "present":
module.fail_json(msg="FullScopeAllowed is active for Client '{realm}.{clientid}'".format(realm=realm, clientid=clientid))
module.fail_json(msg=f"FullScopeAllowed is active for Client '{realm}.{clientid}'")
if client_scope_id:
objClientScope = kc.get_client_by_clientid(client_scope_id, realm)
if not objClientScope:
module.fail_json(msg="Failed to retrive client '{realm}.{client_scope_id}'".format(realm=realm, client_scope_id=client_scope_id))
module.fail_json(msg=f"Failed to retrive client '{realm}.{client_scope_id}'")
before_role_mapping = kc.get_client_role_scope_from_client(objClient["id"], objClientScope["id"], realm)
else:
before_role_mapping = kc.get_client_role_scope_from_realm(objClient["id"], realm)
@ -224,10 +224,9 @@ def main():
for role_name in role_names:
if role_name not in client_scope_roles_by_name:
if client_scope_id:
module.fail_json(msg="Failed to retrive role '{realm}.{client_scope_id}.{role_name}'"
.format(realm=realm, client_scope_id=client_scope_id, role_name=role_name))
module.fail_json(msg=f"Failed to retrive role '{realm}.{client_scope_id}.{role_name}'")
else:
module.fail_json(msg="Failed to retrive role '{realm}.{role_name}'".format(realm=realm, role_name=role_name))
module.fail_json(msg=f"Failed to retrive role '{realm}.{role_name}'")
if role_name not in role_mapping_by_name:
role_mapping_to_manipulate.append(client_scope_roles_by_name[role_name])
role_mapping_by_name[role_name] = client_scope_roles_by_name[role_name]
@ -249,7 +248,7 @@ def main():
if not result['changed']:
# no changes
result['end_state'] = before_role_mapping
result['msg'] = "No changes required for client role scope {name}.".format(name=clientid)
result['msg'] = f"No changes required for client role scope {clientid}."
elif state == "present":
# doing update
if module.check_mode:
@ -258,7 +257,7 @@ def main():
result['end_state'] = kc.update_client_role_scope_from_client(role_mapping_to_manipulate, objClient["id"], objClientScope["id"], realm)
else:
result['end_state'] = kc.update_client_role_scope_from_realm(role_mapping_to_manipulate, objClient["id"], realm)
result['msg'] = "Client role scope for {name} has been updated".format(name=clientid)
result['msg'] = f"Client role scope for {clientid} has been updated"
else:
# doing delete
if module.check_mode:
@ -267,7 +266,7 @@ def main():
result['end_state'] = kc.delete_client_role_scope_from_client(role_mapping_to_manipulate, objClient["id"], objClientScope["id"], realm)
else:
result['end_state'] = kc.delete_client_role_scope_from_realm(role_mapping_to_manipulate, objClient["id"], realm)
result['msg'] = "Client role scope for {name} has been deleted".format(name=clientid)
result['msg'] = f"Client role scope for {clientid} has been deleted"
module.exit_json(**result)

View file

@ -444,8 +444,7 @@ def main():
result['end_state'] = sanitize_cr(after_clientscope)
result['msg'] = 'Clientscope {name} has been created with ID {id}'.format(name=after_clientscope['name'],
id=after_clientscope['id'])
result['msg'] = f"Clientscope {after_clientscope['name']} has been created with ID {after_clientscope['id']}"
else:
if state == 'present':
@ -457,7 +456,7 @@ def main():
if normalise_cr(desired_clientscope, remove_ids=True) == normalise_cr(before_clientscope, remove_ids=True):
result['changed'] = False
result['end_state'] = sanitize_cr(desired_clientscope)
result['msg'] = "No changes required to clientscope {name}.".format(name=before_clientscope['name'])
result['msg'] = f"No changes required to clientscope {before_clientscope['name']}."
module.exit_json(**result)
# doing an update
@ -495,7 +494,7 @@ def main():
result['end_state'] = after_clientscope
result['msg'] = "Clientscope {id} has been updated".format(id=after_clientscope['id'])
result['msg'] = f"Clientscope {after_clientscope['id']} has been updated"
module.exit_json(**result)
else:
@ -514,7 +513,7 @@ def main():
result['end_state'] = {}
result['msg'] = "Clientscope {name} has been deleted".format(name=before_clientscope['name'])
result['msg'] = f"Clientscope {before_clientscope['name']} has been deleted"
module.exit_json(**result)

View file

@ -156,7 +156,7 @@ def main():
result = {
'clientsecret_info': clientsecret,
'msg': 'Get client secret successful for ID {id}'.format(id=id)
'msg': f'Get client secret successful for ID {id}'
}
module.exit_json(**result)

View file

@ -166,7 +166,7 @@ def main():
clientsecret = kc.create_clientsecret(id=id, realm=realm)
result = {
"msg": 'New client secret has been generated for ID {id}'.format(id=id),
"msg": f'New client secret has been generated for ID {id}',
"end_state": clientsecret
}
module.exit_json(**result)

View file

@ -392,7 +392,7 @@ def main():
result['end_state'] = after_clientt
result['msg'] = 'Client template %s has been created.' % desired_clientt['name']
result['msg'] = f"Client template {desired_clientt['name']} has been created."
module.exit_json(**result)
else:
@ -420,7 +420,7 @@ def main():
if module._diff:
result['diff'] = dict(before=before_clientt, after=after_clientt)
result['msg'] = 'Client template %s has been updated.' % desired_clientt['name']
result['msg'] = f"Client template {desired_clientt['name']} has been updated."
module.exit_json(**result)
else:
@ -439,7 +439,7 @@ def main():
result['end_state'] = {}
result['msg'] = 'Client template %s has been deleted.' % before_clientt['name']
result['msg'] = f"Client template {before_clientt['name']} has been deleted."
module.exit_json(**result)

View file

@ -255,7 +255,7 @@ def main():
before_component[param] = component[param]
if changeset_copy[param] != component[param] and param != 'config':
changes += "%s: %s -> %s, " % (param, component[param], changeset_copy[param])
changes += f"{param}: {component[param]} -> {changeset_copy[param]}, "
result['changed'] = True
# Compare parameters under the "config" key
for p, v in changeset_copy['config'].items():
@ -264,7 +264,7 @@ def main():
except KeyError:
before_component['config'][p] = []
if changeset_copy['config'][p] != component['config'][p]:
changes += "config.%s: %s -> %s, " % (p, component['config'][p], changeset_copy['config'][p])
changes += f"config.{p}: {component['config'][p]} -> {changeset_copy['config'][p]}, "
result['changed'] = True
# Check all the possible states of the resource and do what is needed to
@ -276,12 +276,12 @@ def main():
result['diff'] = dict(before=before_component, after=changeset_copy)
if module.check_mode:
result['msg'] = "Component %s would be changed: %s" % (name, changes.strip(", "))
result['msg'] = f"Component {name} would be changed: {changes.strip(', ')}"
else:
kc.update_component(changeset, parent_id)
result['msg'] = "Component %s changed: %s" % (name, changes.strip(", "))
result['msg'] = f"Component {name} changed: {changes.strip(', ')}"
else:
result['msg'] = "Component %s was in sync" % (name)
result['msg'] = f"Component {name} was in sync"
result['end_state'] = changeset_copy
elif component_id and state == 'absent':
@ -290,11 +290,11 @@ def main():
if module.check_mode:
result['changed'] = True
result['msg'] = "Component %s would be deleted" % (name)
result['msg'] = f"Component {name} would be deleted"
else:
kc.delete_component(component_id, parent_id)
result['changed'] = True
result['msg'] = "Component %s deleted" % (name)
result['msg'] = f"Component {name} deleted"
result['end_state'] = {}
elif not component_id and state == 'present':
@ -303,16 +303,16 @@ def main():
if module.check_mode:
result['changed'] = True
result['msg'] = "Component %s would be created" % (name)
result['msg'] = f"Component {name} would be created"
else:
kc.create_component(changeset, parent_id)
result['changed'] = True
result['msg'] = "Component %s created" % (name)
result['msg'] = f"Component {name} created"
result['end_state'] = changeset_copy
elif not component_id and state == 'absent':
result['changed'] = False
result['msg'] = "Component %s not present" % (name)
result['msg'] = f"Component {name} not present"
result['end_state'] = {}
module.exit_json(**result)

View file

@ -142,19 +142,19 @@ def main():
objRealm = kc.get_realm_by_id(realm)
if not objRealm:
module.fail_json(msg="Failed to retrive realm '{realm}'".format(realm=realm))
module.fail_json(msg=f"Failed to retrive realm '{realm}'")
filters = []
if parentId:
filters.append("parent=%s" % (quote(parentId, safe='')))
filters.append(f"parent={quote(parentId, safe='')}")
else:
filters.append("parent=%s" % (quote(objRealm['id'], safe='')))
filters.append(f"parent={quote(objRealm['id'], safe='')}")
if name:
filters.append("name=%s" % (quote(name, safe='')))
filters.append(f"name={quote(name, safe='')}")
if providerType:
filters.append("type=%s" % (quote(providerType, safe='')))
filters.append(f"type={quote(providerType, safe='')}")
result['components'] = kc.get_components(filter="&".join(filters), realm=realm)

View file

@ -422,8 +422,7 @@ def main():
result['end_state'] = after_group
result['msg'] = 'Group {name} has been created with ID {id}'.format(name=after_group['name'],
id=after_group['id'])
result['msg'] = f"Group {after_group['name']} has been created with ID {after_group['id']}"
module.exit_json(**result)
else:
@ -434,7 +433,7 @@ def main():
if desired_group == before_group:
result['changed'] = False
result['end_state'] = desired_group
result['msg'] = "No changes required to group {name}.".format(name=before_group['name'])
result['msg'] = f"No changes required to group {before_group['name']}."
module.exit_json(**result)
# doing an update
@ -453,7 +452,7 @@ def main():
result['end_state'] = after_group
result['msg'] = "Group {id} has been updated".format(id=after_group['id'])
result['msg'] = f"Group {after_group['id']} has been updated"
module.exit_json(**result)
else:
@ -472,7 +471,7 @@ def main():
result['end_state'] = {}
result['msg'] = "Group {name} has been deleted".format(name=before_group['name'])
result['msg'] = f"Group {before_group['name']} has been deleted"
module.exit_json(**result)

View file

@ -654,7 +654,7 @@ def main():
result['end_state'] = sanitize(after_idp)
result['msg'] = 'Identity provider {alias} has been created'.format(alias=alias)
result['msg'] = f'Identity provider {alias} has been created'
module.exit_json(**result)
else:
@ -665,7 +665,7 @@ def main():
if desired_idp == before_idp:
result['changed'] = False
result['end_state'] = sanitize(desired_idp)
result['msg'] = "No changes required to identity provider {alias}.".format(alias=alias)
result['msg'] = f"No changes required to identity provider {alias}."
module.exit_json(**result)
# doing an update
@ -703,7 +703,7 @@ def main():
result['end_state'] = sanitize(after_idp)
result['msg'] = "Identity provider {alias} has been updated".format(alias=alias)
result['msg'] = f"Identity provider {alias} has been updated"
module.exit_json(**result)
elif state == 'absent':
@ -721,7 +721,7 @@ def main():
result['end_state'] = {}
result['msg'] = "Identity provider {alias} has been deleted".format(alias=alias)
result['msg'] = f"Identity provider {alias} has been deleted"
module.exit_json(**result)

View file

@ -1049,7 +1049,7 @@ def main():
result['end_state'] = sanitize_cr(after_realm)
result['msg'] = 'Realm %s has been created.' % desired_realm['realm']
result['msg'] = f"Realm {desired_realm['realm']} has been created."
module.exit_json(**result)
else:
@ -1083,7 +1083,7 @@ def main():
result['diff'] = dict(before=before_realm_sanitized,
after=sanitize_cr(after_realm))
result['msg'] = 'Realm %s has been updated.' % desired_realm['realm']
result['msg'] = f"Realm {desired_realm['realm']} has been updated."
module.exit_json(**result)
else:
@ -1102,7 +1102,7 @@ def main():
result['proposed'] = {}
result['end_state'] = {}
result['msg'] = 'Realm %s has been deleted.' % before_realm['realm']
result['msg'] = f"Realm {before_realm['realm']} has been deleted."
module.exit_json(**result)

View file

@ -124,7 +124,7 @@ def main():
realm_info = kc.get_realm_info_by_id(realm=realm)
result['realm_info'] = realm_info
result['msg'] = 'Get realm public info successful for ID {realm}'.format(realm=realm)
result['msg'] = f'Get realm public info successful for ID {realm}'
module.exit_json(**result)

View file

@ -392,14 +392,14 @@ def main():
before_realm_key[param] = key[param]
if changeset_copy[param] != key[param] and param != 'config':
changes += "%s: %s -> %s, " % (param, key[param], changeset_copy[param])
changes += f"{param}: {key[param]} -> {changeset_copy[param]}, "
result['changed'] = True
# Compare parameters under the "config" key
for p, v in changeset_copy['config'].items():
before_realm_key['config'][p] = key['config'][p]
if changeset_copy['config'][p] != key['config'][p]:
changes += "config.%s: %s -> %s, " % (p, key['config'][p], changeset_copy['config'][p])
changes += f"config.{p}: {key['config'][p]} -> {changeset_copy['config'][p]}, "
result['changed'] = True
# Sanitize linefeeds for the privateKey. Without this the JSON payload
@ -418,16 +418,16 @@ def main():
result['diff'] = dict(before=before_realm_key, after=changeset_copy)
if module.check_mode:
result['msg'] = "Realm key %s would be changed: %s" % (name, changes.strip(", "))
result['msg'] = f"Realm key {name} would be changed: {changes.strip(', ')}"
else:
kc.update_component(changeset, parent_id)
result['msg'] = "Realm key %s changed: %s" % (name, changes.strip(", "))
result['msg'] = f"Realm key {name} changed: {changes.strip(', ')}"
elif not result['changed'] and force:
kc.update_component(changeset, parent_id)
result['changed'] = True
result['msg'] = "Realm key %s was forcibly updated" % (name)
result['msg'] = f"Realm key {name} was forcibly updated"
else:
result['msg'] = "Realm key %s was in sync" % (name)
result['msg'] = f"Realm key {name} was in sync"
result['end_state'] = changeset_copy
elif key_id and state == 'absent':
@ -438,11 +438,11 @@ def main():
if module.check_mode:
result['changed'] = True
result['msg'] = "Realm key %s would be deleted" % (name)
result['msg'] = f"Realm key {name} would be deleted"
else:
kc.delete_component(key_id, parent_id)
result['changed'] = True
result['msg'] = "Realm key %s deleted" % (name)
result['msg'] = f"Realm key {name} deleted"
result['end_state'] = {}
elif not key_id and state == 'present':
@ -451,16 +451,16 @@ def main():
if module.check_mode:
result['changed'] = True
result['msg'] = "Realm key %s would be created" % (name)
result['msg'] = f"Realm key {name} would be created"
else:
kc.create_component(changeset, parent_id)
result['changed'] = True
result['msg'] = "Realm key %s created" % (name)
result['msg'] = f"Realm key {name} created"
result['end_state'] = changeset_copy
elif not key_id and state == 'absent':
result['changed'] = False
result['msg'] = "Realm key %s not present" % (name)
result['msg'] = f"Realm key {name} not present"
result['end_state'] = {}
module.exit_json(**result)

View file

@ -122,9 +122,7 @@ def main():
keys_metadata = kc.get_realm_keys_metadata_by_id(realm=realm)
result["keys_metadata"] = keys_metadata
result["msg"] = "Get realm keys metadata successful for ID {realm}".format(
realm=realm
)
result["msg"] = f"Get realm keys metadata successful for ID {realm}"
module.exit_json(**result)

View file

@ -293,7 +293,7 @@ def main():
if group_rep is not None:
gid = group_rep['id']
else:
module.fail_json(msg='Could not fetch group %s:' % group_name)
module.fail_json(msg=f'Could not fetch group {group_name}:')
else:
group_rep = kc.get_group_by_groupid(gid, realm=realm)
@ -309,7 +309,7 @@ def main():
if role_rep is not None:
role['id'] = role_rep['id']
else:
module.fail_json(msg='Could not fetch realm role %s by name:' % (role['name']))
module.fail_json(msg=f"Could not fetch realm role {role['name']} by name:")
# Fetch missing role_name
else:
for realm_role in kc.get_realm_roles(realm=realm):
@ -318,7 +318,7 @@ def main():
break
if role['name'] is None:
module.fail_json(msg='Could not fetch realm role %s by ID' % (role['id']))
module.fail_json(msg=f"Could not fetch realm role {role['id']} by ID")
assigned_roles_before = group_rep.get('realmRoles', [])
@ -357,11 +357,11 @@ def main():
if state == 'present':
# Assign roles
kc.add_group_realm_rolemapping(gid=gid, role_rep=update_roles, realm=realm)
result['msg'] = 'Realm roles %s assigned to groupId %s.' % (update_roles, gid)
result['msg'] = f'Realm roles {update_roles} assigned to groupId {gid}.'
else:
# Remove mapping of role
kc.delete_group_realm_rolemapping(gid=gid, role_rep=update_roles, realm=realm)
result['msg'] = 'Realm roles %s removed from groupId %s.' % (update_roles, gid)
result['msg'] = f'Realm roles {update_roles} removed from groupId {gid}.'
if gid is None:
assigned_roles_after = kc.get_group_by_name(group_name, realm=realm, parents=parents).get('realmRoles', [])
@ -372,7 +372,7 @@ def main():
# Do nothing
else:
result['changed'] = False
result['msg'] = 'Nothing to do, roles %s are %s with group %s.' % (roles, 'mapped' if state == 'present' else 'not mapped', group_name)
result['msg'] = f"Nothing to do, roles {roles} are {'mapped' if state == 'present' else 'not mapped'} with group {group_name}."
module.exit_json(**result)

View file

@ -354,7 +354,7 @@ def main():
result['end_state'] = after_role
result['msg'] = 'Role {name} has been created'.format(name=name)
result['msg'] = f'Role {name} has been created'
module.exit_json(**result)
else:
@ -380,7 +380,7 @@ def main():
if is_struct_included(desired_role, before_role, exclude=compare_exclude):
result['changed'] = False
result['end_state'] = desired_role
result['msg'] = "No changes required to role {name}.".format(name=name)
result['msg'] = f"No changes required to role {name}."
module.exit_json(**result)
# doing an update
@ -404,7 +404,7 @@ def main():
result['end_state'] = after_role
result['msg'] = "Role {name} has been updated".format(name=name)
result['msg'] = f"Role {name} has been updated"
module.exit_json(**result)
else:
@ -425,7 +425,7 @@ def main():
result['end_state'] = {}
result['msg'] = "Role {name} has been deleted".format(name=name)
result['msg'] = f"Role {name} has been deleted"
module.exit_json(**result)

View file

@ -473,7 +473,7 @@ def main():
else:
# Delete user
kc.delete_user(user_id=before_user['id'], realm=realm)
result["msg"] = 'User %s deleted' % (before_user['username'])
result["msg"] = f"User {before_user['username']} deleted"
changed = True
else:
@ -496,7 +496,7 @@ def main():
module.exit_json(**result)
# Create the user
after_user = kc.create_user(userrep=desired_user, realm=realm)
result["msg"] = 'User %s created' % (desired_user['username'])
result["msg"] = f"User {desired_user['username']} created"
# Add user ID to new representation
desired_user['id'] = after_user["id"]
else:
@ -527,9 +527,9 @@ def main():
after_user["groups"] = kc.get_user_groups(user_id=desired_user["id"], realm=realm)
result["end_state"] = after_user
if changed:
result["msg"] = 'User %s updated' % (desired_user['username'])
result["msg"] = f"User {desired_user['username']} updated"
else:
result["msg"] = 'No changes made for user %s' % (desired_user['username'])
result["msg"] = f"No changes made for user {desired_user['username']}"
result['changed'] = changed
module.exit_json(**result)

View file

@ -888,7 +888,7 @@ def main():
if cid is None:
found = kc.get_components(urlencode(dict(type='org.keycloak.storage.UserStorageProvider', name=name)), realm)
if len(found) > 1:
module.fail_json(msg='No ID given and found multiple user federations with name `{name}`. Cannot continue.'.format(name=name))
module.fail_json(msg=f'No ID given and found multiple user federations with name `{name}`. Cannot continue.')
before_comp = next(iter(found), None)
if before_comp is not None:
cid = before_comp['id']
@ -918,7 +918,7 @@ def main():
# special handling of mappers list to allow change detection
if module.params.get('mappers') is not None:
if module.params['provider_id'] in ['kerberos', 'sssd']:
module.fail_json(msg='Cannot configure mappers for {type} provider.'.format(type=module.params['provider_id']))
module.fail_json(msg=f"Cannot configure mappers for {module.params['provider_id']} provider.")
for change in module.params['mappers']:
change = {k: v for k, v in change.items() if v is not None}
if change.get('id') is None and change.get('name') is None:
@ -932,7 +932,7 @@ def main():
else:
found = [before_mapper for before_mapper in before_comp.get('mappers', []) if before_mapper['name'] == change['name']]
if len(found) > 1:
module.fail_json(msg='Found multiple mappers with name `{name}`. Cannot continue.'.format(name=change['name']))
module.fail_json(msg=f"Found multiple mappers with name `{change['name']}`. Cannot continue.")
if len(found) == 1:
old_mapper = found[0]
else:
@ -988,7 +988,7 @@ def main():
for desired_mapper in desired_mappers:
found = [default_mapper for default_mapper in default_mappers if default_mapper['name'] == desired_mapper['name']]
if len(found) > 1:
module.fail_json(msg='Found multiple mappers with name `{name}`. Cannot continue.'.format(name=desired_mapper['name']))
module.fail_json(msg=f"Found multiple mappers with name `{desired_mapper['name']}`. Cannot continue.")
if len(found) == 1:
old_mapper = found[0]
else:
@ -1017,7 +1017,7 @@ def main():
if module._diff:
result['diff'] = dict(before='', after=sanitize(after_comp))
result['end_state'] = sanitize(after_comp)
result['msg'] = "User federation {id} has been created".format(id=cid)
result['msg'] = f"User federation {cid} has been created"
module.exit_json(**result)
else:
@ -1035,7 +1035,7 @@ def main():
if desired_copy == before_copy:
result['changed'] = False
result['end_state'] = sanitize(desired_comp)
result['msg'] = "No changes required to user federation {id}.".format(id=cid)
result['msg'] = f"No changes required to user federation {cid}."
module.exit_json(**result)
# doing an update
@ -1075,7 +1075,7 @@ def main():
if module._diff:
result['diff'] = dict(before=before_comp_sanitized, after=after_comp_sanitized)
result['changed'] = before_comp_sanitized != after_comp_sanitized
result['msg'] = "User federation {id} has been updated".format(id=cid)
result['msg'] = f"User federation {cid} has been updated"
module.exit_json(**result)
elif state == 'absent':
@ -1093,7 +1093,7 @@ def main():
result['end_state'] = {}
result['msg'] = "User federation {id} has been deleted".format(id=cid)
result['msg'] = f"User federation {cid} has been deleted"
module.exit_json(**result)

View file

@ -306,19 +306,19 @@ def main():
if user_rep is not None:
uid = user_rep.get('id')
else:
module.fail_json(msg='Could not fetch user for username %s:' % target_username)
module.fail_json(msg=f'Could not fetch user for username {target_username}:')
else:
if uid is None and target_username is None:
user_rep = kc.get_service_account_user_by_client_id(client_id=service_account_user_client_id, realm=realm)
if user_rep is not None:
uid = user_rep['id']
else:
module.fail_json(msg='Could not fetch service-account-user for client_id %s:' % target_username)
module.fail_json(msg=f'Could not fetch service-account-user for client_id {target_username}:')
if cid is None and client_id is not None:
cid = kc.get_client_id(client_id=client_id, realm=realm)
if cid is None:
module.fail_json(msg='Could not fetch client %s:' % client_id)
module.fail_json(msg=f'Could not fetch client {client_id}:')
if roles is None:
module.exit_json(msg="Nothing to do (no roles specified).")
else:
@ -334,7 +334,7 @@ def main():
if role_id is not None:
role['id'] = role_id
else:
module.fail_json(msg='Could not fetch role %s for client_id %s or realm %s' % (role.get('name'), client_id, realm))
module.fail_json(msg=f"Could not fetch role {role.get('name')} for client_id {client_id} or realm {realm}")
# Fetch missing role_name
else:
if cid is None:
@ -342,7 +342,7 @@ def main():
else:
role['name'] = kc.get_client_user_rolemapping_by_id(uid=uid, cid=cid, rid=role.get('id'), realm=realm)['name']
if role.get('name') is None:
module.fail_json(msg='Could not fetch role %s for client_id %s or realm %s' % (role.get('id'), client_id, realm))
module.fail_json(msg=f"Could not fetch role {role.get('id')} for client_id {client_id} or realm {realm}")
# Get effective role mappings
if cid is None:
@ -383,7 +383,7 @@ def main():
if module.check_mode:
module.exit_json(**result)
kc.add_user_rolemapping(uid=uid, cid=cid, role_rep=update_roles, realm=realm)
result['msg'] = 'Roles %s assigned to userId %s.' % (update_roles, uid)
result['msg'] = f'Roles {update_roles} assigned to userId {uid}.'
if cid is None:
assigned_roles_after = kc.get_realm_user_composite_rolemappings(uid=uid, realm=realm)
else:
@ -398,7 +398,7 @@ def main():
if module.check_mode:
module.exit_json(**result)
kc.delete_user_rolemapping(uid=uid, cid=cid, role_rep=update_roles, realm=realm)
result['msg'] = 'Roles %s removed from userId %s.' % (update_roles, uid)
result['msg'] = f'Roles {update_roles} removed from userId {uid}.'
if cid is None:
assigned_roles_after = kc.get_realm_user_composite_rolemappings(uid=uid, realm=realm)
else:
@ -408,7 +408,7 @@ def main():
# Do nothing
else:
result['changed'] = False
result['msg'] = 'Nothing to do, roles %s are correctly mapped to user for username %s.' % (roles, target_username)
result['msg'] = f'Nothing to do, roles {roles} are correctly mapped to user for username {target_username}.'
module.exit_json(**result)

View file

@ -665,14 +665,14 @@ def main():
before_realm_userprofile[param] = userprofile[param]
if changeset_copy[param] != userprofile[param] and param != 'config':
changes += "%s: %s -> %s, " % (param, userprofile[param], changeset_copy[param])
changes += f"{param}: {userprofile[param]} -> {changeset_copy[param]}, "
result['changed'] = True
# Compare parameters under the "config" userprofile
for p, v in changeset_copy['config'].items():
before_realm_userprofile['config'][p] = userprofile['config'][p]
if changeset_copy['config'][p] != userprofile['config'][p]:
changes += "config.%s: %s -> %s, " % (p, userprofile['config'][p], changeset_copy['config'][p])
changes += f"config.{p}: {userprofile['config'][p]} -> {changeset_copy['config'][p]}, "
result['changed'] = True
# Check all the possible states of the resource and do what is needed to
@ -688,12 +688,12 @@ def main():
result['diff'] = dict(before=before_realm_userprofile, after=changeset_copy)
if module.check_mode:
result['msg'] = "Userprofile %s would be changed: %s" % (provider_id, changes.strip(", "))
result['msg'] = f"Userprofile {provider_id} would be changed: {changes.strip(', ')}"
else:
kc.update_component(changeset, parent_id)
result['msg'] = "Userprofile %s changed: %s" % (provider_id, changes.strip(", "))
result['msg'] = f"Userprofile {provider_id} changed: {changes.strip(', ')}"
else:
result['msg'] = "Userprofile %s was in sync" % (provider_id)
result['msg'] = f"Userprofile {provider_id} was in sync"
result['end_state'] = changeset_copy
elif userprofile_id and state == 'absent':
@ -702,11 +702,11 @@ def main():
if module.check_mode:
result['changed'] = True
result['msg'] = "Userprofile %s would be deleted" % (provider_id)
result['msg'] = f"Userprofile {provider_id} would be deleted"
else:
kc.delete_component(userprofile_id, parent_id)
result['changed'] = True
result['msg'] = "Userprofile %s deleted" % (provider_id)
result['msg'] = f"Userprofile {provider_id} deleted"
result['end_state'] = {}
elif not userprofile_id and state == 'present':
@ -715,16 +715,16 @@ def main():
if module.check_mode:
result['changed'] = True
result['msg'] = "Userprofile %s would be created" % (provider_id)
result['msg'] = f"Userprofile {provider_id} would be created"
else:
kc.create_component(changeset, parent_id)
result['changed'] = True
result['msg'] = "Userprofile %s created" % (provider_id)
result['msg'] = f"Userprofile {provider_id} created"
result['end_state'] = changeset_copy
elif not userprofile_id and state == 'absent':
result['changed'] = False
result['msg'] = "Userprofile %s not present" % (provider_id)
result['msg'] = f"Userprofile {provider_id} not present"
result['end_state'] = {}
module.exit_json(**result)

View file

@ -105,12 +105,8 @@ def del_passphrase(module):
return None
except keyring.errors.KeyringLocked:
delete_argument = (
'echo "%s" | gnome-keyring-daemon --unlock\nkeyring del %s %s\n'
% (
quote(module.params["keyring_password"]),
quote(module.params["service"]),
quote(module.params["username"]),
)
f'echo "{quote(module.params["keyring_password"])}" | gnome-keyring-daemon --unlock\n'
f'keyring del {quote(module.params["service"])} {quote(module.params["username"])}\n'
)
dummy, dummy, stderr = module.run_command(
"dbus-run-session -- /bin/bash",
@ -139,13 +135,8 @@ def set_passphrase(module):
return None
except keyring.errors.KeyringLocked:
set_argument = (
'echo "%s" | gnome-keyring-daemon --unlock\nkeyring set %s %s\n%s\n'
% (
quote(module.params["keyring_password"]),
quote(module.params["service"]),
quote(module.params["username"]),
quote(module.params["user_password"]),
)
f'echo "{quote(module.params["keyring_password"])}" | gnome-keyring-daemon --unlock\n'
f'keyring set {quote(module.params["service"])} {quote(module.params["username"])}\n{quote(module.params["user_password"])}\n'
)
dummy, dummy, stderr = module.run_command(
"dbus-run-session -- /bin/bash",
@ -173,10 +164,9 @@ def get_passphrase(module):
pass
except AttributeError:
pass
get_argument = 'echo "%s" | gnome-keyring-daemon --unlock\nkeyring get %s %s\n' % (
quote(module.params["keyring_password"]),
quote(module.params["service"]),
quote(module.params["username"]),
get_argument = (
f'echo "{quote(module.params["keyring_password"])}" | gnome-keyring-daemon --unlock\n'
f'keyring get {quote(module.params["service"])} {quote(module.params["username"])}\n'
)
dummy, stdout, dummy = module.run_command(
"dbus-run-session -- /bin/bash",
@ -220,45 +210,30 @@ def run_module():
if module.params["state"] == "present":
if passphrase is not None:
if passphrase == module.params["user_password"]:
result["msg"] = "Passphrase already set for %s@%s" % (
module.params["service"],
module.params["username"],
)
result["msg"] = f"Passphrase already set for {module.params['service']}@{module.params['username']}"
if passphrase != module.params["user_password"]:
set_result = set_passphrase(module)
if set_result is None:
result["changed"] = True
result["msg"] = "Passphrase has been updated for %s@%s" % (
module.params["service"],
module.params["username"],
)
result["msg"] = f"Passphrase has been updated for {module.params['service']}@{module.params['username']}"
if set_result is not None:
module.fail_json(msg=set_result)
if passphrase is None:
set_result = set_passphrase(module)
if set_result is None:
result["changed"] = True
result["msg"] = "Passphrase has been updated for %s@%s" % (
module.params["service"],
module.params["username"],
)
result["msg"] = f"Passphrase has been updated for {module.params['service']}@{module.params['username']}"
if set_result is not None:
module.fail_json(msg=set_result)
if module.params["state"] == "absent":
if not passphrase:
result["result"] = "Passphrase already absent for %s@%s" % (
module.params["service"],
module.params["username"],
)
result["result"] = f"Passphrase already absent for {module.params['service']}@{module.params['username']}"
if passphrase:
del_result = del_passphrase(module)
if del_result is None:
result["changed"] = True
result["msg"] = "Passphrase has been removed for %s@%s" % (
module.params["service"],
module.params["username"],
)
result["msg"] = f"Passphrase has been removed for {module.params['service']}@{module.params['username']}"
if del_result is not None:
module.fail_json(msg=del_result)

View file

@ -81,10 +81,9 @@ except ImportError:
def _alternate_retrieval_method(module):
get_argument = 'echo "%s" | gnome-keyring-daemon --unlock\nkeyring get %s %s\n' % (
quote(module.params["keyring_password"]),
quote(module.params["service"]),
quote(module.params["username"]),
get_argument = (
f'echo "{quote(module.params["keyring_password"])}" | gnome-keyring-daemon --unlock\n'
f'keyring get {quote(module.params["service"])} {quote(module.params["username"])}\n'
)
dummy, stdout, dummy = module.run_command(
"dbus-run-session -- /bin/bash",
@ -129,16 +128,10 @@ def run_module():
passphrase = _alternate_retrieval_method(module)
if passphrase is not None:
result["msg"] = "Successfully retrieved password for %s@%s" % (
module.params["service"],
module.params["username"],
)
result["msg"] = f"Successfully retrieved password for {module.params['service']}@{module.params['username']}"
result["passphrase"] = passphrase
if passphrase is None:
result["msg"] = "Password for %s@%s does not exist." % (
module.params["service"],
module.params["username"],
)
result["msg"] = f"Password for {module.params['service']}@{module.params['username']} does not exist."
module.exit_json(**result)

View file

@ -216,7 +216,7 @@ def get_kibana_version(module, plugin_bin, allow_root):
rc, out, err = module.run_command(cmd_args)
if rc != 0:
module.fail_json(msg="Failed to get Kibana version : %s" % err)
module.fail_json(msg=f"Failed to get Kibana version : {err}")
return out.strip()
@ -258,7 +258,7 @@ def main():
module.exit_json(changed=False, name=name, state=state)
if version:
name = name + '/' + version
name = f"{name}/{version}"
if state == "present":
if force: