| 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_identity_provider |
| 11 |
|
| 12 |
short_description: Allows administration of Keycloak identity providers using Keycloak API |
| 13 |
|
| 14 |
version_added: 3.6.0 |
| 15 |
|
| 16 |
description: |
| 17 |
- This module allows you to add, remove or modify Keycloak identity providers using the Keycloak REST API. It requires access |
| 18 |
to the REST API using OpenID Connect; the user connecting and the client being used must have the requisite access rights. |
| 19 |
In a default Keycloak installation, admin-cli and an admin user would work, as would a separate client definition with |
| 20 |
the 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/15.0/rest-api/index.html). |
| 23 |
attributes: |
| 24 |
check_mode: |
| 25 |
support: full |
| 26 |
diff_mode: |
| 27 |
support: full |
| 28 |
action_group: |
| 29 |
version_added: 10.2.0 |
| 30 |
|
| 31 |
options: |
| 32 |
state: |
| 33 |
description: |
| 34 |
- State of the identity provider. |
| 35 |
- On V(present), the identity provider is created if it does not yet exist, or updated with the parameters you provide. |
| 36 |
- On V(absent), the identity provider is removed if it exists. |
| 37 |
default: 'present' |
| 38 |
type: str |
| 39 |
choices: |
| 40 |
- present |
| 41 |
- absent |
| 42 |
|
| 43 |
realm: |
| 44 |
description: |
| 45 |
- The Keycloak realm under which this identity provider resides. |
| 46 |
default: 'master' |
| 47 |
type: str |
| 48 |
|
| 49 |
alias: |
| 50 |
description: |
| 51 |
- The alias uniquely identifies an identity provider and it is also used to build the redirect URI. |
| 52 |
required: true |
| 53 |
type: str |
| 54 |
|
| 55 |
display_name: |
| 56 |
description: |
| 57 |
- Friendly name for identity provider. |
| 58 |
aliases: |
| 59 |
- displayName |
| 60 |
type: str |
| 61 |
|
| 62 |
enabled: |
| 63 |
description: |
| 64 |
- Enable/disable this identity provider. |
| 65 |
type: bool |
| 66 |
|
| 67 |
store_token: |
| 68 |
description: |
| 69 |
- Enable/disable whether tokens must be stored after authenticating users. |
| 70 |
aliases: |
| 71 |
- storeToken |
| 72 |
type: bool |
| 73 |
|
| 74 |
add_read_token_role_on_create: |
| 75 |
description: |
| 76 |
- Enable/disable whether new users can read any stored tokens. This assigns the C(broker.read-token) role. |
| 77 |
aliases: |
| 78 |
- addReadTokenRoleOnCreate |
| 79 |
type: bool |
| 80 |
|
| 81 |
trust_email: |
| 82 |
description: |
| 83 |
- If enabled, email provided by this provider is not verified even if verification is enabled for the realm. |
| 84 |
aliases: |
| 85 |
- trustEmail |
| 86 |
type: bool |
| 87 |
|
| 88 |
link_only: |
| 89 |
description: |
| 90 |
- If true, users cannot log in through this provider. They can only link to this provider. This is useful if you do |
| 91 |
not want to allow login from the provider, but want to integrate with a provider. |
| 92 |
aliases: |
| 93 |
- linkOnly |
| 94 |
type: bool |
| 95 |
|
| 96 |
first_broker_login_flow_alias: |
| 97 |
description: |
| 98 |
- Alias of authentication flow, which is triggered after first login with this identity provider. |
| 99 |
aliases: |
| 100 |
- firstBrokerLoginFlowAlias |
| 101 |
type: str |
| 102 |
|
| 103 |
post_broker_login_flow_alias: |
| 104 |
description: |
| 105 |
- Alias of authentication flow, which is triggered after each login with this identity provider. |
| 106 |
aliases: |
| 107 |
- postBrokerLoginFlowAlias |
| 108 |
type: str |
| 109 |
|
| 110 |
authenticate_by_default: |
| 111 |
description: |
| 112 |
- Specifies if this identity provider should be used by default for authentication even before displaying login screen. |
| 113 |
aliases: |
| 114 |
- authenticateByDefault |
| 115 |
type: bool |
| 116 |
|
| 117 |
provider_id: |
| 118 |
description: |
| 119 |
- Protocol used by this provider (supported values are V(oidc) or V(saml)). |
| 120 |
aliases: |
| 121 |
- providerId |
| 122 |
type: str |
| 123 |
|
| 124 |
config: |
| 125 |
description: |
| 126 |
- Dict specifying the configuration options for the provider; the contents differ depending on the value of O(provider_id). |
| 127 |
Examples are given below for V(oidc) and V(saml). It is easiest to obtain valid config values by dumping an already-existing |
| 128 |
identity provider configuration through check-mode in the RV(existing) field. |
| 129 |
type: dict |
| 130 |
suboptions: |
| 131 |
hide_on_login_page: |
| 132 |
description: |
| 133 |
- If hidden, login with this provider is possible only if requested explicitly, for example using the C(kc_idp_hint) |
| 134 |
parameter. |
| 135 |
aliases: |
| 136 |
- hideOnLoginPage |
| 137 |
type: bool |
| 138 |
|
| 139 |
gui_order: |
| 140 |
description: |
| 141 |
- Number defining order of the provider in GUI (for example, on Login page). |
| 142 |
aliases: |
| 143 |
- guiOrder |
| 144 |
type: int |
| 145 |
|
| 146 |
sync_mode: |
| 147 |
description: |
| 148 |
- Default sync mode for all mappers. The sync mode determines when user data is synced using the mappers. |
| 149 |
aliases: |
| 150 |
- syncMode |
| 151 |
type: str |
| 152 |
|
| 153 |
issuer: |
| 154 |
description: |
| 155 |
- The issuer identifier for the issuer of the response. If not provided, no validation is performed. |
| 156 |
type: str |
| 157 |
|
| 158 |
authorizationUrl: |
| 159 |
description: |
| 160 |
- The Authorization URL. |
| 161 |
type: str |
| 162 |
|
| 163 |
tokenUrl: |
| 164 |
description: |
| 165 |
- The Token URL. |
| 166 |
type: str |
| 167 |
|
| 168 |
logoutUrl: |
| 169 |
description: |
| 170 |
- End session endpoint to use to logout user from external IDP. |
| 171 |
type: str |
| 172 |
|
| 173 |
userInfoUrl: |
| 174 |
description: |
| 175 |
- The User Info URL. |
| 176 |
type: str |
| 177 |
|
| 178 |
clientAuthMethod: |
| 179 |
description: |
| 180 |
- The client authentication method. |
| 181 |
type: str |
| 182 |
|
| 183 |
clientId: |
| 184 |
description: |
| 185 |
- The client or client identifier registered within the identity provider. |
| 186 |
type: str |
| 187 |
|
| 188 |
clientSecret: |
| 189 |
description: |
| 190 |
- The client or client secret registered within the identity provider. |
| 191 |
type: str |
| 192 |
|
| 193 |
defaultScope: |
| 194 |
description: |
| 195 |
- The scopes to be sent when asking for authorization. |
| 196 |
type: str |
| 197 |
|
| 198 |
validateSignature: |
| 199 |
description: |
| 200 |
- Enable/disable signature validation of external IDP signatures. |
| 201 |
type: bool |
| 202 |
|
| 203 |
useJwksUrl: |
| 204 |
description: |
| 205 |
- If V(true), identity provider public keys are downloaded from given JWKS URL. |
| 206 |
type: bool |
| 207 |
|
| 208 |
jwksUrl: |
| 209 |
description: |
| 210 |
- URL where identity provider keys in JWK format are stored. See JWK specification for more details. |
| 211 |
type: str |
| 212 |
|
| 213 |
entityId: |
| 214 |
description: |
| 215 |
- The Entity ID that is used to uniquely identify this SAML Service Provider. |
| 216 |
type: str |
| 217 |
|
| 218 |
singleSignOnServiceUrl: |
| 219 |
description: |
| 220 |
- The URL that must be used to send authentication requests (SAML AuthnRequest). |
| 221 |
type: str |
| 222 |
|
| 223 |
singleLogoutServiceUrl: |
| 224 |
description: |
| 225 |
- The URL that must be used to send logout requests. |
| 226 |
type: str |
| 227 |
|
| 228 |
backchannelSupported: |
| 229 |
description: |
| 230 |
- Does the external IDP support backchannel logout? |
| 231 |
type: str |
| 232 |
|
| 233 |
nameIDPolicyFormat: |
| 234 |
description: |
| 235 |
- Specifies the URI reference corresponding to a name identifier format. |
| 236 |
type: str |
| 237 |
|
| 238 |
principalType: |
| 239 |
description: |
| 240 |
- Way to identify and track external users from the assertion. |
| 241 |
type: str |
| 242 |
|
| 243 |
fromUrl: |
| 244 |
description: |
| 245 |
- IDP well-known OpenID Connect configuration URL. |
| 246 |
- Support only O(provider_id=oidc). |
| 247 |
- O(config.fromUrl) is mutually exclusive with O(config.userInfoUrl), O(config.authorizationUrl), |
| 248 |
O(config.tokenUrl), O(config.logoutUrl), O(config.issuer) and O(config.jwksUrl). |
| 249 |
type: str |
| 250 |
version_added: '11.2.0' |
| 251 |
|
| 252 |
mappers: |
| 253 |
description: |
| 254 |
- A list of dicts defining mappers associated with this Identity Provider. |
| 255 |
type: list |
| 256 |
elements: dict |
| 257 |
suboptions: |
| 258 |
id: |
| 259 |
description: |
| 260 |
- Unique ID of this mapper. |
| 261 |
type: str |
| 262 |
|
| 263 |
name: |
| 264 |
description: |
| 265 |
- Name of the mapper. |
| 266 |
type: str |
| 267 |
|
| 268 |
identityProviderAlias: |
| 269 |
description: |
| 270 |
- Alias of the identity provider for this mapper. |
| 271 |
type: str |
| 272 |
|
| 273 |
identityProviderMapper: |
| 274 |
description: |
| 275 |
- Type of mapper. |
| 276 |
type: str |
| 277 |
|
| 278 |
config: |
| 279 |
description: |
| 280 |
- Dict specifying the configuration options for the mapper; the contents differ depending on the value of O(mappers[].identityProviderMapper). |
| 281 |
type: dict |
| 282 |
|
| 283 |
extends_documentation_fragment: |
| 284 |
- community.general._keycloak |
| 285 |
- community.general._keycloak.actiongroup_keycloak |
| 286 |
- community.general._attributes |
| 287 |
|
| 288 |
author: |
| 289 |
- Laurent Paumier (@laurpaum) |
| 290 |
""" |
| 291 |
|
| 292 |
EXAMPLES = r""" |
| 293 |
- name: Create OIDC identity provider, authentication with credentials |
| 294 |
community.general.keycloak_identity_provider: |
| 295 |
state: present |
| 296 |
auth_keycloak_url: https://auth.example.com/auth |
| 297 |
auth_realm: master |
| 298 |
auth_username: admin |
| 299 |
auth_password: admin |
| 300 |
realm: myrealm |
| 301 |
alias: oidc-idp |
| 302 |
display_name: OpenID Connect IdP |
| 303 |
enabled: true |
| 304 |
provider_id: oidc |
| 305 |
config: |
| 306 |
issuer: https://idp.example.com |
| 307 |
authorizationUrl: https://idp.example.com/auth |
| 308 |
tokenUrl: https://idp.example.com/token |
| 309 |
userInfoUrl: https://idp.example.com/userinfo |
| 310 |
clientAuthMethod: client_secret_post |
| 311 |
clientId: my-client |
| 312 |
clientSecret: secret |
| 313 |
syncMode: FORCE |
| 314 |
mappers: |
| 315 |
- name: first_name |
| 316 |
identityProviderMapper: oidc-user-attribute-idp-mapper |
| 317 |
config: |
| 318 |
claim: first_name |
| 319 |
user.attribute: first_name |
| 320 |
syncMode: INHERIT |
| 321 |
- name: last_name |
| 322 |
identityProviderMapper: oidc-user-attribute-idp-mapper |
| 323 |
config: |
| 324 |
claim: last_name |
| 325 |
user.attribute: last_name |
| 326 |
syncMode: INHERIT |
| 327 |
|
| 328 |
- name: Create OIDC identity provider, with well-known configuration URL |
| 329 |
community.general.keycloak_identity_provider: |
| 330 |
state: present |
| 331 |
auth_keycloak_url: https://auth.example.com/auth |
| 332 |
auth_realm: master |
| 333 |
auth_username: admin |
| 334 |
auth_password: admin |
| 335 |
realm: myrealm |
| 336 |
alias: oidc-idp |
| 337 |
display_name: OpenID Connect IdP |
| 338 |
enabled: true |
| 339 |
provider_id: oidc |
| 340 |
config: |
| 341 |
fromUrl: https://the-idp.example.com/auth/realms/idprealm/.well-known/openid-configuration |
| 342 |
clientAuthMethod: client_secret_post |
| 343 |
clientId: my-client |
| 344 |
clientSecret: secret |
| 345 |
|
| 346 |
- name: Create SAML identity provider, authentication with credentials |
| 347 |
community.general.keycloak_identity_provider: |
| 348 |
state: present |
| 349 |
auth_keycloak_url: https://auth.example.com/auth |
| 350 |
auth_realm: master |
| 351 |
auth_username: admin |
| 352 |
auth_password: admin |
| 353 |
realm: myrealm |
| 354 |
alias: saml-idp |
| 355 |
display_name: SAML IdP |
| 356 |
enabled: true |
| 357 |
provider_id: saml |
| 358 |
config: |
| 359 |
entityId: https://auth.example.com/auth/realms/myrealm |
| 360 |
singleSignOnServiceUrl: https://idp.example.com/login |
| 361 |
wantAuthnRequestsSigned: true |
| 362 |
wantAssertionsSigned: true |
| 363 |
mappers: |
| 364 |
- name: roles |
| 365 |
identityProviderMapper: saml-user-attribute-idp-mapper |
| 366 |
config: |
| 367 |
user.attribute: roles |
| 368 |
attribute.friendly.name: User Roles |
| 369 |
attribute.name: roles |
| 370 |
syncMode: INHERIT |
| 371 |
|
| 372 |
- name: Create OIDC identity provider, authentication with credentials and advanced claim to group |
| 373 |
community.general.keycloak_identity_provider: |
| 374 |
state: present |
| 375 |
auth_keycloak_url: https://auth.example.com/auth |
| 376 |
auth_realm: master |
| 377 |
auth_username: admin |
| 378 |
auth_password: admin |
| 379 |
realm: myrealm |
| 380 |
alias: oidc-idp |
| 381 |
display_name: OpenID Connect IdP |
| 382 |
enabled: true |
| 383 |
provider_id: oidc |
| 384 |
config: |
| 385 |
issuer: https://idp.example.com |
| 386 |
authorizationUrl: https://idp.example.com/auth |
| 387 |
tokenUrl: https://idp.example.com/token |
| 388 |
userInfoUrl: https://idp.example.com/userinfo |
| 389 |
clientAuthMethod: client_secret_post |
| 390 |
clientId: my-client |
| 391 |
clientSecret: secret |
| 392 |
syncMode: FORCE |
| 393 |
mappers: |
| 394 |
- name: group_name |
| 395 |
identityProviderMapper: oidc-advanced-group-idp-mapper |
| 396 |
config: |
| 397 |
claims: '[{"key":"my_key","value":"my_value"}]' |
| 398 |
group: group_name |
| 399 |
syncMode: INHERIT |
| 400 |
""" |
| 401 |
|
| 402 |
RETURN = r""" |
| 403 |
msg: |
| 404 |
description: Message as to what action was taken. |
| 405 |
returned: always |
| 406 |
type: str |
| 407 |
sample: "Identity provider my-idp has been created" |
| 408 |
|
| 409 |
proposed: |
| 410 |
description: Representation of proposed identity provider. |
| 411 |
returned: always |
| 412 |
type: dict |
| 413 |
sample: |
| 414 |
{ |
| 415 |
"config": { |
| 416 |
"authorizationUrl": "https://idp.example.com/auth", |
| 417 |
"clientAuthMethod": "client_secret_post", |
| 418 |
"clientId": "my-client", |
| 419 |
"clientSecret": "secret", |
| 420 |
"issuer": "https://idp.example.com", |
| 421 |
"tokenUrl": "https://idp.example.com/token", |
| 422 |
"userInfoUrl": "https://idp.example.com/userinfo" |
| 423 |
}, |
| 424 |
"displayName": "OpenID Connect IdP", |
| 425 |
"providerId": "oidc" |
| 426 |
} |
| 427 |
|
| 428 |
existing: |
| 429 |
description: Representation of existing identity provider. |
| 430 |
returned: always |
| 431 |
type: dict |
| 432 |
sample: |
| 433 |
{ |
| 434 |
"addReadTokenRoleOnCreate": false, |
| 435 |
"alias": "my-idp", |
| 436 |
"authenticateByDefault": false, |
| 437 |
"config": { |
| 438 |
"authorizationUrl": "https://old.example.com/auth", |
| 439 |
"clientAuthMethod": "client_secret_post", |
| 440 |
"clientId": "my-client", |
| 441 |
"clientSecret": "**********", |
| 442 |
"issuer": "https://old.example.com", |
| 443 |
"syncMode": "FORCE", |
| 444 |
"tokenUrl": "https://old.example.com/token", |
| 445 |
"userInfoUrl": "https://old.example.com/userinfo" |
| 446 |
}, |
| 447 |
"displayName": "OpenID Connect IdP", |
| 448 |
"enabled": true, |
| 449 |
"firstBrokerLoginFlowAlias": "first broker login", |
| 450 |
"internalId": "4d28d7e3-1b80-45bb-8a30-5822bf55aa1c", |
| 451 |
"linkOnly": false, |
| 452 |
"providerId": "oidc", |
| 453 |
"storeToken": false, |
| 454 |
"trustEmail": false |
| 455 |
} |
| 456 |
|
| 457 |
end_state: |
| 458 |
description: Representation of identity provider after module execution. |
| 459 |
returned: on success |
| 460 |
type: dict |
| 461 |
sample: |
| 462 |
{ |
| 463 |
"addReadTokenRoleOnCreate": false, |
| 464 |
"alias": "my-idp", |
| 465 |
"authenticateByDefault": false, |
| 466 |
"config": { |
| 467 |
"authorizationUrl": "https://idp.example.com/auth", |
| 468 |
"clientAuthMethod": "client_secret_post", |
| 469 |
"clientId": "my-client", |
| 470 |
"clientSecret": "**********", |
| 471 |
"issuer": "https://idp.example.com", |
| 472 |
"tokenUrl": "https://idp.example.com/token", |
| 473 |
"userInfoUrl": "https://idp.example.com/userinfo" |
| 474 |
}, |
| 475 |
"displayName": "OpenID Connect IdP", |
| 476 |
"enabled": true, |
| 477 |
"firstBrokerLoginFlowAlias": "first broker login", |
| 478 |
"internalId": "4d28d7e3-1b80-45bb-8a30-5822bf55aa1c", |
| 479 |
"linkOnly": false, |
| 480 |
"providerId": "oidc", |
| 481 |
"storeToken": false, |
| 482 |
"trustEmail": false |
| 483 |
} |
| 484 |
""" |
| 485 |
|
| 486 |
from copy import deepcopy |
| 487 |
|
| 488 |
from ansible.module_utils.basic import AnsibleModule |
| 489 |
|
| 490 |
from ansible_collections.community.general.plugins.module_utils._keycloak import ( |
| 491 |
KeycloakAPI, |
| 492 |
KeycloakError, |
| 493 |
camel, |
| 494 |
get_token, |
| 495 |
keycloak_argument_spec, |
| 496 |
) |
| 497 |
|
| 498 |
|
| 499 |
def sanitize(idp): |
| 500 |
idpcopy = deepcopy(idp) |
| 501 |
if "config" in idpcopy: |
| 502 |
if "clientSecret" in idpcopy["config"]: |
| 503 |
idpcopy["config"]["clientSecret"] = "**********" |
| 504 |
return idpcopy |
| 505 |
|
| 506 |
|
| 507 |
def get_identity_provider_with_mappers(kc, alias, realm): |
| 508 |
idp = kc.get_identity_provider(alias, realm) |
| 509 |
if idp is not None: |
| 510 |
idp["mappers"] = sorted(kc.get_identity_provider_mappers(alias, realm), key=lambda x: x.get("name")) |
| 511 |
# clientSecret returned by API when using `get_identity_provider(alias, realm)` is always ********** |
| 512 |
# to detect changes to the secret, we get the actual cleartext secret from the full realm info |
| 513 |
if "config" in idp: |
| 514 |
if "clientSecret" in idp["config"]: |
| 515 |
for idp_from_realm in kc.get_realm_by_id(realm).get("identityProviders", []): |
| 516 |
if idp_from_realm["internalId"] == idp["internalId"]: |
| 517 |
cleartext_secret = idp_from_realm.get("config", {}).get("clientSecret") |
| 518 |
if cleartext_secret: |
| 519 |
idp["config"]["clientSecret"] = cleartext_secret |
| 520 |
if idp is None: |
| 521 |
idp = {} |
| 522 |
return idp |
| 523 |
|
| 524 |
|
| 525 |
def fetch_identity_provider_wellknown_config(kc, config): |
| 526 |
""" |
| 527 |
Fetches OpenID Connect well-known configuration from a given URL and updates the config dict with discovered endpoints. |
| 528 |
Support for oidc providers only. |
| 529 |
:param kc: KeycloakAPI instance used to fetch endpoints and handle errors. |
| 530 |
:param config: Dictionary containing identity provider configuration, must include 'fromUrl' key to trigger fetch. |
| 531 |
:return: None. The config dict is updated in-place. |
| 532 |
""" |
| 533 |
if config and "fromUrl" in config: |
| 534 |
if "providerId" in config and config["providerId"] != "oidc": |
| 535 |
kc.module.fail_json(msg="Only 'oidc' provider_id is supported when using 'fromUrl'.") |
| 536 |
endpoints = ["userInfoUrl", "authorizationUrl", "tokenUrl", "logoutUrl", "issuer", "jwksUrl"] |
| 537 |
if any(k in config for k in endpoints): |
| 538 |
kc.module.fail_json( |
| 539 |
msg="Cannot specify both 'fromUrl' and 'userInfoUrl', 'authorizationUrl', 'tokenUrl', 'logoutUrl', 'issuer' or 'jwksUrl'." |
| 540 |
) |
| 541 |
openIdConfig = kc.fetch_idp_endpoints_import_config_url( |
| 542 |
fromUrl=config["fromUrl"], realm=kc.module.params.get("realm", "master") |
| 543 |
) |
| 544 |
for k in endpoints: |
| 545 |
if k in openIdConfig: |
| 546 |
config[k] = openIdConfig[k] |
| 547 |
del config["fromUrl"] |
| 548 |
|
| 549 |
|
| 550 |
def main(): |
| 551 |
""" |
| 552 |
Module execution |
| 553 |
|
| 554 |
:return: |
| 555 |
""" |
| 556 |
argument_spec = keycloak_argument_spec() |
| 557 |
|
| 558 |
mapper_spec = dict( |
| 559 |
id=dict(type="str"), |
| 560 |
name=dict(type="str"), |
| 561 |
identityProviderAlias=dict(type="str"), |
| 562 |
identityProviderMapper=dict(type="str"), |
| 563 |
config=dict(type="dict"), |
| 564 |
) |
| 565 |
|
| 566 |
meta_args = dict( |
| 567 |
state=dict(type="str", default="present", choices=["present", "absent"]), |
| 568 |
realm=dict(type="str", default="master"), |
| 569 |
alias=dict(type="str", required=True), |
| 570 |
add_read_token_role_on_create=dict(type="bool", aliases=["addReadTokenRoleOnCreate"]), |
| 571 |
authenticate_by_default=dict(type="bool", aliases=["authenticateByDefault"]), |
| 572 |
config=dict(type="dict"), |
| 573 |
display_name=dict(type="str", aliases=["displayName"]), |
| 574 |
enabled=dict(type="bool"), |
| 575 |
first_broker_login_flow_alias=dict(type="str", aliases=["firstBrokerLoginFlowAlias"]), |
| 576 |
link_only=dict(type="bool", aliases=["linkOnly"]), |
| 577 |
post_broker_login_flow_alias=dict(type="str", aliases=["postBrokerLoginFlowAlias"]), |
| 578 |
provider_id=dict(type="str", aliases=["providerId"]), |
| 579 |
store_token=dict(type="bool", aliases=["storeToken"]), |
| 580 |
trust_email=dict(type="bool", aliases=["trustEmail"]), |
| 581 |
mappers=dict(type="list", elements="dict", options=mapper_spec), |
| 582 |
) |
| 583 |
|
| 584 |
argument_spec.update(meta_args) |
| 585 |
|
| 586 |
module = AnsibleModule( |
| 587 |
argument_spec=argument_spec, |
| 588 |
supports_check_mode=True, |
| 589 |
required_one_of=( |
| 590 |
[["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"]] |
| 591 |
), |
| 592 |
required_together=([["auth_username", "auth_password"]]), |
| 593 |
required_by={"refresh_token": "auth_realm"}, |
| 594 |
) |
| 595 |
|
| 596 |
result = dict(changed=False, msg="", diff={}, proposed={}, existing={}, end_state={}) |
| 597 |
|
| 598 |
# Obtain access token, initialize API |
| 599 |
try: |
| 600 |
connection_header = get_token(module.params) |
| 601 |
except KeycloakError as e: |
| 602 |
module.fail_json(msg=str(e)) |
| 603 |
|
| 604 |
kc = KeycloakAPI(module, connection_header) |
| 605 |
|
| 606 |
realm = module.params.get("realm") |
| 607 |
alias = module.params.get("alias") |
| 608 |
state = module.params.get("state") |
| 609 |
config = module.params.get("config") |
| 610 |
|
| 611 |
fetch_identity_provider_wellknown_config(kc, config) |
| 612 |
|
| 613 |
# Filter and map the parameters names that apply to the identity provider. |
| 614 |
idp_params = [ |
| 615 |
x |
| 616 |
for x in module.params |
| 617 |
if x not in list(keycloak_argument_spec().keys()) + ["state", "realm", "mappers"] |
| 618 |
and module.params.get(x) is not None |
| 619 |
] |
| 620 |
|
| 621 |
# See if it already exists in Keycloak |
| 622 |
before_idp = get_identity_provider_with_mappers(kc, alias, realm) |
| 623 |
|
| 624 |
# Build a proposed changeset from parameters given to this module |
| 625 |
changeset = {} |
| 626 |
|
| 627 |
for param in idp_params: |
| 628 |
new_param_value = module.params.get(param) |
| 629 |
old_value = before_idp[camel(param)] if camel(param) in before_idp else None |
| 630 |
if new_param_value != old_value: |
| 631 |
changeset[camel(param)] = new_param_value |
| 632 |
|
| 633 |
# special handling of mappers list to allow change detection |
| 634 |
if module.params.get("mappers") is not None: |
| 635 |
for change in module.params["mappers"]: |
| 636 |
change = {k: v for k, v in change.items() if v is not None} |
| 637 |
if change.get("id") is None and change.get("name") is None: |
| 638 |
module.fail_json(msg="Either `name` or `id` has to be specified on each mapper.") |
| 639 |
if before_idp == dict(): |
| 640 |
old_mapper = dict() |
| 641 |
elif change.get("id") is not None: |
| 642 |
old_mapper = kc.get_identity_provider_mapper(change["id"], alias, realm) |
| 643 |
if old_mapper is None: |
| 644 |
old_mapper = dict() |
| 645 |
else: |
| 646 |
found = [x for x in kc.get_identity_provider_mappers(alias, realm) if x["name"] == change["name"]] |
| 647 |
if len(found) == 1: |
| 648 |
old_mapper = found[0] |
| 649 |
else: |
| 650 |
old_mapper = dict() |
| 651 |
new_mapper = old_mapper.copy() |
| 652 |
new_mapper.update(change) |
| 653 |
|
| 654 |
if changeset.get("mappers") is None: |
| 655 |
changeset["mappers"] = list() |
| 656 |
# eventually this holds all desired mappers, unchanged, modified and newly added |
| 657 |
changeset["mappers"].append(new_mapper) |
| 658 |
|
| 659 |
# ensure idempotency in case module.params.mappers is not sorted by name |
| 660 |
changeset["mappers"] = sorted( |
| 661 |
changeset["mappers"], key=lambda x: x.get("id") if x.get("name") is None else x["name"] |
| 662 |
) |
| 663 |
|
| 664 |
# Prepare the desired values using the existing values (non-existence results in a dict that is save to use as a basis) |
| 665 |
desired_idp = before_idp.copy() |
| 666 |
desired_idp.update(changeset) |
| 667 |
|
| 668 |
result["proposed"] = sanitize(changeset) |
| 669 |
result["existing"] = sanitize(before_idp) |
| 670 |
|
| 671 |
# Cater for when it doesn't exist (an empty dict) |
| 672 |
if not before_idp: |
| 673 |
if state == "absent": |
| 674 |
# Do nothing and exit |
| 675 |
if module._diff: |
| 676 |
result["diff"] = dict(before="", after="") |
| 677 |
result["changed"] = False |
| 678 |
result["end_state"] = {} |
| 679 |
result["msg"] = "Identity provider does not exist; doing nothing." |
| 680 |
module.exit_json(**result) |
| 681 |
|
| 682 |
# Process a creation |
| 683 |
result["changed"] = True |
| 684 |
|
| 685 |
if module._diff: |
| 686 |
result["diff"] = dict(before="", after=sanitize(desired_idp)) |
| 687 |
|
| 688 |
if module.check_mode: |
| 689 |
module.exit_json(**result) |
| 690 |
|
| 691 |
# create it |
| 692 |
desired_idp = desired_idp.copy() |
| 693 |
mappers = desired_idp.pop("mappers", []) |
| 694 |
kc.create_identity_provider(desired_idp, realm) |
| 695 |
for mapper in mappers: |
| 696 |
if mapper.get("identityProviderAlias") is None: |
| 697 |
mapper["identityProviderAlias"] = alias |
| 698 |
kc.create_identity_provider_mapper(mapper, alias, realm) |
| 699 |
after_idp = get_identity_provider_with_mappers(kc, alias, realm) |
| 700 |
|
| 701 |
result["end_state"] = sanitize(after_idp) |
| 702 |
|
| 703 |
result["msg"] = f"Identity provider {alias} has been created" |
| 704 |
module.exit_json(**result) |
| 705 |
|
| 706 |
else: |
| 707 |
if state == "present": |
| 708 |
# Process an update |
| 709 |
|
| 710 |
# no changes |
| 711 |
if desired_idp == before_idp: |
| 712 |
result["changed"] = False |
| 713 |
result["end_state"] = sanitize(desired_idp) |
| 714 |
result["msg"] = f"No changes required to identity provider {alias}." |
| 715 |
module.exit_json(**result) |
| 716 |
|
| 717 |
# doing an update |
| 718 |
result["changed"] = True |
| 719 |
|
| 720 |
if module._diff: |
| 721 |
result["diff"] = dict(before=sanitize(before_idp), after=sanitize(desired_idp)) |
| 722 |
|
| 723 |
if module.check_mode: |
| 724 |
module.exit_json(**result) |
| 725 |
|
| 726 |
# do the update |
| 727 |
desired_idp = desired_idp.copy() |
| 728 |
updated_mappers = desired_idp.pop("mappers", []) |
| 729 |
original_mappers = list(before_idp.get("mappers", [])) |
| 730 |
|
| 731 |
kc.update_identity_provider(desired_idp, realm) |
| 732 |
for mapper in updated_mappers: |
| 733 |
if mapper.get("id") is not None: |
| 734 |
# only update existing if there is a change |
| 735 |
for i, orig in enumerate(original_mappers): |
| 736 |
if mapper["id"] == orig["id"]: |
| 737 |
del original_mappers[i] |
| 738 |
if mapper != orig: |
| 739 |
kc.update_identity_provider_mapper(mapper, alias, realm) |
| 740 |
else: |
| 741 |
if mapper.get("identityProviderAlias") is None: |
| 742 |
mapper["identityProviderAlias"] = alias |
| 743 |
kc.create_identity_provider_mapper(mapper, alias, realm) |
| 744 |
for mapper in [ |
| 745 |
x for x in before_idp["mappers"] if [y for y in updated_mappers if y["name"] == x["name"]] == [] |
| 746 |
]: |
| 747 |
kc.delete_identity_provider_mapper(mapper["id"], alias, realm) |
| 748 |
|
| 749 |
after_idp = get_identity_provider_with_mappers(kc, alias, realm) |
| 750 |
|
| 751 |
result["end_state"] = sanitize(after_idp) |
| 752 |
|
| 753 |
result["msg"] = f"Identity provider {alias} has been updated" |
| 754 |
module.exit_json(**result) |
| 755 |
|
| 756 |
elif state == "absent": |
| 757 |
# Process a deletion |
| 758 |
result["changed"] = True |
| 759 |
|
| 760 |
if module._diff: |
| 761 |
result["diff"] = dict(before=sanitize(before_idp), after="") |
| 762 |
|
| 763 |
if module.check_mode: |
| 764 |
module.exit_json(**result) |
| 765 |
|
| 766 |
# delete it |
| 767 |
kc.delete_identity_provider(alias, realm) |
| 768 |
|
| 769 |
result["end_state"] = {} |
| 770 |
|
| 771 |
result["msg"] = f"Identity provider {alias} has been deleted" |
| 772 |
|
| 773 |
module.exit_json(**result) |
| 774 |
|
| 775 |
|
| 776 |
if __name__ == "__main__": |
| 777 |
main() |