| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2019, Adam Goossens <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: keycloak_role |
| 11 |
|
| 12 |
short_description: Allows administration of Keycloak roles using Keycloak API |
| 13 |
|
| 14 |
version_added: 3.4.0 |
| 15 |
|
| 16 |
description: |
| 17 |
- This module allows you to add, remove or modify Keycloak roles using the Keycloak REST API. It requires access to the |
| 18 |
REST API using OpenID Connect; the user connecting and the client being used must have the requisite access rights. In |
| 19 |
a default Keycloak installation, admin-cli and an admin user would work, as would a separate client definition with the |
| 20 |
scope 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/8.0/rest-api/index.html). |
| 23 |
- Attributes are multi-valued in the Keycloak API. All attributes are lists of individual values and are returned that way |
| 24 |
by this module. You may pass single values for attributes when calling the module, and this is translated into a list |
| 25 |
suitable for the API. |
| 26 |
attributes: |
| 27 |
check_mode: |
| 28 |
support: full |
| 29 |
diff_mode: |
| 30 |
support: full |
| 31 |
action_group: |
| 32 |
version_added: 10.2.0 |
| 33 |
|
| 34 |
options: |
| 35 |
state: |
| 36 |
description: |
| 37 |
- State of the role. |
| 38 |
- On V(present), the role is created if it does not yet exist, or updated with the parameters you provide. |
| 39 |
- On V(absent), the role is removed if it exists. |
| 40 |
default: 'present' |
| 41 |
type: str |
| 42 |
choices: |
| 43 |
- present |
| 44 |
- absent |
| 45 |
|
| 46 |
name: |
| 47 |
type: str |
| 48 |
required: true |
| 49 |
description: |
| 50 |
- Name of the role. |
| 51 |
- This parameter is required. |
| 52 |
description: |
| 53 |
type: str |
| 54 |
description: |
| 55 |
- The role description. |
| 56 |
realm: |
| 57 |
type: str |
| 58 |
description: |
| 59 |
- The Keycloak realm under which this role resides. |
| 60 |
default: 'master' |
| 61 |
|
| 62 |
client_id: |
| 63 |
type: str |
| 64 |
description: |
| 65 |
- If the role is a client role, the client ID under which it resides. |
| 66 |
- If this parameter is absent, the role is considered a realm role. |
| 67 |
attributes: |
| 68 |
type: dict |
| 69 |
description: |
| 70 |
- A dict of key/value pairs to set as custom attributes for the role. |
| 71 |
- Values may be single values (for example a string) or a list of strings. |
| 72 |
composite: |
| 73 |
description: |
| 74 |
- If V(true), the role is a composition of other realm and/or client role. |
| 75 |
default: false |
| 76 |
type: bool |
| 77 |
version_added: 7.1.0 |
| 78 |
composites: |
| 79 |
description: |
| 80 |
- List of roles to include to the composite realm role. |
| 81 |
- If the composite role is a client role, the C(clientId) (not ID of the client) must be specified. |
| 82 |
default: [] |
| 83 |
type: list |
| 84 |
elements: dict |
| 85 |
version_added: 7.1.0 |
| 86 |
suboptions: |
| 87 |
name: |
| 88 |
description: |
| 89 |
- Name of the role. This can be the name of a REALM role or a client role. |
| 90 |
type: str |
| 91 |
required: true |
| 92 |
client_id: |
| 93 |
description: |
| 94 |
- Client ID if the role is a client role. Do not include this option for a REALM role. |
| 95 |
- Use the client ID you can see in the Keycloak console, not the technical ID of the client. |
| 96 |
type: str |
| 97 |
aliases: |
| 98 |
- clientId |
| 99 |
state: |
| 100 |
description: |
| 101 |
- Create the composite if present, remove it if absent. |
| 102 |
type: str |
| 103 |
choices: |
| 104 |
- present |
| 105 |
- absent |
| 106 |
default: present |
| 107 |
|
| 108 |
extends_documentation_fragment: |
| 109 |
- community.general._keycloak |
| 110 |
- community.general._keycloak.actiongroup_keycloak |
| 111 |
- community.general._attributes |
| 112 |
|
| 113 |
author: |
| 114 |
- Laurent Paumier (@laurpaum) |
| 115 |
""" |
| 116 |
|
| 117 |
EXAMPLES = r""" |
| 118 |
- name: Create a Keycloak realm role, authentication with credentials |
| 119 |
community.general.keycloak_role: |
| 120 |
name: my-new-kc-role |
| 121 |
realm: MyCustomRealm |
| 122 |
state: present |
| 123 |
auth_client_id: admin-cli |
| 124 |
auth_keycloak_url: https://auth.example.com/auth |
| 125 |
auth_realm: master |
| 126 |
auth_username: USERNAME |
| 127 |
auth_password: PASSWORD |
| 128 |
delegate_to: localhost |
| 129 |
|
| 130 |
- name: Create a Keycloak realm role, authentication with token |
| 131 |
community.general.keycloak_role: |
| 132 |
name: my-new-kc-role |
| 133 |
realm: MyCustomRealm |
| 134 |
state: present |
| 135 |
auth_client_id: admin-cli |
| 136 |
auth_keycloak_url: https://auth.example.com/auth |
| 137 |
token: TOKEN |
| 138 |
delegate_to: localhost |
| 139 |
|
| 140 |
- name: Create a Keycloak client role |
| 141 |
community.general.keycloak_role: |
| 142 |
name: my-new-kc-role |
| 143 |
realm: MyCustomRealm |
| 144 |
client_id: MyClient |
| 145 |
state: present |
| 146 |
auth_client_id: admin-cli |
| 147 |
auth_keycloak_url: https://auth.example.com/auth |
| 148 |
auth_realm: master |
| 149 |
auth_username: USERNAME |
| 150 |
auth_password: PASSWORD |
| 151 |
delegate_to: localhost |
| 152 |
|
| 153 |
- name: Delete a Keycloak role |
| 154 |
community.general.keycloak_role: |
| 155 |
name: my-role-for-deletion |
| 156 |
state: absent |
| 157 |
auth_client_id: admin-cli |
| 158 |
auth_keycloak_url: https://auth.example.com/auth |
| 159 |
auth_realm: master |
| 160 |
auth_username: USERNAME |
| 161 |
auth_password: PASSWORD |
| 162 |
delegate_to: localhost |
| 163 |
|
| 164 |
- name: Create a keycloak role with some custom attributes |
| 165 |
community.general.keycloak_role: |
| 166 |
auth_client_id: admin-cli |
| 167 |
auth_keycloak_url: https://auth.example.com/auth |
| 168 |
auth_realm: master |
| 169 |
auth_username: USERNAME |
| 170 |
auth_password: PASSWORD |
| 171 |
name: my-new-role |
| 172 |
attributes: |
| 173 |
attrib1: value1 |
| 174 |
attrib2: value2 |
| 175 |
attrib3: |
| 176 |
- with |
| 177 |
- numerous |
| 178 |
- individual |
| 179 |
- list |
| 180 |
- items |
| 181 |
delegate_to: localhost |
| 182 |
""" |
| 183 |
|
| 184 |
RETURN = r""" |
| 185 |
msg: |
| 186 |
description: Message as to what action was taken. |
| 187 |
returned: always |
| 188 |
type: str |
| 189 |
sample: "Role myrole has been updated" |
| 190 |
|
| 191 |
proposed: |
| 192 |
description: Representation of proposed role. |
| 193 |
returned: always |
| 194 |
type: dict |
| 195 |
sample: {"description": "My updated test description"} |
| 196 |
|
| 197 |
existing: |
| 198 |
description: Representation of existing role. |
| 199 |
returned: always |
| 200 |
type: dict |
| 201 |
sample: |
| 202 |
{ |
| 203 |
"attributes": {}, |
| 204 |
"clientRole": true, |
| 205 |
"composite": false, |
| 206 |
"containerId": "9f03eb61-a826-4771-a9fd-930e06d2d36a", |
| 207 |
"description": "My client test role", |
| 208 |
"id": "561703dd-0f38-45ff-9a5a-0c978f794547", |
| 209 |
"name": "myrole" |
| 210 |
} |
| 211 |
|
| 212 |
end_state: |
| 213 |
description: Representation of role after module execution (sample is truncated). |
| 214 |
returned: on success |
| 215 |
type: dict |
| 216 |
sample: |
| 217 |
{ |
| 218 |
"attributes": {}, |
| 219 |
"clientRole": true, |
| 220 |
"composite": false, |
| 221 |
"containerId": "9f03eb61-a826-4771-a9fd-930e06d2d36a", |
| 222 |
"description": "My updated client test role", |
| 223 |
"id": "561703dd-0f38-45ff-9a5a-0c978f794547", |
| 224 |
"name": "myrole" |
| 225 |
} |
| 226 |
""" |
| 227 |
|
| 228 |
import copy |
| 229 |
|
| 230 |
from ansible.module_utils.basic import AnsibleModule |
| 231 |
|
| 232 |
from ansible_collections.community.general.plugins.module_utils._keycloak import ( |
| 233 |
KeycloakAPI, |
| 234 |
KeycloakError, |
| 235 |
camel, |
| 236 |
get_token, |
| 237 |
is_struct_included, |
| 238 |
keycloak_argument_spec, |
| 239 |
) |
| 240 |
|
| 241 |
|
| 242 |
def main(): |
| 243 |
""" |
| 244 |
Module execution |
| 245 |
|
| 246 |
:return: |
| 247 |
""" |
| 248 |
argument_spec = keycloak_argument_spec() |
| 249 |
|
| 250 |
composites_spec = dict( |
| 251 |
name=dict(type="str", required=True), |
| 252 |
client_id=dict(type="str", aliases=["clientId"]), |
| 253 |
state=dict(type="str", default="present", choices=["present", "absent"]), |
| 254 |
) |
| 255 |
|
| 256 |
meta_args = dict( |
| 257 |
state=dict(type="str", default="present", choices=["present", "absent"]), |
| 258 |
name=dict(type="str", required=True), |
| 259 |
description=dict(type="str"), |
| 260 |
realm=dict(type="str", default="master"), |
| 261 |
client_id=dict(type="str"), |
| 262 |
attributes=dict(type="dict"), |
| 263 |
composites=dict(type="list", default=[], options=composites_spec, elements="dict"), |
| 264 |
composite=dict(type="bool", default=False), |
| 265 |
) |
| 266 |
|
| 267 |
argument_spec.update(meta_args) |
| 268 |
|
| 269 |
module = AnsibleModule( |
| 270 |
argument_spec=argument_spec, |
| 271 |
supports_check_mode=True, |
| 272 |
required_one_of=( |
| 273 |
[["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"]] |
| 274 |
), |
| 275 |
required_together=([["auth_username", "auth_password"]]), |
| 276 |
required_by={"refresh_token": "auth_realm"}, |
| 277 |
) |
| 278 |
|
| 279 |
result = dict(changed=False, msg="", diff={}, proposed={}, existing={}, end_state={}) |
| 280 |
|
| 281 |
# Obtain access token, initialize API |
| 282 |
try: |
| 283 |
connection_header = get_token(module.params) |
| 284 |
except KeycloakError as e: |
| 285 |
module.fail_json(msg=str(e)) |
| 286 |
|
| 287 |
kc = KeycloakAPI(module, connection_header) |
| 288 |
|
| 289 |
realm = module.params.get("realm") |
| 290 |
clientid = module.params.get("client_id") |
| 291 |
name = module.params.get("name") |
| 292 |
state = module.params.get("state") |
| 293 |
|
| 294 |
# attributes in Keycloak have their values returned as lists |
| 295 |
# using the API. attributes is a dict, so we'll transparently convert |
| 296 |
# the values to lists. |
| 297 |
if module.params.get("attributes") is not None: |
| 298 |
for key, val in module.params["attributes"].items(): |
| 299 |
module.params["attributes"][key] = [val] if not isinstance(val, list) else val |
| 300 |
|
| 301 |
# Filter and map the parameters names that apply to the role |
| 302 |
role_params = [ |
| 303 |
x |
| 304 |
for x in module.params |
| 305 |
if x not in list(keycloak_argument_spec().keys()) + ["state", "realm", "client_id"] |
| 306 |
and module.params.get(x) is not None |
| 307 |
] |
| 308 |
|
| 309 |
# See if it already exists in Keycloak |
| 310 |
if clientid is None: |
| 311 |
before_role = kc.get_realm_role(name, realm) |
| 312 |
else: |
| 313 |
before_role = kc.get_client_role(name, clientid, realm) |
| 314 |
|
| 315 |
if before_role is None: |
| 316 |
before_role = {} |
| 317 |
|
| 318 |
# Build a proposed changeset from parameters given to this module |
| 319 |
changeset = {} |
| 320 |
|
| 321 |
for param in role_params: |
| 322 |
new_param_value = module.params.get(param) |
| 323 |
old_value = before_role[param] if param in before_role else None |
| 324 |
if new_param_value != old_value: |
| 325 |
changeset[camel(param)] = copy.deepcopy(new_param_value) |
| 326 |
|
| 327 |
# Prepare the desired values using the existing values (non-existence results in a dict that is save to use as a basis) |
| 328 |
desired_role = copy.deepcopy(before_role) |
| 329 |
desired_role.update(changeset) |
| 330 |
|
| 331 |
result["proposed"] = changeset |
| 332 |
result["existing"] = before_role |
| 333 |
|
| 334 |
# Cater for when it doesn't exist (an empty dict) |
| 335 |
if not before_role: |
| 336 |
if state == "absent": |
| 337 |
# Do nothing and exit |
| 338 |
if module._diff: |
| 339 |
result["diff"] = dict(before="", after="") |
| 340 |
result["changed"] = False |
| 341 |
result["end_state"] = {} |
| 342 |
result["msg"] = "Role does not exist, doing nothing." |
| 343 |
module.exit_json(**result) |
| 344 |
|
| 345 |
# Process a creation |
| 346 |
result["changed"] = True |
| 347 |
|
| 348 |
if name is None: |
| 349 |
module.fail_json(msg="name must be specified when creating a new role") |
| 350 |
|
| 351 |
if module._diff: |
| 352 |
result["diff"] = dict(before="", after=desired_role) |
| 353 |
|
| 354 |
if module.check_mode: |
| 355 |
module.exit_json(**result) |
| 356 |
|
| 357 |
# create it |
| 358 |
if clientid is None: |
| 359 |
kc.create_realm_role(desired_role, realm) |
| 360 |
after_role = kc.get_realm_role(name, realm) |
| 361 |
else: |
| 362 |
kc.create_client_role(desired_role, clientid, realm) |
| 363 |
after_role = kc.get_client_role(name, clientid, realm) |
| 364 |
|
| 365 |
if after_role["composite"]: |
| 366 |
after_role["composites"] = kc.get_role_composites(rolerep=after_role, clientid=clientid, realm=realm) |
| 367 |
|
| 368 |
result["end_state"] = after_role |
| 369 |
|
| 370 |
result["msg"] = f"Role {name} has been created" |
| 371 |
module.exit_json(**result) |
| 372 |
|
| 373 |
else: |
| 374 |
if state == "present": |
| 375 |
compare_exclude = ["clientId"] |
| 376 |
if ( |
| 377 |
"composites" in desired_role |
| 378 |
and isinstance(desired_role["composites"], list) |
| 379 |
and len(desired_role["composites"]) > 0 |
| 380 |
): |
| 381 |
composites = kc.get_role_composites(rolerep=before_role, clientid=clientid, realm=realm) |
| 382 |
before_role["composites"] = [] |
| 383 |
for composite in composites: |
| 384 |
before_composite = {} |
| 385 |
if composite["clientRole"]: |
| 386 |
composite_client = kc.get_client_by_id(id=composite["containerId"], realm=realm) |
| 387 |
before_composite["client_id"] = composite_client["clientId"] |
| 388 |
else: |
| 389 |
before_composite["client_id"] = None |
| 390 |
before_composite["name"] = composite["name"] |
| 391 |
before_composite["state"] = "present" |
| 392 |
before_role["composites"].append(before_composite) |
| 393 |
else: |
| 394 |
compare_exclude.append("composites") |
| 395 |
# Process an update |
| 396 |
# no changes |
| 397 |
if is_struct_included(desired_role, before_role, exclude=compare_exclude): |
| 398 |
result["changed"] = False |
| 399 |
result["end_state"] = desired_role |
| 400 |
result["msg"] = f"No changes required to role {name}." |
| 401 |
module.exit_json(**result) |
| 402 |
|
| 403 |
# doing an update |
| 404 |
result["changed"] = True |
| 405 |
|
| 406 |
if module._diff: |
| 407 |
result["diff"] = dict(before=before_role, after=desired_role) |
| 408 |
|
| 409 |
if module.check_mode: |
| 410 |
module.exit_json(**result) |
| 411 |
|
| 412 |
# do the update |
| 413 |
if clientid is None: |
| 414 |
kc.update_realm_role(desired_role, realm) |
| 415 |
after_role = kc.get_realm_role(name, realm) |
| 416 |
else: |
| 417 |
kc.update_client_role(desired_role, clientid, realm) |
| 418 |
after_role = kc.get_client_role(name, clientid, realm) |
| 419 |
if after_role["composite"]: |
| 420 |
after_role["composites"] = kc.get_role_composites(rolerep=after_role, clientid=clientid, realm=realm) |
| 421 |
|
| 422 |
result["end_state"] = after_role |
| 423 |
|
| 424 |
result["msg"] = f"Role {name} has been updated" |
| 425 |
module.exit_json(**result) |
| 426 |
|
| 427 |
else: |
| 428 |
# Process a deletion (because state was not 'present') |
| 429 |
result["changed"] = True |
| 430 |
|
| 431 |
if module._diff: |
| 432 |
result["diff"] = dict(before=before_role, after="") |
| 433 |
|
| 434 |
if module.check_mode: |
| 435 |
module.exit_json(**result) |
| 436 |
|
| 437 |
# delete it |
| 438 |
if clientid is None: |
| 439 |
kc.delete_realm_role(name, realm) |
| 440 |
else: |
| 441 |
kc.delete_client_role(name, clientid, realm) |
| 442 |
|
| 443 |
result["end_state"] = {} |
| 444 |
|
| 445 |
result["msg"] = f"Role {name} has been deleted" |
| 446 |
|
| 447 |
module.exit_json(**result) |
| 448 |
|
| 449 |
|
| 450 |
if __name__ == "__main__": |
| 451 |
main() |