| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) Ansible project |
| 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_userprofile |
| 11 |
|
| 12 |
short_description: Allows managing Keycloak User Profiles |
| 13 |
|
| 14 |
description: |
| 15 |
- This module allows you to create, update, or delete Keycloak User Profiles using the Keycloak API. You can also customize |
| 16 |
the "Unmanaged Attributes" with it. |
| 17 |
- The names of module options are snake_cased versions of the camelCase ones found in the Keycloak API and its documentation |
| 18 |
at U(https://www.keycloak.org/docs-api/24.0.5/rest-api/index.html). For compatibility reasons, the module also accepts |
| 19 |
the camelCase versions of the options. |
| 20 |
version_added: "9.4.0" |
| 21 |
|
| 22 |
attributes: |
| 23 |
check_mode: |
| 24 |
support: full |
| 25 |
diff_mode: |
| 26 |
support: full |
| 27 |
action_group: |
| 28 |
version_added: 10.2.0 |
| 29 |
|
| 30 |
options: |
| 31 |
state: |
| 32 |
description: |
| 33 |
- State of the User Profile provider. |
| 34 |
- On V(present), the User Profile provider is created if it does not yet exist, or updated with the parameters you provide. |
| 35 |
- On V(absent), the User Profile provider is removed if it exists. |
| 36 |
default: 'present' |
| 37 |
type: str |
| 38 |
choices: |
| 39 |
- present |
| 40 |
- absent |
| 41 |
|
| 42 |
parent_id: |
| 43 |
description: |
| 44 |
- The parent ID of the realm key. In practice the ID (name) of the realm. |
| 45 |
aliases: |
| 46 |
- parentId |
| 47 |
- realm |
| 48 |
type: str |
| 49 |
required: true |
| 50 |
|
| 51 |
provider_id: |
| 52 |
description: |
| 53 |
- The name of the provider ID for the key (supported value is V(declarative-user-profile)). |
| 54 |
aliases: |
| 55 |
- providerId |
| 56 |
choices: ['declarative-user-profile'] |
| 57 |
default: 'declarative-user-profile' |
| 58 |
type: str |
| 59 |
|
| 60 |
provider_type: |
| 61 |
description: |
| 62 |
- Component type for User Profile (only supported value is V(org.keycloak.userprofile.UserProfileProvider)). |
| 63 |
aliases: |
| 64 |
- providerType |
| 65 |
choices: ['org.keycloak.userprofile.UserProfileProvider'] |
| 66 |
default: org.keycloak.userprofile.UserProfileProvider |
| 67 |
type: str |
| 68 |
|
| 69 |
config: |
| 70 |
description: |
| 71 |
- The configuration of the User Profile Provider. |
| 72 |
type: dict |
| 73 |
suboptions: |
| 74 |
kc_user_profile_config: |
| 75 |
description: |
| 76 |
- Define a declarative User Profile. See EXAMPLES for more context. |
| 77 |
aliases: |
| 78 |
- kcUserProfileConfig |
| 79 |
type: list |
| 80 |
elements: dict |
| 81 |
suboptions: |
| 82 |
attributes: |
| 83 |
description: |
| 84 |
- A list of attributes to be included in the User Profile. |
| 85 |
type: list |
| 86 |
elements: dict |
| 87 |
suboptions: |
| 88 |
name: |
| 89 |
description: |
| 90 |
- The name of the attribute. |
| 91 |
type: str |
| 92 |
required: true |
| 93 |
|
| 94 |
display_name: |
| 95 |
description: |
| 96 |
- The display name of the attribute. |
| 97 |
aliases: |
| 98 |
- displayName |
| 99 |
type: str |
| 100 |
required: true |
| 101 |
|
| 102 |
validations: |
| 103 |
description: |
| 104 |
- The validations to be applied to the attribute. |
| 105 |
type: dict |
| 106 |
suboptions: |
| 107 |
length: |
| 108 |
description: |
| 109 |
- The length validation for the attribute. |
| 110 |
type: dict |
| 111 |
suboptions: |
| 112 |
min: |
| 113 |
description: |
| 114 |
- The minimum length of the attribute. |
| 115 |
type: int |
| 116 |
max: |
| 117 |
description: |
| 118 |
- The maximum length of the attribute. |
| 119 |
type: int |
| 120 |
required: true |
| 121 |
|
| 122 |
email: |
| 123 |
description: |
| 124 |
- The email validation for the attribute. |
| 125 |
type: dict |
| 126 |
|
| 127 |
username_prohibited_characters: |
| 128 |
description: |
| 129 |
- The prohibited characters validation for the username attribute. |
| 130 |
type: dict |
| 131 |
aliases: |
| 132 |
- usernameProhibitedCharacters |
| 133 |
|
| 134 |
up_username_not_idn_homograph: |
| 135 |
description: |
| 136 |
- The validation to prevent IDN homograph attacks in usernames. |
| 137 |
type: dict |
| 138 |
aliases: |
| 139 |
- upUsernameNotIdnHomograph |
| 140 |
|
| 141 |
person_name_prohibited_characters: |
| 142 |
description: |
| 143 |
- The prohibited characters validation for person name attributes. |
| 144 |
type: dict |
| 145 |
aliases: |
| 146 |
- personNameProhibitedCharacters |
| 147 |
|
| 148 |
uri: |
| 149 |
description: |
| 150 |
- The URI validation for the attribute. |
| 151 |
type: dict |
| 152 |
|
| 153 |
pattern: |
| 154 |
description: |
| 155 |
- The pattern validation for the attribute using regular expressions. |
| 156 |
type: dict |
| 157 |
|
| 158 |
options: |
| 159 |
description: |
| 160 |
- Validation to ensure the attribute matches one of the provided options. |
| 161 |
type: dict |
| 162 |
|
| 163 |
integer: |
| 164 |
description: |
| 165 |
- The integer validation for the attribute. |
| 166 |
type: dict |
| 167 |
version_added: 12.2.0 |
| 168 |
|
| 169 |
double: |
| 170 |
description: |
| 171 |
- The double validation for the attribute. |
| 172 |
type: dict |
| 173 |
version_added: 12.2.0 |
| 174 |
|
| 175 |
iso_date: |
| 176 |
description: |
| 177 |
- The iso-date validation for the attribute. |
| 178 |
type: dict |
| 179 |
aliases: |
| 180 |
- isoDate |
| 181 |
version_added: 12.2.0 |
| 182 |
|
| 183 |
local_date: |
| 184 |
description: |
| 185 |
- The local-date validation for the attribute. |
| 186 |
type: dict |
| 187 |
aliases: |
| 188 |
- localDate |
| 189 |
version_added: 12.2.0 |
| 190 |
|
| 191 |
multivalued: |
| 192 |
description: |
| 193 |
- The multivalued validation for the attribute. |
| 194 |
type: dict |
| 195 |
suboptions: |
| 196 |
min: |
| 197 |
description: |
| 198 |
- The minimum amount of values of the attribute. |
| 199 |
type: int |
| 200 |
max: |
| 201 |
description: |
| 202 |
- The maximum amount of values of the attribute. |
| 203 |
type: int |
| 204 |
required: true |
| 205 |
version_added: 12.2.0 |
| 206 |
|
| 207 |
annotations: |
| 208 |
description: |
| 209 |
- Annotations for the attribute. |
| 210 |
type: dict |
| 211 |
|
| 212 |
group: |
| 213 |
description: |
| 214 |
- Specifies the User Profile group where this attribute is added. |
| 215 |
type: str |
| 216 |
|
| 217 |
permissions: |
| 218 |
description: |
| 219 |
- The permissions for viewing and editing the attribute. |
| 220 |
type: dict |
| 221 |
suboptions: |
| 222 |
view: |
| 223 |
description: |
| 224 |
- The roles that can view the attribute. |
| 225 |
- Supported values are V(admin) and V(user). |
| 226 |
type: list |
| 227 |
elements: str |
| 228 |
default: |
| 229 |
- admin |
| 230 |
- user |
| 231 |
|
| 232 |
edit: |
| 233 |
description: |
| 234 |
- The roles that can edit the attribute. |
| 235 |
- Supported values are V(admin) and V(user). |
| 236 |
type: list |
| 237 |
elements: str |
| 238 |
default: |
| 239 |
- admin |
| 240 |
- user |
| 241 |
|
| 242 |
multivalued: |
| 243 |
description: |
| 244 |
- Whether the attribute can have multiple values. |
| 245 |
type: bool |
| 246 |
default: false |
| 247 |
|
| 248 |
required: |
| 249 |
description: |
| 250 |
- The roles that require this attribute. |
| 251 |
type: dict |
| 252 |
suboptions: |
| 253 |
roles: |
| 254 |
description: |
| 255 |
- The roles for which this attribute is required. |
| 256 |
- Supported values are V(admin) and V(user). |
| 257 |
type: list |
| 258 |
elements: str |
| 259 |
default: |
| 260 |
- user |
| 261 |
|
| 262 |
selector: |
| 263 |
description: |
| 264 |
- Selector when the attribute should be added. |
| 265 |
type: dict |
| 266 |
version_added: 12.2.0 |
| 267 |
suboptions: |
| 268 |
scopes: |
| 269 |
description: |
| 270 |
- Scopes to which the attribute should be added. |
| 271 |
type: list |
| 272 |
elements: str |
| 273 |
|
| 274 |
groups: |
| 275 |
description: |
| 276 |
- A list of attribute groups to be included in the User Profile. |
| 277 |
type: list |
| 278 |
elements: dict |
| 279 |
suboptions: |
| 280 |
name: |
| 281 |
description: |
| 282 |
- The name of the group. |
| 283 |
type: str |
| 284 |
required: true |
| 285 |
|
| 286 |
display_header: |
| 287 |
description: |
| 288 |
- The display header for the group. |
| 289 |
aliases: |
| 290 |
- displayHeader |
| 291 |
type: str |
| 292 |
required: true |
| 293 |
|
| 294 |
display_description: |
| 295 |
description: |
| 296 |
- The display description for the group. |
| 297 |
aliases: |
| 298 |
- displayDescription |
| 299 |
type: str |
| 300 |
|
| 301 |
annotations: |
| 302 |
description: |
| 303 |
- The annotations included in the group. |
| 304 |
type: dict |
| 305 |
|
| 306 |
unmanaged_attribute_policy: |
| 307 |
description: |
| 308 |
- Policy for unmanaged attributes. |
| 309 |
aliases: |
| 310 |
- unmanagedAttributePolicy |
| 311 |
type: str |
| 312 |
choices: |
| 313 |
- ENABLED |
| 314 |
- ADMIN_EDIT |
| 315 |
- ADMIN_VIEW |
| 316 |
|
| 317 |
notes: |
| 318 |
- Currently, only a single V(declarative-user-profile) entry is supported for O(provider_id) (design of the Keyckoak API). |
| 319 |
However, there can be multiple O(config.kc_user_profile_config[].attributes[]) entries. |
| 320 |
extends_documentation_fragment: |
| 321 |
- community.general._keycloak |
| 322 |
- community.general._keycloak.actiongroup_keycloak |
| 323 |
- community.general._attributes |
| 324 |
|
| 325 |
author: |
| 326 |
- Eike Waldt (@yeoldegrove) |
| 327 |
""" |
| 328 |
|
| 329 |
EXAMPLES = r""" |
| 330 |
- name: Create a Declarative User Profile with default settings |
| 331 |
community.general.keycloak_userprofile: |
| 332 |
state: present |
| 333 |
parent_id: master |
| 334 |
config: |
| 335 |
kc_user_profile_config: |
| 336 |
- attributes: |
| 337 |
- name: username |
| 338 |
displayName: ${username} |
| 339 |
validations: |
| 340 |
length: |
| 341 |
min: 3 |
| 342 |
max: 255 |
| 343 |
username_prohibited_characters: {} |
| 344 |
up_username_not_idn_homograph: {} |
| 345 |
annotations: {} |
| 346 |
permissions: |
| 347 |
view: |
| 348 |
- admin |
| 349 |
- user |
| 350 |
edit: [] |
| 351 |
multivalued: false |
| 352 |
- name: email |
| 353 |
displayName: ${email} |
| 354 |
validations: |
| 355 |
email: {} |
| 356 |
length: |
| 357 |
max: 255 |
| 358 |
annotations: {} |
| 359 |
required: |
| 360 |
roles: |
| 361 |
- user |
| 362 |
permissions: |
| 363 |
view: |
| 364 |
- admin |
| 365 |
- user |
| 366 |
edit: [] |
| 367 |
multivalued: false |
| 368 |
- name: firstName |
| 369 |
displayName: ${firstName} |
| 370 |
validations: |
| 371 |
length: |
| 372 |
max: 255 |
| 373 |
person_name_prohibited_characters: {} |
| 374 |
annotations: {} |
| 375 |
required: |
| 376 |
roles: |
| 377 |
- user |
| 378 |
permissions: |
| 379 |
view: |
| 380 |
- admin |
| 381 |
- user |
| 382 |
edit: [] |
| 383 |
multivalued: false |
| 384 |
- name: lastName |
| 385 |
displayName: ${lastName} |
| 386 |
validations: |
| 387 |
length: |
| 388 |
max: 255 |
| 389 |
person_name_prohibited_characters: {} |
| 390 |
annotations: {} |
| 391 |
required: |
| 392 |
roles: |
| 393 |
- user |
| 394 |
permissions: |
| 395 |
view: |
| 396 |
- admin |
| 397 |
- user |
| 398 |
edit: [] |
| 399 |
multivalued: false |
| 400 |
- name: testAttribute |
| 401 |
displayName: ${testAttribute} |
| 402 |
validations: |
| 403 |
integer: |
| 404 |
min: 0 |
| 405 |
max: 255 |
| 406 |
annotations: {} |
| 407 |
required: |
| 408 |
roles: |
| 409 |
- user |
| 410 |
permissions: |
| 411 |
view: |
| 412 |
- admin |
| 413 |
- user |
| 414 |
edit: [] |
| 415 |
multivalued: false |
| 416 |
groups: |
| 417 |
- name: user-metadata |
| 418 |
displayHeader: User metadata |
| 419 |
displayDescription: Attributes, which refer to user metadata |
| 420 |
annotations: {} |
| 421 |
|
| 422 |
- name: Delete a Keycloak User Profile Provider |
| 423 |
keycloak_userprofile: |
| 424 |
state: absent |
| 425 |
parent_id: master |
| 426 |
|
| 427 |
# Unmanaged attributes are user attributes not explicitly defined in the User Profile |
| 428 |
# configuration. By default, unmanaged attributes are "Disabled" and are not |
| 429 |
# available from any context such as registration, account, and the |
| 430 |
# administration console. By setting "Enabled", unmanaged attributes are fully |
| 431 |
# recognized by the server and accessible through all contexts, useful if you are |
| 432 |
# starting migrating an existing realm to the declarative User Profile |
| 433 |
# and you don't have yet all user attributes defined in the User Profile configuration. |
| 434 |
- name: Enable Unmanaged Attributes |
| 435 |
community.general.keycloak_userprofile: |
| 436 |
state: present |
| 437 |
parent_id: master |
| 438 |
config: |
| 439 |
kc_user_profile_config: |
| 440 |
- unmanagedAttributePolicy: ENABLED |
| 441 |
|
| 442 |
# By setting "Only administrators can write", unmanaged attributes can be managed |
| 443 |
# only through the administration console and API, useful if you have already |
| 444 |
# defined any custom attribute that can be managed by users but you are unsure |
| 445 |
# about adding other attributes that should only be managed by administrators. |
| 446 |
- name: Enable ADMIN_EDIT on Unmanaged Attributes |
| 447 |
community.general.keycloak_userprofile: |
| 448 |
state: present |
| 449 |
parent_id: master |
| 450 |
config: |
| 451 |
kc_user_profile_config: |
| 452 |
- unmanagedAttributePolicy: ADMIN_EDIT |
| 453 |
|
| 454 |
# By setting `Only administrators can view`, unmanaged attributes are read-only |
| 455 |
# and only available through the administration console and API. |
| 456 |
- name: Enable ADMIN_VIEW on Unmanaged Attributes |
| 457 |
community.general.keycloak_userprofile: |
| 458 |
state: present |
| 459 |
parent_id: master |
| 460 |
config: |
| 461 |
kc_user_profile_config: |
| 462 |
- unmanagedAttributePolicy: ADMIN_VIEW |
| 463 |
""" |
| 464 |
|
| 465 |
RETURN = r""" |
| 466 |
msg: |
| 467 |
description: The output message generated by the module. |
| 468 |
returned: always |
| 469 |
type: str |
| 470 |
sample: UserProfileProvider created successfully |
| 471 |
data: |
| 472 |
description: The data returned by the Keycloak API. |
| 473 |
returned: when state is present |
| 474 |
type: dict |
| 475 |
""" |
| 476 |
|
| 477 |
import json |
| 478 |
from copy import deepcopy |
| 479 |
from urllib.parse import urlencode |
| 480 |
|
| 481 |
from ansible.module_utils.basic import AnsibleModule |
| 482 |
|
| 483 |
from ansible_collections.community.general.plugins.module_utils._keycloak import ( |
| 484 |
KeycloakAPI, |
| 485 |
KeycloakError, |
| 486 |
camel, |
| 487 |
get_token, |
| 488 |
keycloak_argument_spec, |
| 489 |
) |
| 490 |
|
| 491 |
|
| 492 |
def remove_null_values(data): |
| 493 |
if isinstance(data, dict): |
| 494 |
# Recursively remove null values from dictionaries |
| 495 |
return {k: remove_null_values(v) for k, v in data.items() if v is not None} |
| 496 |
elif isinstance(data, list): |
| 497 |
# Recursively remove null values from lists |
| 498 |
return [remove_null_values(item) for item in data if item is not None] |
| 499 |
else: |
| 500 |
# Return the data if it is neither a dictionary nor a list |
| 501 |
return data |
| 502 |
|
| 503 |
|
| 504 |
def camel_recursive(data): |
| 505 |
if isinstance(data, dict): |
| 506 |
# Convert keys to camelCase and apply recursively |
| 507 |
return {camel(k): camel_recursive(v) for k, v in data.items()} |
| 508 |
elif isinstance(data, list): |
| 509 |
# Apply camelCase conversion to each item in the list |
| 510 |
return [camel_recursive(item) for item in data] |
| 511 |
else: |
| 512 |
# Return the data as-is if it is not a dict or list |
| 513 |
return data |
| 514 |
|
| 515 |
|
| 516 |
def main(): |
| 517 |
argument_spec = keycloak_argument_spec() |
| 518 |
|
| 519 |
meta_args = dict( |
| 520 |
state=dict(type="str", choices=["present", "absent"], default="present"), |
| 521 |
parent_id=dict(type="str", aliases=["parentId", "realm"], required=True), |
| 522 |
provider_id=dict( |
| 523 |
type="str", aliases=["providerId"], default="declarative-user-profile", choices=["declarative-user-profile"] |
| 524 |
), |
| 525 |
provider_type=dict( |
| 526 |
type="str", |
| 527 |
aliases=["providerType"], |
| 528 |
default="org.keycloak.userprofile.UserProfileProvider", |
| 529 |
choices=["org.keycloak.userprofile.UserProfileProvider"], |
| 530 |
), |
| 531 |
config=dict( |
| 532 |
type="dict", |
| 533 |
options={ |
| 534 |
"kc_user_profile_config": dict( |
| 535 |
type="list", |
| 536 |
aliases=["kcUserProfileConfig"], |
| 537 |
elements="dict", |
| 538 |
options={ |
| 539 |
"attributes": dict( |
| 540 |
type="list", |
| 541 |
elements="dict", |
| 542 |
options={ |
| 543 |
"name": dict(type="str", required=True), |
| 544 |
"display_name": dict(type="str", aliases=["displayName"], required=True), |
| 545 |
"validations": dict( |
| 546 |
type="dict", |
| 547 |
options={ |
| 548 |
"length": dict( |
| 549 |
type="dict", |
| 550 |
options={"min": dict(type="int"), "max": dict(type="int", required=True)}, |
| 551 |
), |
| 552 |
"email": dict(type="dict"), |
| 553 |
"username_prohibited_characters": dict( |
| 554 |
type="dict", aliases=["usernameProhibitedCharacters"] |
| 555 |
), |
| 556 |
"up_username_not_idn_homograph": dict( |
| 557 |
type="dict", aliases=["upUsernameNotIdnHomograph"] |
| 558 |
), |
| 559 |
"person_name_prohibited_characters": dict( |
| 560 |
type="dict", aliases=["personNameProhibitedCharacters"] |
| 561 |
), |
| 562 |
"uri": dict(type="dict"), |
| 563 |
"pattern": dict(type="dict"), |
| 564 |
"options": dict(type="dict"), |
| 565 |
"integer": dict(type="dict"), |
| 566 |
"double": dict(type="dict"), |
| 567 |
"iso_date": dict(type="dict", aliases=["isoDate"]), |
| 568 |
"local_date": dict(type="dict", aliases=["localDate"]), |
| 569 |
"multivalued": dict( |
| 570 |
type="dict", |
| 571 |
options={ |
| 572 |
"min": dict(type="int", required=False), |
| 573 |
"max": dict(type="int", required=True), |
| 574 |
}, |
| 575 |
), |
| 576 |
}, |
| 577 |
), |
| 578 |
"annotations": dict(type="dict"), |
| 579 |
"group": dict(type="str"), |
| 580 |
"permissions": dict( |
| 581 |
type="dict", |
| 582 |
options={ |
| 583 |
"view": dict(type="list", elements="str", default=["admin", "user"]), |
| 584 |
"edit": dict(type="list", elements="str", default=["admin", "user"]), |
| 585 |
}, |
| 586 |
), |
| 587 |
"multivalued": dict(type="bool", default=False), |
| 588 |
"required": dict( |
| 589 |
type="dict", options={"roles": dict(type="list", elements="str", default=["user"])} |
| 590 |
), |
| 591 |
"selector": dict(type="dict", options={"scopes": dict(type="list", elements="str")}), |
| 592 |
}, |
| 593 |
), |
| 594 |
"groups": dict( |
| 595 |
type="list", |
| 596 |
elements="dict", |
| 597 |
options={ |
| 598 |
"name": dict(type="str", required=True), |
| 599 |
"display_header": dict(type="str", aliases=["displayHeader"], required=True), |
| 600 |
"display_description": dict(type="str", aliases=["displayDescription"]), |
| 601 |
"annotations": dict(type="dict"), |
| 602 |
}, |
| 603 |
), |
| 604 |
"unmanaged_attribute_policy": dict( |
| 605 |
type="str", |
| 606 |
aliases=["unmanagedAttributePolicy"], |
| 607 |
choices=["ENABLED", "ADMIN_EDIT", "ADMIN_VIEW"], |
| 608 |
), |
| 609 |
}, |
| 610 |
) |
| 611 |
}, |
| 612 |
), |
| 613 |
) |
| 614 |
|
| 615 |
argument_spec.update(meta_args) |
| 616 |
|
| 617 |
module = AnsibleModule( |
| 618 |
argument_spec=argument_spec, |
| 619 |
supports_check_mode=True, |
| 620 |
required_one_of=( |
| 621 |
[["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"]] |
| 622 |
), |
| 623 |
required_together=([["auth_username", "auth_password"]]), |
| 624 |
required_by={"refresh_token": "auth_realm"}, |
| 625 |
) |
| 626 |
|
| 627 |
# Initialize the result object. Only "changed" seems to have special |
| 628 |
# meaning for Ansible. |
| 629 |
result = dict(changed=False, msg="", end_state={}, diff=dict(before={}, after={})) |
| 630 |
|
| 631 |
# This will include the current state of the realm userprofile if it is already |
| 632 |
# present. This is only used for diff-mode. |
| 633 |
before_realm_userprofile = {} |
| 634 |
before_realm_userprofile["config"] = {} |
| 635 |
|
| 636 |
# Obtain access token, initialize API |
| 637 |
try: |
| 638 |
connection_header = get_token(module.params) |
| 639 |
except KeycloakError as e: |
| 640 |
module.fail_json(msg=str(e)) |
| 641 |
|
| 642 |
kc = KeycloakAPI(module, connection_header) |
| 643 |
|
| 644 |
params_to_ignore = list(keycloak_argument_spec().keys()) + ["state"] |
| 645 |
|
| 646 |
# Filter and map the parameters names that apply to the role |
| 647 |
component_params = [x for x in module.params if x not in params_to_ignore and module.params.get(x) is not None] |
| 648 |
|
| 649 |
# Build a proposed changeset from parameters given to this module |
| 650 |
changeset = {} |
| 651 |
|
| 652 |
# Build the changeset with proper JSON serialization for kc_user_profile_config |
| 653 |
config = module.params.get("config") |
| 654 |
changeset["config"] = {} |
| 655 |
|
| 656 |
# Generate a JSON payload for Keycloak Admin API from the module |
| 657 |
# parameters. Parameters that do not belong to the JSON payload (e.g. |
| 658 |
# "state" or "auth_keycloal_url") have been filtered away earlier (see |
| 659 |
# above). |
| 660 |
# |
| 661 |
# This loop converts Ansible module parameters (snake-case) into |
| 662 |
# Keycloak-compatible format (camel-case). For example proider_id |
| 663 |
# becomes providerId. It also handles some special cases, e.g. aliases. |
| 664 |
for component_param in component_params: |
| 665 |
# realm/parent_id parameter |
| 666 |
if component_param == "realm" or component_param == "parent_id": |
| 667 |
changeset["parent_id"] = module.params.get(component_param) |
| 668 |
changeset.pop(component_param, None) |
| 669 |
# complex parameters in config suboptions |
| 670 |
elif component_param == "config": |
| 671 |
for config_param in config: |
| 672 |
# special parameter kc_user_profile_config |
| 673 |
if config_param in ("kcUserProfileConfig", "kc_user_profile_config"): |
| 674 |
config_param_org = config_param |
| 675 |
# rename parameter to be accepted by Keycloak API |
| 676 |
config_param = "kc.user.profile.config" |
| 677 |
# make sure no null values are passed to Keycloak API |
| 678 |
kc_user_profile_config = remove_null_values(config[config_param_org]) |
| 679 |
changeset[camel(component_param)][config_param] = [] |
| 680 |
if len(kc_user_profile_config) > 0: |
| 681 |
# convert aliases to camelCase |
| 682 |
kc_user_profile_config = camel_recursive(kc_user_profile_config) |
| 683 |
# rename validations to be accepted by Keycloak API |
| 684 |
if "attributes" in kc_user_profile_config[0]: |
| 685 |
for attribute in kc_user_profile_config[0]["attributes"]: |
| 686 |
if "validations" in attribute: |
| 687 |
if "usernameProhibitedCharacters" in attribute["validations"]: |
| 688 |
attribute["validations"]["username-prohibited-characters"] = attribute[ |
| 689 |
"validations" |
| 690 |
].pop("usernameProhibitedCharacters") |
| 691 |
if "upUsernameNotIdnHomograph" in attribute["validations"]: |
| 692 |
attribute["validations"]["up-username-not-idn-homograph"] = attribute[ |
| 693 |
"validations" |
| 694 |
].pop("upUsernameNotIdnHomograph") |
| 695 |
if "personNameProhibitedCharacters" in attribute["validations"]: |
| 696 |
attribute["validations"]["person-name-prohibited-characters"] = attribute[ |
| 697 |
"validations" |
| 698 |
].pop("personNameProhibitedCharacters") |
| 699 |
if "isoDate" in attribute["validations"]: |
| 700 |
attribute["validations"]["iso-date"] = attribute["validations"].pop("isoDate") |
| 701 |
if "localDate" in attribute["validations"]: |
| 702 |
attribute["validations"]["local-date"] = attribute["validations"].pop( |
| 703 |
"localDate" |
| 704 |
) |
| 705 |
changeset[camel(component_param)][config_param].append(kc_user_profile_config[0]) |
| 706 |
# usual camelCase parameters |
| 707 |
else: |
| 708 |
changeset[camel(component_param)][camel(config_param)] = [] |
| 709 |
raw_value = module.params.get(component_param)[config_param] |
| 710 |
if isinstance(raw_value, bool): |
| 711 |
value = str(raw_value).lower() |
| 712 |
else: |
| 713 |
value = raw_value # Directly use the raw value |
| 714 |
changeset[camel(component_param)][camel(config_param)].append(value) |
| 715 |
# usual parameters |
| 716 |
else: |
| 717 |
new_param_value = module.params.get(component_param) |
| 718 |
changeset[camel(component_param)] = new_param_value |
| 719 |
|
| 720 |
# Make it easier to refer to current module parameters |
| 721 |
state = module.params.get("state") |
| 722 |
parent_id = module.params.get("parent_id") |
| 723 |
provider_type = module.params.get("provider_type") |
| 724 |
provider_id = module.params.get("provider_id") |
| 725 |
|
| 726 |
# Make a deep copy of the changeset. This is use when determining |
| 727 |
# changes to the current state. |
| 728 |
changeset_copy = deepcopy(changeset) |
| 729 |
|
| 730 |
# Get a list of all Keycloak components that are of userprofile provider type. |
| 731 |
realm_userprofiles = kc.get_components(urlencode(dict(type=provider_type)), parent_id) |
| 732 |
|
| 733 |
# If this component is present get its userprofile ID. Confusingly the userprofile ID is |
| 734 |
# also known as the Provider ID. |
| 735 |
userprofile_id = None |
| 736 |
|
| 737 |
# Track individual parameter changes |
| 738 |
changes = "" |
| 739 |
|
| 740 |
# This tells Ansible whether the userprofile was changed (added, removed, modified) |
| 741 |
result["changed"] = False |
| 742 |
|
| 743 |
# Loop through the list of components. If we encounter a component whose |
| 744 |
# name matches the value of the name parameter then assume the userprofile is |
| 745 |
# already present. |
| 746 |
for userprofile in realm_userprofiles: |
| 747 |
if provider_id == "declarative-user-profile": |
| 748 |
userprofile_id = userprofile["id"] |
| 749 |
changeset["id"] = userprofile_id |
| 750 |
changeset_copy["id"] = userprofile_id |
| 751 |
|
| 752 |
# keycloak returns kc.user.profile.config as a single JSON formatted string, so we have to deserialize it |
| 753 |
if "config" in userprofile and "kc.user.profile.config" in userprofile["config"]: |
| 754 |
userprofile["config"]["kc.user.profile.config"][0] = json.loads( |
| 755 |
userprofile["config"]["kc.user.profile.config"][0] |
| 756 |
) |
| 757 |
|
| 758 |
# Compare top-level parameters |
| 759 |
for param in changeset: |
| 760 |
before_realm_userprofile[param] = userprofile[param] |
| 761 |
|
| 762 |
if changeset_copy[param] != userprofile[param] and param != "config": |
| 763 |
changes += f"{param}: {userprofile[param]} -> {changeset_copy[param]}, " |
| 764 |
result["changed"] = True |
| 765 |
|
| 766 |
# Compare parameters under the "config" userprofile |
| 767 |
for p, v in changeset_copy["config"].items(): |
| 768 |
before_realm_userprofile["config"][p] = userprofile["config"][p] |
| 769 |
if v != userprofile["config"][p]: |
| 770 |
changes += f"config.{p}: {userprofile['config'][p]} -> {v}, " |
| 771 |
result["changed"] = True |
| 772 |
|
| 773 |
# Check all the possible states of the resource and do what is needed to |
| 774 |
# converge current state with desired state (create, update or delete |
| 775 |
# the userprofile). |
| 776 |
|
| 777 |
# keycloak expects kc.user.profile.config as a single JSON formatted string, so we have to serialize it |
| 778 |
if "config" in changeset and "kc.user.profile.config" in changeset["config"]: |
| 779 |
changeset["config"]["kc.user.profile.config"][0] = json.dumps(changeset["config"]["kc.user.profile.config"][0]) |
| 780 |
if userprofile_id and state == "present": |
| 781 |
if result["changed"]: |
| 782 |
if module._diff: |
| 783 |
result["diff"] = dict(before=before_realm_userprofile, after=changeset_copy) |
| 784 |
|
| 785 |
if module.check_mode: |
| 786 |
result["msg"] = f"Userprofile {provider_id} would be changed: {changes.strip(', ')}" |
| 787 |
else: |
| 788 |
kc.update_component(changeset, parent_id) |
| 789 |
result["msg"] = f"Userprofile {provider_id} changed: {changes.strip(', ')}" |
| 790 |
else: |
| 791 |
result["msg"] = f"Userprofile {provider_id} was in sync" |
| 792 |
|
| 793 |
result["end_state"] = changeset_copy |
| 794 |
elif userprofile_id and state == "absent": |
| 795 |
if module._diff: |
| 796 |
result["diff"] = dict(before=before_realm_userprofile, after={}) |
| 797 |
|
| 798 |
if module.check_mode: |
| 799 |
result["changed"] = True |
| 800 |
result["msg"] = f"Userprofile {provider_id} would be deleted" |
| 801 |
else: |
| 802 |
kc.delete_component(userprofile_id, parent_id) |
| 803 |
result["changed"] = True |
| 804 |
result["msg"] = f"Userprofile {provider_id} deleted" |
| 805 |
|
| 806 |
result["end_state"] = {} |
| 807 |
elif not userprofile_id and state == "present": |
| 808 |
if module._diff: |
| 809 |
result["diff"] = dict(before={}, after=changeset_copy) |
| 810 |
|
| 811 |
if module.check_mode: |
| 812 |
result["changed"] = True |
| 813 |
result["msg"] = f"Userprofile {provider_id} would be created" |
| 814 |
else: |
| 815 |
kc.create_component(changeset, parent_id) |
| 816 |
result["changed"] = True |
| 817 |
result["msg"] = f"Userprofile {provider_id} created" |
| 818 |
|
| 819 |
result["end_state"] = changeset_copy |
| 820 |
elif not userprofile_id and state == "absent": |
| 821 |
result["changed"] = False |
| 822 |
result["msg"] = f"Userprofile {provider_id} not present" |
| 823 |
result["end_state"] = {} |
| 824 |
|
| 825 |
module.exit_json(**result) |
| 826 |
|
| 827 |
|
| 828 |
if __name__ == "__main__": |
| 829 |
main() |