Debian Codegraph @

ansible_collections/community/general/plugins/modules/keycloak_realm.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2017, Eike Frost <[email protected]>
4 # Copyright (c) 2021, Christophe Gilles <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: keycloak_realm
12
13 short_description: Allows administration of Keycloak realm using Keycloak API
14
15 version_added: 3.0.0
16
17 description:
18 - This module allows the administration of Keycloak realm using the Keycloak REST API. It requires access to the REST API
19 using OpenID Connect; the user connecting and the realm being used must have the requisite access rights. In a default
20 Keycloak installation, admin-cli and an admin user would work, as would a separate realm definition with the scope tailored
21 to your needs and a user having the expected roles.
22 - The names of module options are snake_cased versions of the camelCase ones found in the Keycloak API and its documentation
23 at U(https://www.keycloak.org/docs-api/8.0/rest-api/index.html). Aliases are provided so camelCased versions can be used
24 as well.
25 - The Keycloak API does not always sanity check inputs, for example you can set SAML-specific settings on an OpenID Connect
26 client for instance and also the other way around. B(Be careful). If you do not specify a setting, usually a sensible
27 default is chosen.
28 attributes:
29 check_mode:
30 support: full
31 diff_mode:
32 support: full
33 action_group:
34 version_added: 10.2.0
35
36 options:
37 state:
38 description:
39 - State of the realm.
40 - On V(present), the realm is created (or updated if it exists already).
41 - On V(absent), the realm is removed if it exists.
42 choices: ['present', 'absent']
43 default: 'present'
44 type: str
45
46 id:
47 description:
48 - The realm to create.
49 type: str
50 realm:
51 description:
52 - The realm name.
53 type: str
54 access_code_lifespan:
55 description:
56 - The realm access code lifespan.
57 aliases:
58 - accessCodeLifespan
59 type: int
60 access_code_lifespan_login:
61 description:
62 - The realm access code lifespan login.
63 aliases:
64 - accessCodeLifespanLogin
65 type: int
66 access_code_lifespan_user_action:
67 description:
68 - The realm access code lifespan user action.
69 aliases:
70 - accessCodeLifespanUserAction
71 type: int
72 access_token_lifespan:
73 description:
74 - The realm access token lifespan.
75 aliases:
76 - accessTokenLifespan
77 type: int
78 access_token_lifespan_for_implicit_flow:
79 description:
80 - The realm access token lifespan for implicit flow.
81 aliases:
82 - accessTokenLifespanForImplicitFlow
83 type: int
84 account_theme:
85 description:
86 - The realm account theme.
87 aliases:
88 - accountTheme
89 type: str
90 action_token_generated_by_admin_lifespan:
91 description:
92 - The realm action token generated by admin lifespan.
93 aliases:
94 - actionTokenGeneratedByAdminLifespan
95 type: int
96 action_token_generated_by_user_lifespan:
97 description:
98 - The realm action token generated by user lifespan.
99 aliases:
100 - actionTokenGeneratedByUserLifespan
101 type: int
102 admin_events_details_enabled:
103 description:
104 - The realm admin events details enabled.
105 aliases:
106 - adminEventsDetailsEnabled
107 type: bool
108 admin_events_enabled:
109 description:
110 - The realm admin events enabled.
111 aliases:
112 - adminEventsEnabled
113 type: bool
114 admin_permissions_enabled:
115 description:
116 - The realm admin permissions enabled.
117 aliases:
118 - adminPermissionsEnabled
119 type: bool
120 version_added: 12.0.0
121 admin_theme:
122 description:
123 - The realm admin theme.
124 aliases:
125 - adminTheme
126 type: str
127 attributes:
128 description:
129 - The realm attributes.
130 type: dict
131 browser_flow:
132 description:
133 - The realm browser flow.
134 aliases:
135 - browserFlow
136 type: str
137 browser_security_headers:
138 description:
139 - The realm browser security headers.
140 aliases:
141 - browserSecurityHeaders
142 type: dict
143 brute_force_protected:
144 description:
145 - The realm brute force protected.
146 aliases:
147 - bruteForceProtected
148 type: bool
149 brute_force_strategy:
150 description:
151 - The realm brute force strategy.
152 aliases:
153 - bruteForceStrategy
154 choices: ['LINEAR', 'MULTIPLE']
155 type: str
156 version_added: 11.2.0
157 client_authentication_flow:
158 description:
159 - The realm client authentication flow.
160 aliases:
161 - clientAuthenticationFlow
162 type: str
163 client_scope_mappings:
164 description:
165 - The realm client scope mappings.
166 aliases:
167 - clientScopeMappings
168 type: dict
169 default_default_client_scopes:
170 description:
171 - The realm default default client scopes.
172 aliases:
173 - defaultDefaultClientScopes
174 type: list
175 elements: str
176 default_groups:
177 description:
178 - The realm default groups.
179 aliases:
180 - defaultGroups
181 type: list
182 elements: str
183 default_locale:
184 description:
185 - The realm default locale.
186 aliases:
187 - defaultLocale
188 type: str
189 default_optional_client_scopes:
190 description:
191 - The realm default optional client scopes.
192 aliases:
193 - defaultOptionalClientScopes
194 type: list
195 elements: str
196 default_roles:
197 description:
198 - The realm default roles.
199 aliases:
200 - defaultRoles
201 type: list
202 elements: str
203 default_signature_algorithm:
204 description:
205 - The realm default signature algorithm.
206 aliases:
207 - defaultSignatureAlgorithm
208 type: str
209 direct_grant_flow:
210 description:
211 - The realm direct grant flow.
212 aliases:
213 - directGrantFlow
214 type: str
215 display_name:
216 description:
217 - The realm display name.
218 aliases:
219 - displayName
220 type: str
221 display_name_html:
222 description:
223 - The realm display name HTML.
224 aliases:
225 - displayNameHtml
226 type: str
227 docker_authentication_flow:
228 description:
229 - The realm docker authentication flow.
230 aliases:
231 - dockerAuthenticationFlow
232 type: str
233 duplicate_emails_allowed:
234 description:
235 - The realm duplicate emails allowed option.
236 aliases:
237 - duplicateEmailsAllowed
238 type: bool
239 edit_username_allowed:
240 description:
241 - The realm edit username allowed option.
242 aliases:
243 - editUsernameAllowed
244 type: bool
245 email_theme:
246 description:
247 - The realm email theme.
248 aliases:
249 - emailTheme
250 type: str
251 enabled:
252 description:
253 - The realm enabled option.
254 type: bool
255 enabled_event_types:
256 description:
257 - The realm enabled event types.
258 aliases:
259 - enabledEventTypes
260 type: list
261 elements: str
262 events_enabled:
263 description:
264 - Enables or disables login events for this realm.
265 aliases:
266 - eventsEnabled
267 type: bool
268 version_added: 3.6.0
269 events_expiration:
270 description:
271 - The realm events expiration.
272 aliases:
273 - eventsExpiration
274 type: int
275 events_listeners:
276 description:
277 - The realm events listeners.
278 aliases:
279 - eventsListeners
280 type: list
281 elements: str
282 failure_factor:
283 description:
284 - The realm failure factor.
285 aliases:
286 - failureFactor
287 type: int
288 first_broker_login_flow:
289 description:
290 - The realm first broker login flow.
291 aliases:
292 - firstBrokerLoginFlow
293 type: str
294 version_added: 12.5.0
295 internationalization_enabled:
296 description:
297 - The realm internationalization enabled option.
298 aliases:
299 - internationalizationEnabled
300 type: bool
301 localization_texts:
302 description:
303 - The custom localization texts for a realm.
304 aliases:
305 - localizationTexts
306 type: dict
307 version_added: 12.4.0
308 login_theme:
309 description:
310 - The realm login theme.
311 aliases:
312 - loginTheme
313 type: str
314 login_with_email_allowed:
315 description:
316 - The realm login with email allowed option.
317 aliases:
318 - loginWithEmailAllowed
319 type: bool
320 max_delta_time_seconds:
321 description:
322 - The realm max delta time in seconds.
323 aliases:
324 - maxDeltaTimeSeconds
325 type: int
326 max_failure_wait_seconds:
327 description:
328 - The realm max failure wait in seconds.
329 aliases:
330 - maxFailureWaitSeconds
331 type: int
332 max_temporary_lockouts:
333 description:
334 - The realm max temporary lockouts.
335 aliases:
336 - maxTemporaryLockouts
337 type: int
338 version_added: 11.2.0
339 minimum_quick_login_wait_seconds:
340 description:
341 - The realm minimum quick login wait in seconds.
342 aliases:
343 - minimumQuickLoginWaitSeconds
344 type: int
345 not_before:
346 description:
347 - The realm not before.
348 aliases:
349 - notBefore
350 type: int
351 offline_session_idle_timeout:
352 description:
353 - The realm offline session idle timeout.
354 aliases:
355 - offlineSessionIdleTimeout
356 type: int
357 offline_session_max_lifespan:
358 description:
359 - The realm offline session max lifespan.
360 aliases:
361 - offlineSessionMaxLifespan
362 type: int
363 offline_session_max_lifespan_enabled:
364 description:
365 - The realm offline session max lifespan enabled option.
366 aliases:
367 - offlineSessionMaxLifespanEnabled
368 type: bool
369 otp_policy_algorithm:
370 description:
371 - The realm otp policy algorithm.
372 aliases:
373 - otpPolicyAlgorithm
374 type: str
375 otp_policy_digits:
376 description:
377 - The realm otp policy digits.
378 aliases:
379 - otpPolicyDigits
380 type: int
381 otp_policy_initial_counter:
382 description:
383 - The realm otp policy initial counter.
384 aliases:
385 - otpPolicyInitialCounter
386 type: int
387 otp_policy_look_ahead_window:
388 description:
389 - The realm otp policy look ahead window.
390 aliases:
391 - otpPolicyLookAheadWindow
392 type: int
393 otp_policy_period:
394 description:
395 - The realm otp policy period.
396 aliases:
397 - otpPolicyPeriod
398 type: int
399 otp_policy_type:
400 description:
401 - The realm otp policy type.
402 aliases:
403 - otpPolicyType
404 type: str
405 otp_supported_applications:
406 description:
407 - The realm otp supported applications.
408 aliases:
409 - otpSupportedApplications
410 type: list
411 elements: str
412 password_policy:
413 description:
414 - The realm password policy.
415 aliases:
416 - passwordPolicy
417 type: str
418 organizations_enabled:
419 description:
420 - Enables support for experimental organization feature.
421 aliases:
422 - organizationsEnabled
423 type: bool
424 version_added: 10.0.0
425 permanent_lockout:
426 description:
427 - The realm permanent lockout.
428 aliases:
429 - permanentLockout
430 type: bool
431 quick_login_check_milli_seconds:
432 description:
433 - The realm quick login check in milliseconds.
434 aliases:
435 - quickLoginCheckMilliSeconds
436 type: int
437 refresh_token_max_reuse:
438 description:
439 - The realm refresh token max reuse.
440 aliases:
441 - refreshTokenMaxReuse
442 type: int
443 registration_allowed:
444 description:
445 - The realm registration allowed option.
446 aliases:
447 - registrationAllowed
448 type: bool
449 registration_email_as_username:
450 description:
451 - The realm registration email as username option.
452 aliases:
453 - registrationEmailAsUsername
454 type: bool
455 registration_flow:
456 description:
457 - The realm registration flow.
458 aliases:
459 - registrationFlow
460 type: str
461 remember_me:
462 description:
463 - The realm remember me option.
464 aliases:
465 - rememberMe
466 type: bool
467 reset_credentials_flow:
468 description:
469 - The realm reset credentials flow.
470 aliases:
471 - resetCredentialsFlow
472 type: str
473 reset_password_allowed:
474 description:
475 - The realm reset password allowed option.
476 aliases:
477 - resetPasswordAllowed
478 type: bool
479 revoke_refresh_token:
480 description:
481 - The realm revoke refresh token option.
482 aliases:
483 - revokeRefreshToken
484 type: bool
485 smtp_server:
486 description:
487 - The realm smtp server.
488 aliases:
489 - smtpServer
490 type: dict
491 ssl_required:
492 description:
493 - The realm ssl required option.
494 choices: ['all', 'external', 'none']
495 aliases:
496 - sslRequired
497 type: str
498 sso_session_idle_timeout:
499 description:
500 - The realm sso session idle timeout.
501 aliases:
502 - ssoSessionIdleTimeout
503 type: int
504 sso_session_idle_timeout_remember_me:
505 description:
506 - The realm sso session idle timeout remember me.
507 aliases:
508 - ssoSessionIdleTimeoutRememberMe
509 type: int
510 sso_session_max_lifespan:
511 description:
512 - The realm sso session max lifespan.
513 aliases:
514 - ssoSessionMaxLifespan
515 type: int
516 sso_session_max_lifespan_remember_me:
517 description:
518 - The realm sso session max lifespan remember me.
519 aliases:
520 - ssoSessionMaxLifespanRememberMe
521 type: int
522 supported_locales:
523 description:
524 - The realm supported locales.
525 aliases:
526 - supportedLocales
527 type: list
528 elements: str
529 user_managed_access_allowed:
530 description:
531 - The realm user managed access allowed option.
532 aliases:
533 - userManagedAccessAllowed
534 type: bool
535 verify_email:
536 description:
537 - The realm verify email option.
538 aliases:
539 - verifyEmail
540 type: bool
541 wait_increment_seconds:
542 description:
543 - The realm wait increment in seconds.
544 aliases:
545 - waitIncrementSeconds
546 type: int
547 client_session_idle_timeout:
548 description:
549 - All Clients inherit from this setting, time a session is allowed to be idle before it expires.
550 aliases:
551 - clientSessionIdleTimeout
552 type: int
553 version_added: 11.2.0
554 client_session_max_lifespan:
555 description:
556 - All Clients inherit from this setting, max time before a session is expired.
557 aliases:
558 - clientSessionMaxLifespan
559 type: int
560 version_added: 11.2.0
561 client_offline_session_idle_timeout:
562 description:
563 - All Clients inherit from this setting, time an offline session is allowed to be idle before it expires.
564 aliases:
565 - clientOfflineSessionIdleTimeout
566 type: int
567 version_added: 11.2.0
568 client_offline_session_max_lifespan:
569 description:
570 - All Clients inherit from this setting, max time before an offline session is expired regardless of activity.
571 aliases:
572 - clientOfflineSessionMaxLifespan
573 type: int
574 version_added: 11.2.0
575 oauth2_device_code_lifespan:
576 description:
577 - Max time before the device code and user code are expired.
578 aliases:
579 - oauth2DeviceCodeLifespan
580 type: int
581 version_added: 11.2.0
582 oauth2_device_polling_interval:
583 description:
584 - The minimum amount of time in seconds that the client should wait between polling requests to the token endpoint.
585 aliases:
586 - oauth2DevicePollingInterval
587 type: int
588 version_added: 11.2.0
589 web_authn_policy_rp_entity_name:
590 description:
591 - WebAuthn Relying Party Entity Name.
592 aliases:
593 - webAuthnPolicyRpEntityName
594 type: str
595 version_added: 11.3.0
596 web_authn_policy_signature_algorithms:
597 description:
598 - List of acceptable WebAuthn signature algorithms.
599 aliases:
600 - webAuthnPolicySignatureAlgorithms
601 type: list
602 version_added: 11.3.0
603 elements: str
604 web_authn_policy_rp_id:
605 description:
606 - WebAuthn Relying Party ID (domain). Empty string means use request host.
607 aliases:
608 - webAuthnPolicyRpId
609 type: str
610 version_added: 11.3.0
611 web_authn_policy_attestation_conveyance_preference:
612 description:
613 - Attestation conveyance preference for WebAuthn.
614 aliases:
615 - webAuthnPolicyAttestationConveyancePreference
616 type: str
617 version_added: 11.3.0
618 web_authn_policy_authenticator_attachment:
619 description:
620 - Authenticator attachment preference for WebAuthn authenticators.
621 aliases:
622 - webAuthnPolicyAuthenticatorAttachment
623 type: str
624 version_added: 11.3.0
625 web_authn_policy_require_resident_key:
626 description:
627 - Whether resident keys are required for WebAuthn (Yes/No/not specified).
628 aliases:
629 - webAuthnPolicyRequireResidentKey
630 type: str
631 version_added: 11.3.0
632 web_authn_policy_user_verification_requirement:
633 description:
634 - User verification requirement for WebAuthn.
635 aliases:
636 - webAuthnPolicyUserVerificationRequirement
637 type: str
638 version_added: 11.3.0
639 web_authn_policy_create_timeout:
640 description:
641 - Timeout for WebAuthn credential creation (ms).
642 aliases:
643 - webAuthnPolicyCreateTimeout
644 type: int
645 version_added: 11.3.0
646 web_authn_policy_avoid_same_authenticator_register:
647 description:
648 - Avoid registering the same authenticator multiple times.
649 aliases:
650 - webAuthnPolicyAvoidSameAuthenticatorRegister
651 type: bool
652 version_added: 11.3.0
653 web_authn_policy_acceptable_aaguids:
654 description:
655 - List of acceptable AAGUIDs for WebAuthn authenticators.
656 aliases:
657 - webAuthnPolicyAcceptableAaguids
658 type: list
659 version_added: 11.3.0
660 elements: str
661 web_authn_policy_extra_origins:
662 description:
663 - Additional acceptable origins for WebAuthn requests.
664 aliases:
665 - webAuthnPolicyExtraOrigins
666 type: list
667 version_added: 11.3.0
668 elements: str
669 web_authn_policy_passwordless_rp_entity_name:
670 description:
671 - WebAuthn Passwordless Relying Party Entity Name.
672 aliases:
673 - webAuthnPolicyPasswordlessRpEntityName
674 type: str
675 version_added: 11.3.0
676 web_authn_policy_passwordless_signature_algorithms:
677 description:
678 - List of acceptable WebAuthn signature algorithms for passwordless.
679 aliases:
680 - webAuthnPolicyPasswordlessSignatureAlgorithms
681 type: list
682 version_added: 11.3.0
683 elements: str
684 web_authn_policy_passwordless_rp_id:
685 description:
686 - WebAuthn Passwordless Relying Party ID (domain).
687 aliases:
688 - webAuthnPolicyPasswordlessRpId
689 type: str
690 version_added: 11.3.0
691 web_authn_policy_passwordless_attestation_conveyance_preference:
692 description:
693 - Attestation conveyance preference for WebAuthn passwordless.
694 aliases:
695 - webAuthnPolicyPasswordlessAttestationConveyancePreference
696 type: str
697 version_added: 11.3.0
698 web_authn_policy_passwordless_authenticator_attachment:
699 description:
700 - Authenticator attachment for WebAuthn passwordless.
701 aliases:
702 - webAuthnPolicyPasswordlessAuthenticatorAttachment
703 type: str
704 version_added: 11.3.0
705 web_authn_policy_passwordless_require_resident_key:
706 description:
707 - Whether resident keys are required for WebAuthn passwordless (V(Yes)/V(No)/V(not specified)).
708 aliases:
709 - webAuthnPolicyPasswordlessRequireResidentKey
710 type: str
711 version_added: 11.3.0
712 web_authn_policy_passwordless_user_verification_requirement:
713 description:
714 - User verification requirement for WebAuthn passwordless.
715 aliases:
716 - webAuthnPolicyPasswordlessUserVerificationRequirement
717 type: str
718 version_added: 11.3.0
719 web_authn_policy_passwordless_create_timeout:
720 description:
721 - Timeout for WebAuthn passwordless credential creation (ms).
722 aliases:
723 - webAuthnPolicyPasswordlessCreateTimeout
724 type: int
725 version_added: 11.3.0
726 web_authn_policy_passwordless_avoid_same_authenticator_register:
727 description:
728 - Avoid registering the same authenticator multiple times for passwordless.
729 aliases:
730 - webAuthnPolicyPasswordlessAvoidSameAuthenticatorRegister
731 type: bool
732 version_added: 11.3.0
733 web_authn_policy_passwordless_acceptable_aaguids:
734 description:
735 - List of acceptable AAGUIDs for WebAuthn passwordless authenticators.
736 aliases:
737 - webAuthnPolicyPasswordlessAcceptableAaguids
738 type: list
739 version_added: 11.3.0
740 elements: str
741 web_authn_policy_passwordless_extra_origins:
742 description:
743 - Additional acceptable origins for WebAuthn passwordless requests.
744 aliases:
745 - webAuthnPolicyPasswordlessExtraOrigins
746 type: list
747 version_added: 11.3.0
748 elements: str
749 web_authn_policy_passwordless_passkeys_enabled:
750 description:
751 - Enable passkeys (conditional UI) authentication in the username forms.
752 aliases:
753 - webAuthnPolicyPasswordlessPasskeysEnabled
754 type: bool
755 version_added: 12.1.0
756
757 extends_documentation_fragment:
758 - community.general._keycloak
759 - community.general._keycloak.actiongroup_keycloak
760 - community.general._attributes
761
762 author:
763 - Christophe Gilles (@kris2kris)
764 """
765
766 EXAMPLES = r"""
767 - name: Create or update Keycloak realm (minimal example)
768 community.general.keycloak_realm:
769 auth_client_id: admin-cli
770 auth_keycloak_url: https://auth.example.com/auth
771 auth_realm: master
772 auth_username: USERNAME
773 auth_password: PASSWORD
774 realm: unique_realm_name
775 state: present
776
777 - name: Delete a Keycloak realm
778 community.general.keycloak_realm:
779 auth_client_id: admin-cli
780 auth_keycloak_url: https://auth.example.com/auth
781 auth_realm: master
782 auth_username: USERNAME
783 auth_password: PASSWORD
784 realm: unique_realm_name
785 state: absent
786 """
787
788 RETURN = r"""
789 msg:
790 description: Message as to what action was taken.
791 returned: always
792 type: str
793 sample: "Realm testrealm has been updated"
794
795 proposed:
796 description: Representation of proposed realm.
797 returned: always
798 type: dict
799 sample: {"realm": "test"}
800
801 existing:
802 description: Representation of existing realm (sample is truncated).
803 returned: always
804 type: dict
805 sample:
806 {
807 "adminUrl": "http://www.example.com/admin_url",
808 "attributes": {
809 "request.object.signature.alg": "RS256"
810 }
811 }
812
813 end_state:
814 description: Representation of realm after module execution (sample is truncated).
815 returned: on success
816 type: dict
817 sample:
818 {
819 "adminUrl": "http://www.example.com/admin_url",
820 "attributes": {
821 "request.object.signature.alg": "RS256"
822 }
823 }
824 """
825
826 from ansible.module_utils.basic import AnsibleModule
827
828 from ansible_collections.community.general.plugins.module_utils._keycloak import (
829 KeycloakAPI,
830 KeycloakError,
831 camel,
832 get_token,
833 keycloak_argument_spec,
834 )
835
836
837 def normalise_cr(realmrep):
838 """Re-sorts any properties where the order is important so that diff's is minimised and the change detection is more effective.
839
840 :param realmrep: the realmrep dict to be sanitized
841 :return: normalised realmrep dict
842 """
843 # Avoid the dict passed in to be modified
844 realmrep = realmrep.copy()
845
846 if "enabledEventTypes" in realmrep:
847 realmrep["enabledEventTypes"] = list(sorted(realmrep["enabledEventTypes"]))
848
849 if "otpSupportedApplications" in realmrep:
850 realmrep["otpSupportedApplications"] = list(sorted(realmrep["otpSupportedApplications"]))
851
852 if "supportedLocales" in realmrep:
853 realmrep["supportedLocales"] = list(sorted(realmrep["supportedLocales"]))
854
855 return realmrep
856
857
858 def sanitize_cr(realmrep):
859 """Removes probably sensitive details from a realm representation.
860
861 :param realmrep: the realmrep dict to be sanitized
862 :return: sanitized realmrep dict
863 """
864 if not realmrep:
865 return realmrep
866
867 result = realmrep.copy()
868 if "secret" in result:
869 result["secret"] = "********"
870 if "attributes" in result:
871 if "saml.signing.private.key" in result["attributes"]:
872 result["attributes"] = result["attributes"].copy()
873 result["attributes"]["saml.signing.private.key"] = "********"
874 return normalise_cr(result)
875
876
877 def main():
878 """
879 Module execution
880
881 :return:
882 """
883 argument_spec = keycloak_argument_spec()
884
885 meta_args = dict(
886 state=dict(default="present", choices=["present", "absent"]),
887 id=dict(type="str"),
888 realm=dict(type="str"),
889 access_code_lifespan=dict(type="int", aliases=["accessCodeLifespan"]),
890 access_code_lifespan_login=dict(type="int", aliases=["accessCodeLifespanLogin"]),
891 access_code_lifespan_user_action=dict(type="int", aliases=["accessCodeLifespanUserAction"]),
892 access_token_lifespan=dict(type="int", aliases=["accessTokenLifespan"], no_log=False),
893 access_token_lifespan_for_implicit_flow=dict(
894 type="int", aliases=["accessTokenLifespanForImplicitFlow"], no_log=False
895 ),
896 account_theme=dict(type="str", aliases=["accountTheme"]),
897 action_token_generated_by_admin_lifespan=dict(
898 type="int", aliases=["actionTokenGeneratedByAdminLifespan"], no_log=False
899 ),
900 action_token_generated_by_user_lifespan=dict(
901 type="int", aliases=["actionTokenGeneratedByUserLifespan"], no_log=False
902 ),
903 admin_events_details_enabled=dict(type="bool", aliases=["adminEventsDetailsEnabled"]),
904 admin_events_enabled=dict(type="bool", aliases=["adminEventsEnabled"]),
905 admin_permissions_enabled=dict(type="bool", aliases=["adminPermissionsEnabled"]),
906 admin_theme=dict(type="str", aliases=["adminTheme"]),
907 attributes=dict(type="dict"),
908 browser_flow=dict(type="str", aliases=["browserFlow"]),
909 browser_security_headers=dict(type="dict", aliases=["browserSecurityHeaders"]),
910 brute_force_protected=dict(type="bool", aliases=["bruteForceProtected"]),
911 brute_force_strategy=dict(type="str", choices=["LINEAR", "MULTIPLE"], aliases=["bruteForceStrategy"]),
912 client_authentication_flow=dict(type="str", aliases=["clientAuthenticationFlow"]),
913 client_scope_mappings=dict(type="dict", aliases=["clientScopeMappings"]),
914 default_default_client_scopes=dict(type="list", elements="str", aliases=["defaultDefaultClientScopes"]),
915 default_groups=dict(type="list", elements="str", aliases=["defaultGroups"]),
916 default_locale=dict(type="str", aliases=["defaultLocale"]),
917 default_optional_client_scopes=dict(type="list", elements="str", aliases=["defaultOptionalClientScopes"]),
918 default_roles=dict(type="list", elements="str", aliases=["defaultRoles"]),
919 default_signature_algorithm=dict(type="str", aliases=["defaultSignatureAlgorithm"]),
920 direct_grant_flow=dict(type="str", aliases=["directGrantFlow"]),
921 display_name=dict(type="str", aliases=["displayName"]),
922 display_name_html=dict(type="str", aliases=["displayNameHtml"]),
923 docker_authentication_flow=dict(type="str", aliases=["dockerAuthenticationFlow"]),
924 duplicate_emails_allowed=dict(type="bool", aliases=["duplicateEmailsAllowed"]),
925 edit_username_allowed=dict(type="bool", aliases=["editUsernameAllowed"]),
926 email_theme=dict(type="str", aliases=["emailTheme"]),
927 enabled=dict(type="bool"),
928 enabled_event_types=dict(type="list", elements="str", aliases=["enabledEventTypes"]),
929 events_enabled=dict(type="bool", aliases=["eventsEnabled"]),
930 events_expiration=dict(type="int", aliases=["eventsExpiration"]),
931 events_listeners=dict(type="list", elements="str", aliases=["eventsListeners"]),
932 failure_factor=dict(type="int", aliases=["failureFactor"]),
933 first_broker_login_flow=dict(type="str", aliases=["firstBrokerLoginFlow"]),
934 internationalization_enabled=dict(type="bool", aliases=["internationalizationEnabled"]),
935 localization_texts=dict(type="dict", aliases=["localizationTexts"]),
936 login_theme=dict(type="str", aliases=["loginTheme"]),
937 login_with_email_allowed=dict(type="bool", aliases=["loginWithEmailAllowed"]),
938 max_delta_time_seconds=dict(type="int", aliases=["maxDeltaTimeSeconds"]),
939 max_failure_wait_seconds=dict(type="int", aliases=["maxFailureWaitSeconds"]),
940 max_temporary_lockouts=dict(type="int", aliases=["maxTemporaryLockouts"]),
941 minimum_quick_login_wait_seconds=dict(type="int", aliases=["minimumQuickLoginWaitSeconds"]),
942 not_before=dict(type="int", aliases=["notBefore"]),
943 offline_session_idle_timeout=dict(type="int", aliases=["offlineSessionIdleTimeout"]),
944 offline_session_max_lifespan=dict(type="int", aliases=["offlineSessionMaxLifespan"]),
945 offline_session_max_lifespan_enabled=dict(type="bool", aliases=["offlineSessionMaxLifespanEnabled"]),
946 otp_policy_algorithm=dict(type="str", aliases=["otpPolicyAlgorithm"]),
947 otp_policy_digits=dict(type="int", aliases=["otpPolicyDigits"]),
948 otp_policy_initial_counter=dict(type="int", aliases=["otpPolicyInitialCounter"]),
949 otp_policy_look_ahead_window=dict(type="int", aliases=["otpPolicyLookAheadWindow"]),
950 otp_policy_period=dict(type="int", aliases=["otpPolicyPeriod"]),
951 otp_policy_type=dict(type="str", aliases=["otpPolicyType"]),
952 otp_supported_applications=dict(type="list", elements="str", aliases=["otpSupportedApplications"]),
953 password_policy=dict(type="str", aliases=["passwordPolicy"], no_log=False),
954 organizations_enabled=dict(type="bool", aliases=["organizationsEnabled"]),
955 permanent_lockout=dict(type="bool", aliases=["permanentLockout"]),
956 quick_login_check_milli_seconds=dict(type="int", aliases=["quickLoginCheckMilliSeconds"]),
957 refresh_token_max_reuse=dict(type="int", aliases=["refreshTokenMaxReuse"], no_log=False),
958 registration_allowed=dict(type="bool", aliases=["registrationAllowed"]),
959 registration_email_as_username=dict(type="bool", aliases=["registrationEmailAsUsername"]),
960 registration_flow=dict(type="str", aliases=["registrationFlow"]),
961 remember_me=dict(type="bool", aliases=["rememberMe"]),
962 reset_credentials_flow=dict(type="str", aliases=["resetCredentialsFlow"]),
963 reset_password_allowed=dict(type="bool", aliases=["resetPasswordAllowed"], no_log=False),
964 revoke_refresh_token=dict(type="bool", aliases=["revokeRefreshToken"]),
965 smtp_server=dict(type="dict", aliases=["smtpServer"]),
966 ssl_required=dict(choices=["external", "all", "none"], aliases=["sslRequired"]),
967 sso_session_idle_timeout=dict(type="int", aliases=["ssoSessionIdleTimeout"]),
968 sso_session_idle_timeout_remember_me=dict(type="int", aliases=["ssoSessionIdleTimeoutRememberMe"]),
969 sso_session_max_lifespan=dict(type="int", aliases=["ssoSessionMaxLifespan"]),
970 sso_session_max_lifespan_remember_me=dict(type="int", aliases=["ssoSessionMaxLifespanRememberMe"]),
971 supported_locales=dict(type="list", elements="str", aliases=["supportedLocales"]),
972 user_managed_access_allowed=dict(type="bool", aliases=["userManagedAccessAllowed"]),
973 verify_email=dict(type="bool", aliases=["verifyEmail"]),
974 wait_increment_seconds=dict(type="int", aliases=["waitIncrementSeconds"]),
975 client_session_idle_timeout=dict(type="int", aliases=["clientSessionIdleTimeout"]),
976 client_session_max_lifespan=dict(type="int", aliases=["clientSessionMaxLifespan"]),
977 client_offline_session_idle_timeout=dict(type="int", aliases=["clientOfflineSessionIdleTimeout"]),
978 client_offline_session_max_lifespan=dict(type="int", aliases=["clientOfflineSessionMaxLifespan"]),
979 oauth2_device_code_lifespan=dict(type="int", aliases=["oauth2DeviceCodeLifespan"]),
980 oauth2_device_polling_interval=dict(type="int", aliases=["oauth2DevicePollingInterval"]),
981 web_authn_policy_rp_entity_name=dict(type="str", aliases=["webAuthnPolicyRpEntityName"]),
982 web_authn_policy_signature_algorithms=dict(
983 type="list", elements="str", aliases=["webAuthnPolicySignatureAlgorithms"]
984 ),
985 web_authn_policy_rp_id=dict(type="str", aliases=["webAuthnPolicyRpId"]),
986 web_authn_policy_attestation_conveyance_preference=dict(
987 type="str", aliases=["webAuthnPolicyAttestationConveyancePreference"]
988 ),
989 web_authn_policy_authenticator_attachment=dict(type="str", aliases=["webAuthnPolicyAuthenticatorAttachment"]),
990 web_authn_policy_require_resident_key=dict(
991 type="str", aliases=["webAuthnPolicyRequireResidentKey"], no_log=False
992 ),
993 web_authn_policy_user_verification_requirement=dict(
994 type="str", aliases=["webAuthnPolicyUserVerificationRequirement"]
995 ),
996 web_authn_policy_create_timeout=dict(type="int", aliases=["webAuthnPolicyCreateTimeout"]),
997 web_authn_policy_avoid_same_authenticator_register=dict(
998 type="bool", aliases=["webAuthnPolicyAvoidSameAuthenticatorRegister"]
999 ),
1000 web_authn_policy_acceptable_aaguids=dict(
1001 type="list", elements="str", aliases=["webAuthnPolicyAcceptableAaguids"]
1002 ),
1003 web_authn_policy_extra_origins=dict(type="list", elements="str", aliases=["webAuthnPolicyExtraOrigins"]),
1004 web_authn_policy_passwordless_rp_entity_name=dict(
1005 type="str", aliases=["webAuthnPolicyPasswordlessRpEntityName"]
1006 ),
1007 web_authn_policy_passwordless_signature_algorithms=dict(
1008 type="list", elements="str", aliases=["webAuthnPolicyPasswordlessSignatureAlgorithms"], no_log=False
1009 ),
1010 web_authn_policy_passwordless_rp_id=dict(type="str", aliases=["webAuthnPolicyPasswordlessRpId"]),
1011 web_authn_policy_passwordless_attestation_conveyance_preference=dict(
1012 type="str", aliases=["webAuthnPolicyPasswordlessAttestationConveyancePreference"], no_log=False
1013 ),
1014 web_authn_policy_passwordless_authenticator_attachment=dict(
1015 type="str", aliases=["webAuthnPolicyPasswordlessAuthenticatorAttachment"], no_log=False
1016 ),
1017 web_authn_policy_passwordless_require_resident_key=dict(
1018 type="str", aliases=["webAuthnPolicyPasswordlessRequireResidentKey"], no_log=False
1019 ),
1020 web_authn_policy_passwordless_user_verification_requirement=dict(
1021 type="str", aliases=["webAuthnPolicyPasswordlessUserVerificationRequirement"], no_log=False
1022 ),
1023 web_authn_policy_passwordless_create_timeout=dict(
1024 type="int", aliases=["webAuthnPolicyPasswordlessCreateTimeout"]
1025 ),
1026 web_authn_policy_passwordless_avoid_same_authenticator_register=dict(
1027 type="bool", aliases=["webAuthnPolicyPasswordlessAvoidSameAuthenticatorRegister"]
1028 ),
1029 web_authn_policy_passwordless_acceptable_aaguids=dict(
1030 type="list", elements="str", aliases=["webAuthnPolicyPasswordlessAcceptableAaguids"], no_log=False
1031 ),
1032 web_authn_policy_passwordless_extra_origins=dict(
1033 type="list", elements="str", aliases=["webAuthnPolicyPasswordlessExtraOrigins"], no_log=False
1034 ),
1035 web_authn_policy_passwordless_passkeys_enabled=dict(
1036 type="bool", aliases=["webAuthnPolicyPasswordlessPasskeysEnabled"]
1037 ),
1038 )
1039
1040 argument_spec.update(meta_args)
1041
1042 module = AnsibleModule(
1043 argument_spec=argument_spec,
1044 supports_check_mode=True,
1045 required_one_of=(
1046 [
1047 ["id", "realm", "enabled"],
1048 ["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"],
1049 ]
1050 ),
1051 required_together=([["auth_username", "auth_password"]]),
1052 required_by={"refresh_token": "auth_realm"},
1053 )
1054
1055 result = dict(changed=False, msg="", diff={}, proposed={}, existing={}, end_state={})
1056
1057 # Obtain access token, initialize API
1058 try:
1059 connection_header = get_token(module.params)
1060 except KeycloakError as e:
1061 module.fail_json(msg=str(e))
1062
1063 kc = KeycloakAPI(module, connection_header)
1064
1065 realm = module.params.get("realm")
1066 state = module.params.get("state")
1067
1068 # convert module parameters to realm representation parameters (if they belong in there)
1069 params_to_ignore = list(keycloak_argument_spec().keys()) + ["state"]
1070
1071 # Filter and map the parameters names that apply to the role
1072 realm_params = [x for x in module.params if x not in params_to_ignore and module.params.get(x) is not None]
1073
1074 # See whether the realm already exists in Keycloak
1075 before_realm = kc.get_realm_by_id(realm=realm)
1076
1077 if before_realm is None:
1078 before_realm = {}
1079
1080 # Build a proposed changeset from parameters given to this module
1081 changeset = {}
1082
1083 for realm_param in realm_params:
1084 new_param_value = module.params.get(realm_param)
1085 changeset[camel(realm_param)] = new_param_value
1086
1087 # Prepare the desired values using the existing values (non-existence results in a dict that is save to use as a basis)
1088 desired_realm = before_realm.copy()
1089 desired_realm.update(changeset)
1090
1091 result["proposed"] = sanitize_cr(changeset)
1092 before_realm_sanitized = sanitize_cr(before_realm)
1093 result["existing"] = before_realm_sanitized
1094
1095 # Cater for when it doesn't exist (an empty dict)
1096 if not before_realm:
1097 if state == "absent":
1098 # Do nothing and exit
1099 if module._diff:
1100 result["diff"] = dict(before="", after="")
1101 result["changed"] = False
1102 result["end_state"] = {}
1103 result["msg"] = "Realm does not exist, doing nothing."
1104 module.exit_json(**result)
1105
1106 # Process a creation
1107 result["changed"] = True
1108
1109 if module._diff:
1110 result["diff"] = dict(before="", after=sanitize_cr(desired_realm))
1111
1112 if module.check_mode:
1113 module.exit_json(**result)
1114
1115 # create it
1116 kc.create_realm(desired_realm)
1117 after_realm = kc.get_realm_by_id(desired_realm["realm"])
1118
1119 result["end_state"] = sanitize_cr(after_realm)
1120
1121 result["msg"] = f"Realm {desired_realm['realm']} has been created."
1122 module.exit_json(**result)
1123
1124 else:
1125 if state == "present":
1126 # Process an update
1127
1128 # doing an update
1129 result["changed"] = True
1130 if module.check_mode:
1131 # We can only compare the current realm with the proposed updates we have
1132 before_norm = normalise_cr(before_realm)
1133 desired_norm = normalise_cr(desired_realm)
1134 if module._diff:
1135 result["diff"] = dict(before=sanitize_cr(before_norm), after=sanitize_cr(desired_norm))
1136 result["changed"] = before_norm != desired_norm
1137
1138 module.exit_json(**result)
1139
1140 # do the update
1141 kc.update_realm(desired_realm, realm=realm)
1142
1143 after_realm = kc.get_realm_by_id(realm=realm)
1144
1145 if before_realm == after_realm:
1146 result["changed"] = False
1147
1148 result["end_state"] = sanitize_cr(after_realm)
1149
1150 if module._diff:
1151 result["diff"] = dict(before=before_realm_sanitized, after=sanitize_cr(after_realm))
1152
1153 result["msg"] = f"Realm {desired_realm['realm']} has been updated."
1154 module.exit_json(**result)
1155
1156 else:
1157 # Process a deletion (because state was not 'present')
1158 result["changed"] = True
1159
1160 if module._diff:
1161 result["diff"] = dict(before=before_realm_sanitized, after="")
1162
1163 if module.check_mode:
1164 module.exit_json(**result)
1165
1166 # delete it
1167 kc.delete_realm(realm=realm)
1168
1169 result["proposed"] = {}
1170 result["end_state"] = {}
1171
1172 result["msg"] = f"Realm {before_realm['realm']} has been deleted."
1173
1174 module.exit_json(**result)
1175
1176
1177 if __name__ == "__main__":
1178 main()