Reformat everything.

This commit is contained in:
Felix Fontein
2025-11-01 12:08:41 +01:00
parent 3f2213791a
commit 340ff8586d
1008 changed files with 61301 additions and 58309 deletions

View File

@@ -221,8 +221,13 @@ end_state:
}
"""
from ansible_collections.community.general.plugins.module_utils.identity.keycloak.keycloak import KeycloakAPI, camel, \
keycloak_argument_spec, get_token, KeycloakError
from ansible_collections.community.general.plugins.module_utils.identity.keycloak.keycloak import (
KeycloakAPI,
camel,
keycloak_argument_spec,
get_token,
KeycloakError,
)
from ansible.module_utils.basic import AnsibleModule
from urllib.parse import urlencode
from copy import deepcopy
@@ -237,17 +242,17 @@ def main():
argument_spec = keycloak_argument_spec()
meta_args = dict(
state=dict(type='str', default='present', choices=['present', 'absent']),
name=dict(type='str', required=True),
force=dict(type='bool', default=False),
parent_id=dict(type='str', required=True),
provider_id=dict(type='str', default='rsa', choices=['rsa', 'rsa-enc']),
state=dict(type="str", default="present", choices=["present", "absent"]),
name=dict(type="str", required=True),
force=dict(type="bool", default=False),
parent_id=dict(type="str", required=True),
provider_id=dict(type="str", default="rsa", choices=["rsa", "rsa-enc"]),
config=dict(
type='dict',
type="dict",
options=dict(
active=dict(type='bool', default=True),
enabled=dict(type='bool', default=True),
priority=dict(type='int', required=True),
active=dict(type="bool", default=True),
enabled=dict(type="bool", default=True),
priority=dict(type="int", required=True),
algorithm=dict(
type="str",
default="RS256",
@@ -263,29 +268,32 @@ def main():
"RSA-OAEP-256",
],
),
private_key=dict(type='str', required=True, no_log=True),
certificate=dict(type='str', required=True)
)
)
private_key=dict(type="str", required=True, no_log=True),
certificate=dict(type="str", required=True),
),
),
)
argument_spec.update(meta_args)
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True,
required_one_of=([['token', 'auth_realm', 'auth_username', 'auth_password', 'auth_client_id', 'auth_client_secret']]),
required_together=([['auth_username', 'auth_password']]),
required_by={'refresh_token': 'auth_realm'},
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
required_one_of=(
[["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"]]
),
required_together=([["auth_username", "auth_password"]]),
required_by={"refresh_token": "auth_realm"},
)
# Initialize the result object. Only "changed" seems to have special
# meaning for Ansible.
result = dict(changed=False, msg='', end_state={}, diff=dict(before={}, after={}))
result = dict(changed=False, msg="", end_state={}, diff=dict(before={}, after={}))
# This will include the current state of the realm key if it is already
# present. This is only used for diff-mode.
before_realm_key = {}
before_realm_key['config'] = {}
before_realm_key["config"] = {}
# Obtain access token, initialize API
try:
@@ -298,16 +306,14 @@ def main():
params_to_ignore = list(keycloak_argument_spec().keys()) + ["state", "force", "parent_id"]
# Filter and map the parameters names that apply to the role
component_params = [x for x in module.params
if x not in params_to_ignore and
module.params.get(x) is not None]
component_params = [x for x in module.params if x not in params_to_ignore and module.params.get(x) is not None]
# We only support one component provider type in this module
provider_type = 'org.keycloak.keys.KeyProvider'
provider_type = "org.keycloak.keys.KeyProvider"
# Build a proposed changeset from parameters given to this module
changeset = {}
changeset['config'] = {}
changeset["config"] = {}
# Generate a JSON payload for Keycloak Admin API from the module
# parameters. Parameters that do not belong to the JSON payload (e.g.
@@ -323,16 +329,16 @@ def main():
# by Keycloak.
#
for component_param in component_params:
if component_param == 'config':
for config_param in module.params.get('config'):
changeset['config'][camel(config_param)] = []
raw_value = module.params.get('config')[config_param]
if component_param == "config":
for config_param in module.params.get("config"):
changeset["config"][camel(config_param)] = []
raw_value = module.params.get("config")[config_param]
if isinstance(raw_value, bool):
value = str(raw_value).lower()
else:
value = str(raw_value)
changeset['config'][camel(config_param)].append(value)
changeset["config"][camel(config_param)].append(value)
else:
# No need for camelcase in here as these are one word parameters
new_param_value = module.params.get(component_param)
@@ -340,7 +346,7 @@ def main():
# As provider_type is not a module parameter we have to add it to the
# changeset explicitly.
changeset['providerType'] = provider_type
changeset["providerType"] = provider_type
# Make a deep copy of the changeset. This is use when determining
# changes to the current state.
@@ -354,16 +360,16 @@ def main():
# parameter needs be present in the JSON payload, any changes done to any
# other parameters (e.g. config.priority) will trigger update of the keys
# as a side-effect.
del changeset_copy['config']['privateKey']
del changeset_copy['config']['certificate']
del changeset_copy["config"]["privateKey"]
del changeset_copy["config"]["certificate"]
# Make it easier to refer to current module parameters
name = module.params.get('name')
force = module.params.get('force')
state = module.params.get('state')
enabled = module.params.get('enabled')
provider_id = module.params.get('provider_id')
parent_id = module.params.get('parent_id')
name = module.params.get("name")
force = module.params.get("force")
state = module.params.get("state")
enabled = module.params.get("enabled")
provider_id = module.params.get("provider_id")
parent_id = module.params.get("parent_id")
# Get a list of all Keycloak components that are of keyprovider type.
realm_keys = kc.get_components(urlencode(dict(type=provider_type)), parent_id)
@@ -376,95 +382,95 @@ def main():
changes = ""
# This tells Ansible whether the key was changed (added, removed, modified)
result['changed'] = False
result["changed"] = False
# Loop through the list of components. If we encounter a component whose
# name matches the value of the name parameter then assume the key is
# already present.
for key in realm_keys:
if key['name'] == name:
key_id = key['id']
changeset['id'] = key_id
changeset_copy['id'] = key_id
if key["name"] == name:
key_id = key["id"]
changeset["id"] = key_id
changeset_copy["id"] = key_id
# Compare top-level parameters
for param, value in changeset.items():
before_realm_key[param] = key[param]
if changeset_copy[param] != key[param] and param != 'config':
if changeset_copy[param] != key[param] and param != "config":
changes += f"{param}: {key[param]} -> {changeset_copy[param]}, "
result['changed'] = True
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]:
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 += f"config.{p}: {key['config'][p]} -> {changeset_copy['config'][p]}, "
result['changed'] = True
result["changed"] = True
# Sanitize linefeeds for the privateKey. Without this the JSON payload
# will be invalid.
changeset['config']['privateKey'][0] = changeset['config']['privateKey'][0].replace('\\n', '\n')
changeset['config']['certificate'][0] = changeset['config']['certificate'][0].replace('\\n', '\n')
changeset["config"]["privateKey"][0] = changeset["config"]["privateKey"][0].replace("\\n", "\n")
changeset["config"]["certificate"][0] = changeset["config"]["certificate"][0].replace("\\n", "\n")
# Check all the possible states of the resource and do what is needed to
# converge current state with desired state (create, update or delete
# the key).
if key_id and state == 'present':
if result['changed']:
if key_id and state == "present":
if result["changed"]:
if module._diff:
del before_realm_key['config']['privateKey']
del before_realm_key['config']['certificate']
result['diff'] = dict(before=before_realm_key, after=changeset_copy)
del before_realm_key["config"]["privateKey"]
del before_realm_key["config"]["certificate"]
result["diff"] = dict(before=before_realm_key, after=changeset_copy)
if module.check_mode:
result['msg'] = f"Realm key {name} would be changed: {changes.strip(', ')}"
result["msg"] = f"Realm key {name} would be changed: {changes.strip(', ')}"
else:
kc.update_component(changeset, parent_id)
result['msg'] = f"Realm key {name} changed: {changes.strip(', ')}"
elif not result['changed'] and force:
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'] = f"Realm key {name} was forcibly updated"
result["changed"] = True
result["msg"] = f"Realm key {name} was forcibly updated"
else:
result['msg'] = f"Realm key {name} was in sync"
result["msg"] = f"Realm key {name} was in sync"
result['end_state'] = changeset_copy
elif key_id and state == 'absent':
result["end_state"] = changeset_copy
elif key_id and state == "absent":
if module._diff:
del before_realm_key['config']['privateKey']
del before_realm_key['config']['certificate']
result['diff'] = dict(before=before_realm_key, after={})
del before_realm_key["config"]["privateKey"]
del before_realm_key["config"]["certificate"]
result["diff"] = dict(before=before_realm_key, after={})
if module.check_mode:
result['changed'] = True
result['msg'] = f"Realm key {name} would be deleted"
result["changed"] = True
result["msg"] = f"Realm key {name} would be deleted"
else:
kc.delete_component(key_id, parent_id)
result['changed'] = True
result['msg'] = f"Realm key {name} deleted"
result["changed"] = True
result["msg"] = f"Realm key {name} deleted"
result['end_state'] = {}
elif not key_id and state == 'present':
result["end_state"] = {}
elif not key_id and state == "present":
if module._diff:
result['diff'] = dict(before={}, after=changeset_copy)
result["diff"] = dict(before={}, after=changeset_copy)
if module.check_mode:
result['changed'] = True
result['msg'] = f"Realm key {name} would be created"
result["changed"] = True
result["msg"] = f"Realm key {name} would be created"
else:
kc.create_component(changeset, parent_id)
result['changed'] = True
result['msg'] = f"Realm key {name} created"
result["changed"] = True
result["msg"] = f"Realm key {name} created"
result['end_state'] = changeset_copy
elif not key_id and state == 'absent':
result['changed'] = False
result['msg'] = f"Realm key {name} not present"
result['end_state'] = {}
result["end_state"] = changeset_copy
elif not key_id and state == "absent":
result["changed"] = False
result["msg"] = f"Realm key {name} not present"
result["end_state"] = {}
module.exit_json(**result)
if __name__ == '__main__':
if __name__ == "__main__":
main()