Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2019, Adam Goossens <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: keycloak_group
11
12 short_description: Allows administration of Keycloak groups using Keycloak API
13
14 description:
15 - This module allows you to add, remove or modify Keycloak groups using the Keycloak REST API. It requires access to the
16 REST API using OpenID Connect; the user connecting and the client being used must have the requisite access rights. In
17 a default Keycloak installation, admin-cli and an admin user would work, as would a separate client definition with the
18 scope tailored to your needs and a user having the expected roles.
19 - The names of module options are snake_cased versions of the camelCase ones found in the Keycloak API and its documentation
20 at U(https://www.keycloak.org/docs-api/20.0.2/rest-api/index.html).
21 - Attributes are multi-valued in the Keycloak API. All attributes are lists of individual values and are returned that way
22 by this module. You may pass single values for attributes when calling the module, and this is translated into a list
23 suitable for the API.
24 - When updating a group, where possible provide the group ID to the module. This removes a lookup to the API to translate
25 the name into the group ID.
26 attributes:
27 check_mode:
28 support: full
29 diff_mode:
30 support: full
31 action_group:
32 version_added: 10.2.0
33
34 options:
35 state:
36 description:
37 - State of the group.
38 - On V(present), the group is created if it does not yet exist, or updated with the parameters you provide.
39 - On V(absent), the group is removed if it exists. Be aware that absenting a group with subgroups automatically deletes
40 all its subgroups too.
41 default: 'present'
42 type: str
43 choices:
44 - present
45 - absent
46
47 name:
48 type: str
49 description:
50 - Name of the group.
51 - This parameter is required only when creating or updating the group.
52 realm:
53 type: str
54 description:
55 - They Keycloak realm under which this group resides.
56 default: 'master'
57
58 id:
59 type: str
60 description:
61 - The unique identifier for this group.
62 - This parameter is not required for updating or deleting a group but providing it reduces the number of API calls required.
63 attributes:
64 type: dict
65 description:
66 - A dict of key/value pairs to set as custom attributes for the group.
67 - Values may be single values (for example a string) or a list of strings.
68 parents:
69 version_added: "6.4.0"
70 type: list
71 description:
72 - List of parent groups for the group to handle sorted top to bottom.
73 - Set this to create a group as a subgroup of another group or groups (parents) or when accessing an existing subgroup
74 by name.
75 - Not necessary to set when accessing an existing subgroup by its C(ID) because in that case the group can be directly
76 queried without necessarily knowing its parent(s).
77 elements: dict
78 suboptions:
79 id:
80 type: str
81 description:
82 - Identify parent by ID.
83 - Needs less API calls than using O(parents[].name).
84 - A deep parent chain can be started at any point when first given parent is given as ID.
85 - Note that in principle both ID and name can be specified at the same time but current implementation only always
86 use just one of them, with ID being preferred.
87 name:
88 type: str
89 description:
90 - Identify parent by name.
91 - Needs more internal API calls than using O(parents[].id) to map names to ID's under the hood.
92 - When giving a parent chain with only names it must be complete up to the top.
93 - Note that in principle both ID and name can be specified at the same time but current implementation only always
94 use just one of them, with ID being preferred.
95 notes:
96 - Presently, the RV(end_state.realmRoles), RV(end_state.clientRoles), and RV(end_state.access) attributes returned by the
97 Keycloak API are read-only for groups. This limitation will be removed in a later version of this module.
98 extends_documentation_fragment:
99 - community.general._keycloak
100 - community.general._keycloak.actiongroup_keycloak
101 - community.general._attributes
102
103 author:
104 - Adam Goossens (@adamgoossens)
105 """
106
107 EXAMPLES = r"""
108 - name: Create a Keycloak group, authentication with credentials
109 community.general.keycloak_group:
110 name: my-new-kc-group
111 realm: MyCustomRealm
112 state: present
113 auth_client_id: admin-cli
114 auth_keycloak_url: https://auth.example.com/auth
115 auth_realm: master
116 auth_username: USERNAME
117 auth_password: PASSWORD
118 register: result_new_kcgrp
119 delegate_to: localhost
120
121 - name: Create a Keycloak group, authentication with token
122 community.general.keycloak_group:
123 name: my-new-kc-group
124 realm: MyCustomRealm
125 state: present
126 auth_client_id: admin-cli
127 auth_keycloak_url: https://auth.example.com/auth
128 token: TOKEN
129 delegate_to: localhost
130
131 - name: Delete a keycloak group
132 community.general.keycloak_group:
133 id: '9d59aa76-2755-48c6-b1af-beb70a82c3cd'
134 state: absent
135 realm: MyCustomRealm
136 auth_client_id: admin-cli
137 auth_keycloak_url: https://auth.example.com/auth
138 auth_realm: master
139 auth_username: USERNAME
140 auth_password: PASSWORD
141 delegate_to: localhost
142
143 - name: Delete a Keycloak group based on name
144 community.general.keycloak_group:
145 name: my-group-for-deletion
146 state: absent
147 auth_client_id: admin-cli
148 auth_keycloak_url: https://auth.example.com/auth
149 auth_realm: master
150 auth_username: USERNAME
151 auth_password: PASSWORD
152 delegate_to: localhost
153
154 - name: Update the name of a Keycloak group
155 community.general.keycloak_group:
156 id: '9d59aa76-2755-48c6-b1af-beb70a82c3cd'
157 name: an-updated-kc-group-name
158 state: present
159 auth_client_id: admin-cli
160 auth_keycloak_url: https://auth.example.com/auth
161 auth_realm: master
162 auth_username: USERNAME
163 auth_password: PASSWORD
164 delegate_to: localhost
165
166 - name: Create a keycloak group with some custom attributes
167 community.general.keycloak_group:
168 auth_client_id: admin-cli
169 auth_keycloak_url: https://auth.example.com/auth
170 auth_realm: master
171 auth_username: USERNAME
172 auth_password: PASSWORD
173 name: my-new_group
174 attributes:
175 attrib1: value1
176 attrib2: value2
177 attrib3:
178 - with
179 - numerous
180 - individual
181 - list
182 - items
183 delegate_to: localhost
184
185 - name: Create a Keycloak subgroup of a base group (using parent name)
186 community.general.keycloak_group:
187 name: my-new-kc-group-sub
188 realm: MyCustomRealm
189 state: present
190 auth_client_id: admin-cli
191 auth_keycloak_url: https://auth.example.com/auth
192 auth_realm: master
193 auth_username: USERNAME
194 auth_password: PASSWORD
195 parents:
196 - name: my-new-kc-group
197 register: result_new_kcgrp_sub
198 delegate_to: localhost
199
200 - name: Create a Keycloak subgroup of a base group (using parent id)
201 community.general.keycloak_group:
202 name: my-new-kc-group-sub2
203 realm: MyCustomRealm
204 state: present
205 auth_client_id: admin-cli
206 auth_keycloak_url: https://auth.example.com/auth
207 auth_realm: master
208 auth_username: USERNAME
209 auth_password: PASSWORD
210 parents:
211 - id: "{{ result_new_kcgrp.end_state.id }}"
212 delegate_to: localhost
213
214 - name: Create a Keycloak subgroup of a subgroup (using parent names)
215 community.general.keycloak_group:
216 name: my-new-kc-group-sub-sub
217 realm: MyCustomRealm
218 state: present
219 auth_client_id: admin-cli
220 auth_keycloak_url: https://auth.example.com/auth
221 auth_realm: master
222 auth_username: USERNAME
223 auth_password: PASSWORD
224 parents:
225 - name: my-new-kc-group
226 - name: my-new-kc-group-sub
227 delegate_to: localhost
228
229 - name: Create a Keycloak subgroup of a subgroup (using direct parent id)
230 community.general.keycloak_group:
231 name: my-new-kc-group-sub-sub
232 realm: MyCustomRealm
233 state: present
234 auth_client_id: admin-cli
235 auth_keycloak_url: https://auth.example.com/auth
236 auth_realm: master
237 auth_username: USERNAME
238 auth_password: PASSWORD
239 parents:
240 - id: "{{ result_new_kcgrp_sub.end_state.id }}"
241 delegate_to: localhost
242 """
243
244 RETURN = r"""
245 msg:
246 description: Message as to what action was taken.
247 returned: always
248 type: str
249
250 end_state:
251 description: Representation of the group after module execution (sample is truncated).
252 returned: on success
253 type: dict
254 contains:
255 id:
256 description: GUID that identifies the group.
257 type: str
258 returned: always
259 sample: 23f38145-3195-462c-97e7-97041ccea73e
260 name:
261 description: Name of the group.
262 type: str
263 returned: always
264 sample: grp-test-123
265 attributes:
266 description: Attributes applied to this group.
267 type: dict
268 returned: always
269 sample:
270 attr1: ["val1", "val2", "val3"]
271 path:
272 description: URI path to the group.
273 type: str
274 returned: always
275 sample: /grp-test-123
276 realmRoles:
277 description: An array of the realm-level roles granted to this group.
278 type: list
279 returned: always
280 sample: []
281 subGroups:
282 description: A list of groups that are children of this group. These groups have the same parameters as documented here.
283 type: list
284 returned: always
285 clientRoles:
286 description: A list of client-level roles granted to this group.
287 type: list
288 returned: always
289 sample: []
290 access:
291 description: A dict describing the accesses you have to this group based on the credentials used.
292 type: dict
293 returned: always
294 sample:
295 manage: true
296 manageMembership: true
297 view: true
298 """
299
300 from ansible.module_utils.basic import AnsibleModule
301
302 from ansible_collections.community.general.plugins.module_utils._keycloak import (
303 KeycloakAPI,
304 KeycloakError,
305 camel,
306 get_token,
307 keycloak_argument_spec,
308 )
309
310
311 def main():
312 """
313 Module execution
314
315 :return:
316 """
317 argument_spec = keycloak_argument_spec()
318
319 meta_args = dict(
320 state=dict(default="present", choices=["present", "absent"]),
321 realm=dict(default="master"),
322 id=dict(type="str"),
323 name=dict(type="str"),
324 attributes=dict(type="dict"),
325 parents=dict(
326 type="list",
327 elements="dict",
328 options=dict(id=dict(type="str"), name=dict(type="str")),
329 ),
330 )
331
332 argument_spec.update(meta_args)
333
334 module = AnsibleModule(
335 argument_spec=argument_spec,
336 supports_check_mode=True,
337 required_one_of=(
338 [
339 ["id", "name"],
340 ["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"],
341 ]
342 ),
343 required_together=([["auth_username", "auth_password"]]),
344 required_by={"refresh_token": "auth_realm"},
345 )
346
347 result = dict(changed=False, msg="", diff={}, group="")
348
349 # Obtain access token, initialize API
350 try:
351 connection_header = get_token(module.params)
352 except KeycloakError as e:
353 module.fail_json(msg=str(e))
354
355 kc = KeycloakAPI(module, connection_header)
356
357 realm = module.params.get("realm")
358 state = module.params.get("state")
359 gid = module.params.get("id")
360 name = module.params.get("name")
361 attributes = module.params.get("attributes")
362
363 parents = module.params.get("parents")
364
365 # attributes in Keycloak have their values returned as lists
366 # using the API. attributes is a dict, so we'll transparently convert
367 # the values to lists.
368 if attributes is not None:
369 for key, val in module.params["attributes"].items():
370 module.params["attributes"][key] = [val] if not isinstance(val, list) else val
371
372 # Filter and map the parameters names that apply to the group
373 group_params = [
374 x
375 for x in module.params
376 if x not in list(keycloak_argument_spec().keys()) + ["state", "realm", "parents"]
377 and module.params.get(x) is not None
378 ]
379
380 # See if it already exists in Keycloak
381 if gid is None:
382 before_group = kc.get_group_by_name(name, realm=realm, parents=parents)
383 else:
384 before_group = kc.get_group_by_groupid(gid, realm=realm)
385
386 if before_group is None:
387 before_group = {}
388
389 # Build a proposed changeset from parameters given to this module
390 changeset = {}
391
392 for param in group_params:
393 new_param_value = module.params.get(param)
394 old_value = before_group[param] if param in before_group else None
395 if new_param_value != old_value:
396 changeset[camel(param)] = new_param_value
397
398 # Prepare the desired values using the existing values (non-existence results in a dict that is save to use as a basis)
399 desired_group = before_group.copy()
400 desired_group.update(changeset)
401
402 # Cater for when it doesn't exist (an empty dict)
403 if not before_group:
404 if state == "absent":
405 # Do nothing and exit
406 if module._diff:
407 result["diff"] = dict(before="", after="")
408 result["changed"] = False
409 result["end_state"] = {}
410 result["msg"] = "Group does not exist; doing nothing."
411 module.exit_json(**result)
412
413 # Process a creation
414 result["changed"] = True
415
416 if name is None:
417 module.fail_json(msg="name must be specified when creating a new group")
418
419 if module._diff:
420 result["diff"] = dict(before="", after=desired_group)
421
422 if module.check_mode:
423 module.exit_json(**result)
424
425 # create it ...
426 if parents:
427 # ... as subgroup of another parent group
428 kc.create_subgroup(parents, desired_group, realm=realm)
429 else:
430 # ... as toplvl base group
431 kc.create_group(desired_group, realm=realm)
432
433 after_group = kc.get_group_by_name(name, realm, parents=parents)
434
435 result["end_state"] = after_group
436
437 result["msg"] = f"Group {after_group['name']} has been created with ID {after_group['id']}"
438 module.exit_json(**result)
439
440 else:
441 if state == "present":
442 # Process an update
443
444 # no changes
445 if desired_group == before_group:
446 result["changed"] = False
447 result["end_state"] = desired_group
448 result["msg"] = f"No changes required to group {before_group['name']}."
449 module.exit_json(**result)
450
451 # doing an update
452 result["changed"] = True
453
454 if module._diff:
455 result["diff"] = dict(before=before_group, after=desired_group)
456
457 if module.check_mode:
458 module.exit_json(**result)
459
460 # do the update
461 kc.update_group(desired_group, realm=realm)
462
463 after_group = kc.get_group_by_groupid(desired_group["id"], realm=realm)
464
465 result["end_state"] = after_group
466
467 result["msg"] = f"Group {after_group['id']} has been updated"
468 module.exit_json(**result)
469
470 else:
471 # Process a deletion (because state was not 'present')
472 result["changed"] = True
473
474 if module._diff:
475 result["diff"] = dict(before=before_group, after="")
476
477 if module.check_mode:
478 module.exit_json(**result)
479
480 # delete it
481 gid = before_group["id"]
482 kc.delete_group(groupid=gid, realm=realm)
483
484 result["end_state"] = {}
485
486 result["msg"] = f"Group {before_group['name']} has been deleted"
487
488 module.exit_json(**result)
489
490
491 if __name__ == "__main__":
492 main()