| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2024, Björn Bösel <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or |
| 5 |
# https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: keycloak_component |
| 11 |
|
| 12 |
short_description: Allows administration of Keycloak components using Keycloak API |
| 13 |
|
| 14 |
version_added: 10.0.0 |
| 15 |
|
| 16 |
description: |
| 17 |
- This module allows the administration of Keycloak components using the Keycloak REST API. It requires access to the REST |
| 18 |
API using OpenID Connect; the user connecting and the realm being used must have the requisite access rights. In a default |
| 19 |
Keycloak installation, C(admin-cli) and an C(admin) user would work, as would a separate realm definition with the scope |
| 20 |
tailored to your needs and a user having the expected roles. |
| 21 |
- The names of module options are snake_cased versions of the camelCase ones found in the Keycloak API and its documentation |
| 22 |
at U(https://www.keycloak.org/docs-api/latest/rest-api/index.html). Aliases are provided so camelCased versions can be |
| 23 |
used as well. |
| 24 |
attributes: |
| 25 |
check_mode: |
| 26 |
support: full |
| 27 |
diff_mode: |
| 28 |
support: full |
| 29 |
action_group: |
| 30 |
version_added: 10.2.0 |
| 31 |
|
| 32 |
options: |
| 33 |
state: |
| 34 |
description: |
| 35 |
- State of the Keycloak component. |
| 36 |
- On V(present), the component is created (or updated if it exists already). |
| 37 |
- On V(absent), the component is removed if it exists. |
| 38 |
choices: ['present', 'absent'] |
| 39 |
default: 'present' |
| 40 |
type: str |
| 41 |
name: |
| 42 |
description: |
| 43 |
- Name of the component to create. |
| 44 |
type: str |
| 45 |
required: true |
| 46 |
parent_id: |
| 47 |
description: |
| 48 |
- The parent_id of the component. In practice the ID (name) of the realm. |
| 49 |
type: str |
| 50 |
required: true |
| 51 |
provider_id: |
| 52 |
description: |
| 53 |
- The name of the "provider ID" for the key. |
| 54 |
type: str |
| 55 |
required: true |
| 56 |
provider_type: |
| 57 |
description: |
| 58 |
- The name of the "provider type" for the key. That is, V(org.keycloak.storage.UserStorageProvider), V(org.keycloak.userprofile.UserProfileProvider), |
| 59 |
... |
| 60 |
- See U(https://www.keycloak.org/docs/latest/server_development/index.html#_providers). |
| 61 |
type: str |
| 62 |
required: true |
| 63 |
config: |
| 64 |
description: |
| 65 |
- Configuration properties for the provider. |
| 66 |
- Contents vary depending on the provider type. |
| 67 |
type: dict |
| 68 |
|
| 69 |
extends_documentation_fragment: |
| 70 |
- community.general._keycloak |
| 71 |
- community.general._keycloak.actiongroup_keycloak |
| 72 |
- community.general._attributes |
| 73 |
|
| 74 |
author: |
| 75 |
- Björn Bösel (@fivetide) |
| 76 |
""" |
| 77 |
|
| 78 |
EXAMPLES = r""" |
| 79 |
- name: Manage Keycloak User Storage Provider |
| 80 |
community.general.keycloak_component: |
| 81 |
auth_keycloak_url: http://localhost:8080/auth |
| 82 |
auth_username: keycloak |
| 83 |
auth_password: keycloak |
| 84 |
auth_realm: master |
| 85 |
name: my storage provider |
| 86 |
state: present |
| 87 |
parent_id: some_realm |
| 88 |
provider_id: my storage |
| 89 |
provider_type: "org.keycloak.storage.UserStorageProvider" |
| 90 |
config: |
| 91 |
myCustomKey: "my_custom_key" |
| 92 |
cachePolicy: "NO_CACHE" |
| 93 |
enabled: true |
| 94 |
""" |
| 95 |
|
| 96 |
RETURN = r""" |
| 97 |
end_state: |
| 98 |
description: Representation of the keycloak_component after module execution. |
| 99 |
returned: on success |
| 100 |
type: dict |
| 101 |
contains: |
| 102 |
id: |
| 103 |
description: ID of the component. |
| 104 |
type: str |
| 105 |
returned: when O(state=present) |
| 106 |
sample: 5b7ec13f-99da-46ad-8326-ab4c73cf4ce4 |
| 107 |
name: |
| 108 |
description: Name of the component. |
| 109 |
type: str |
| 110 |
returned: when O(state=present) |
| 111 |
sample: mykey |
| 112 |
parentId: |
| 113 |
description: ID of the realm this key belongs to. |
| 114 |
type: str |
| 115 |
returned: when O(state=present) |
| 116 |
sample: myrealm |
| 117 |
providerId: |
| 118 |
description: The ID of the key provider. |
| 119 |
type: str |
| 120 |
returned: when O(state=present) |
| 121 |
sample: rsa |
| 122 |
providerType: |
| 123 |
description: The type of provider. |
| 124 |
type: str |
| 125 |
returned: when O(state=present) |
| 126 |
config: |
| 127 |
description: Component configuration. |
| 128 |
type: dict |
| 129 |
""" |
| 130 |
|
| 131 |
from copy import deepcopy |
| 132 |
from urllib.parse import urlencode |
| 133 |
|
| 134 |
from ansible.module_utils.basic import AnsibleModule |
| 135 |
|
| 136 |
from ansible_collections.community.general.plugins.module_utils._keycloak import ( |
| 137 |
KeycloakAPI, |
| 138 |
KeycloakError, |
| 139 |
camel, |
| 140 |
get_token, |
| 141 |
keycloak_argument_spec, |
| 142 |
) |
| 143 |
|
| 144 |
|
| 145 |
def main(): |
| 146 |
argument_spec = keycloak_argument_spec() |
| 147 |
|
| 148 |
meta_args = dict( |
| 149 |
state=dict(type="str", default="present", choices=["present", "absent"]), |
| 150 |
name=dict(type="str", required=True), |
| 151 |
parent_id=dict(type="str", required=True), |
| 152 |
provider_id=dict(type="str", required=True), |
| 153 |
provider_type=dict(type="str", required=True), |
| 154 |
config=dict( |
| 155 |
type="dict", |
| 156 |
), |
| 157 |
) |
| 158 |
|
| 159 |
argument_spec.update(meta_args) |
| 160 |
|
| 161 |
module = AnsibleModule( |
| 162 |
argument_spec=argument_spec, |
| 163 |
supports_check_mode=True, |
| 164 |
required_one_of=( |
| 165 |
[["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"]] |
| 166 |
), |
| 167 |
required_together=([["auth_username", "auth_password"]]), |
| 168 |
required_by={"refresh_token": "auth_realm"}, |
| 169 |
) |
| 170 |
|
| 171 |
result = dict(changed=False, msg="", end_state={}, diff=dict(before={}, after={})) |
| 172 |
|
| 173 |
# This will include the current state of the component if it is already |
| 174 |
# present. This is only used for diff-mode. |
| 175 |
before_component = {} |
| 176 |
before_component["config"] = {} |
| 177 |
|
| 178 |
# Obtain access token, initialize API |
| 179 |
try: |
| 180 |
connection_header = get_token(module.params) |
| 181 |
except KeycloakError as e: |
| 182 |
module.fail_json(msg=str(e)) |
| 183 |
|
| 184 |
kc = KeycloakAPI(module, connection_header) |
| 185 |
|
| 186 |
params_to_ignore = list(keycloak_argument_spec().keys()) + ["state", "parent_id"] |
| 187 |
|
| 188 |
# Filter and map the parameters names that apply to the role |
| 189 |
component_params = [x for x in module.params if x not in params_to_ignore and module.params.get(x) is not None] |
| 190 |
|
| 191 |
provider_type = module.params.get("provider_type") |
| 192 |
|
| 193 |
# Build a proposed changeset from parameters given to this module |
| 194 |
changeset = {} |
| 195 |
changeset["config"] = {} |
| 196 |
|
| 197 |
# Generate a JSON payload for Keycloak Admin API from the module |
| 198 |
# parameters. Parameters that do not belong to the JSON payload (e.g. |
| 199 |
# "state" or "auth_keycloal_url") have been filtered away earlier (see |
| 200 |
# above). |
| 201 |
# |
| 202 |
# This loop converts Ansible module parameters (snake-case) into |
| 203 |
# Keycloak-compatible format (camel-case). For example private_key |
| 204 |
# becomes privateKey. |
| 205 |
# |
| 206 |
# It also converts bool, str and int parameters into lists with a single |
| 207 |
# entry of 'str' type. Bool values are also lowercased. This is required |
| 208 |
# by Keycloak. |
| 209 |
# |
| 210 |
for component_param in component_params: |
| 211 |
if component_param == "config": |
| 212 |
for config_param in module.params.get("config"): |
| 213 |
changeset["config"][camel(config_param)] = [] |
| 214 |
raw_value = module.params.get("config")[config_param] |
| 215 |
if isinstance(raw_value, bool): |
| 216 |
value = str(raw_value).lower() |
| 217 |
else: |
| 218 |
value = str(raw_value) |
| 219 |
|
| 220 |
changeset["config"][camel(config_param)].append(value) |
| 221 |
else: |
| 222 |
# No need for camelcase in here as these are one word parameters |
| 223 |
new_param_value = module.params.get(component_param) |
| 224 |
changeset[camel(component_param)] = new_param_value |
| 225 |
|
| 226 |
# Make a deep copy of the changeset. This is use when determining |
| 227 |
# changes to the current state. |
| 228 |
changeset_copy = deepcopy(changeset) |
| 229 |
|
| 230 |
# Make it easier to refer to current module parameters |
| 231 |
name = module.params.get("name") |
| 232 |
state = module.params.get("state") |
| 233 |
provider_type = module.params.get("provider_type") |
| 234 |
parent_id = module.params.get("parent_id") |
| 235 |
|
| 236 |
# Get a list of all Keycloak components that are of keyprovider type. |
| 237 |
current_components = kc.get_components(urlencode(dict(type=provider_type)), parent_id) |
| 238 |
|
| 239 |
# If this component is present get its key ID. Confusingly the key ID is |
| 240 |
# also known as the Provider ID. |
| 241 |
component_id = None |
| 242 |
|
| 243 |
# Track individual parameter changes |
| 244 |
changes = "" |
| 245 |
|
| 246 |
# This tells Ansible whether the key was changed (added, removed, modified) |
| 247 |
result["changed"] = False |
| 248 |
|
| 249 |
# Loop through the list of components. If we encounter a component whose |
| 250 |
# name matches the value of the name parameter then assume the key is |
| 251 |
# already present. |
| 252 |
for component in current_components: |
| 253 |
if component["name"] == name: |
| 254 |
component_id = component["id"] |
| 255 |
changeset["id"] = component_id |
| 256 |
changeset_copy["id"] = component_id |
| 257 |
|
| 258 |
# Compare top-level parameters |
| 259 |
for param in changeset: |
| 260 |
before_component[param] = component[param] |
| 261 |
|
| 262 |
if changeset_copy[param] != component[param] and param != "config": |
| 263 |
changes += f"{param}: {component[param]} -> {changeset_copy[param]}, " |
| 264 |
result["changed"] = True |
| 265 |
# Compare parameters under the "config" key |
| 266 |
for p, v in changeset_copy["config"].items(): |
| 267 |
try: |
| 268 |
before_component["config"][p] = component["config"][p] or [] |
| 269 |
except KeyError: |
| 270 |
before_component["config"][p] = [] |
| 271 |
if v != component["config"][p]: |
| 272 |
changes += f"config.{p}: {component['config'][p]} -> {v}, " |
| 273 |
result["changed"] = True |
| 274 |
|
| 275 |
# Check all the possible states of the resource and do what is needed to |
| 276 |
# converge current state with desired state (create, update or delete |
| 277 |
# the key). |
| 278 |
if component_id and state == "present": |
| 279 |
if result["changed"]: |
| 280 |
if module._diff: |
| 281 |
result["diff"] = dict(before=before_component, after=changeset_copy) |
| 282 |
|
| 283 |
if module.check_mode: |
| 284 |
result["msg"] = f"Component {name} would be changed: {changes.strip(', ')}" |
| 285 |
else: |
| 286 |
kc.update_component(changeset, parent_id) |
| 287 |
result["msg"] = f"Component {name} changed: {changes.strip(', ')}" |
| 288 |
else: |
| 289 |
result["msg"] = f"Component {name} was in sync" |
| 290 |
|
| 291 |
result["end_state"] = changeset_copy |
| 292 |
elif component_id and state == "absent": |
| 293 |
if module._diff: |
| 294 |
result["diff"] = dict(before=before_component, after={}) |
| 295 |
|
| 296 |
if module.check_mode: |
| 297 |
result["changed"] = True |
| 298 |
result["msg"] = f"Component {name} would be deleted" |
| 299 |
else: |
| 300 |
kc.delete_component(component_id, parent_id) |
| 301 |
result["changed"] = True |
| 302 |
result["msg"] = f"Component {name} deleted" |
| 303 |
|
| 304 |
result["end_state"] = {} |
| 305 |
elif not component_id and state == "present": |
| 306 |
if module._diff: |
| 307 |
result["diff"] = dict(before={}, after=changeset_copy) |
| 308 |
|
| 309 |
if module.check_mode: |
| 310 |
result["changed"] = True |
| 311 |
result["msg"] = f"Component {name} would be created" |
| 312 |
else: |
| 313 |
kc.create_component(changeset, parent_id) |
| 314 |
result["changed"] = True |
| 315 |
result["msg"] = f"Component {name} created" |
| 316 |
|
| 317 |
result["end_state"] = changeset_copy |
| 318 |
elif not component_id and state == "absent": |
| 319 |
result["changed"] = False |
| 320 |
result["msg"] = f"Component {name} not present" |
| 321 |
result["end_state"] = {} |
| 322 |
|
| 323 |
module.exit_json(**result) |
| 324 |
|
| 325 |
|
| 326 |
if __name__ == "__main__": |
| 327 |
main() |