| 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_realm_rolemapping |
| 11 |
|
| 12 |
short_description: Allows administration of Keycloak realm role mappings into groups with the Keycloak API |
| 13 |
|
| 14 |
version_added: 8.2.0 |
| 15 |
|
| 16 |
description: |
| 17 |
- This module allows you to add, remove or modify Keycloak realm role mappings into groups with the Keycloak REST API. It |
| 18 |
requires access to the REST API using OpenID Connect; the user connecting and the client being used must have the requisite |
| 19 |
access rights. In a default Keycloak installation, admin-cli and an admin user would work, as would a separate client |
| 20 |
definition with 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/18.0/rest-api/index.html). |
| 23 |
- Attributes are multi-valued in the Keycloak API. All attributes are lists of individual values and are returned that way |
| 24 |
by this module. You may pass single values for attributes when calling the module, and this is translated into a list |
| 25 |
suitable for the API. |
| 26 |
- When updating a group_rolemapping, where possible provide the role ID to the module. This removes a lookup to the API |
| 27 |
to translate the name into the role ID. |
| 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_rolemapping. |
| 40 |
- On C(present), the realm_rolemapping is created if it does not yet exist, or updated with the parameters you provide. |
| 41 |
- On C(absent), the realm_rolemapping is removed if it exists. |
| 42 |
default: 'present' |
| 43 |
type: str |
| 44 |
choices: |
| 45 |
- present |
| 46 |
- absent |
| 47 |
|
| 48 |
realm: |
| 49 |
type: str |
| 50 |
description: |
| 51 |
- They Keycloak realm under which this role_representation resides. |
| 52 |
default: 'master' |
| 53 |
|
| 54 |
group_name: |
| 55 |
type: str |
| 56 |
description: |
| 57 |
- Name of the group to be mapped. |
| 58 |
- This parameter is required (can be replaced by gid for less API call). |
| 59 |
parents: |
| 60 |
type: list |
| 61 |
description: |
| 62 |
- List of parent groups for the group to handle sorted top to bottom. |
| 63 |
- Set this if your group is a subgroup and you do not provide the GID in O(gid). |
| 64 |
elements: dict |
| 65 |
suboptions: |
| 66 |
id: |
| 67 |
type: str |
| 68 |
description: |
| 69 |
- Identify parent by ID. |
| 70 |
- Needs less API calls than using O(parents[].name). |
| 71 |
- A deep parent chain can be started at any point when first given parent is given as ID. |
| 72 |
- Note that in principle both ID and name can be specified at the same time but current implementation only always |
| 73 |
use just one of them, with ID being preferred. |
| 74 |
name: |
| 75 |
type: str |
| 76 |
description: |
| 77 |
- Identify parent by name. |
| 78 |
- Needs more internal API calls than using O(parents[].id) to map names to ID's under the hood. |
| 79 |
- When giving a parent chain with only names it must be complete up to the top. |
| 80 |
- Note that in principle both ID and name can be specified at the same time but current implementation only always |
| 81 |
use just one of them, with ID being preferred. |
| 82 |
gid: |
| 83 |
type: str |
| 84 |
description: |
| 85 |
- ID of the group to be mapped. |
| 86 |
- This parameter is not required for updating or deleting the rolemapping but providing it reduces the number of API |
| 87 |
calls required. |
| 88 |
roles: |
| 89 |
description: |
| 90 |
- Roles to be mapped to the group. |
| 91 |
type: list |
| 92 |
elements: dict |
| 93 |
suboptions: |
| 94 |
name: |
| 95 |
type: str |
| 96 |
description: |
| 97 |
- Name of the role_representation. |
| 98 |
- This parameter is required only when creating or updating the role_representation. |
| 99 |
id: |
| 100 |
type: str |
| 101 |
description: |
| 102 |
- The unique identifier for this role_representation. |
| 103 |
- This parameter is not required for updating or deleting a role_representation but providing it reduces the number |
| 104 |
of API calls required. |
| 105 |
extends_documentation_fragment: |
| 106 |
- community.general._keycloak |
| 107 |
- community.general._keycloak.actiongroup_keycloak |
| 108 |
- community.general._attributes |
| 109 |
|
| 110 |
author: |
| 111 |
- Gaëtan Daubresse (@Gaetan2907) |
| 112 |
- Marius Huysamen (@mhuysamen) |
| 113 |
- Alexander Groß (@agross) |
| 114 |
""" |
| 115 |
|
| 116 |
EXAMPLES = r""" |
| 117 |
- name: Map a client role to a group, authentication with credentials |
| 118 |
community.general.keycloak_realm_rolemapping: |
| 119 |
realm: MyCustomRealm |
| 120 |
auth_client_id: admin-cli |
| 121 |
auth_keycloak_url: https://auth.example.com/auth |
| 122 |
auth_realm: master |
| 123 |
auth_username: USERNAME |
| 124 |
auth_password: PASSWORD |
| 125 |
state: present |
| 126 |
group_name: group1 |
| 127 |
roles: |
| 128 |
- name: role_name1 |
| 129 |
id: role_id1 |
| 130 |
- name: role_name2 |
| 131 |
id: role_id2 |
| 132 |
delegate_to: localhost |
| 133 |
|
| 134 |
- name: Map a client role to a group, authentication with token |
| 135 |
community.general.keycloak_realm_rolemapping: |
| 136 |
realm: MyCustomRealm |
| 137 |
auth_client_id: admin-cli |
| 138 |
auth_keycloak_url: https://auth.example.com/auth |
| 139 |
token: TOKEN |
| 140 |
state: present |
| 141 |
group_name: group1 |
| 142 |
roles: |
| 143 |
- name: role_name1 |
| 144 |
id: role_id1 |
| 145 |
- name: role_name2 |
| 146 |
id: role_id2 |
| 147 |
delegate_to: localhost |
| 148 |
|
| 149 |
- name: Map a client role to a subgroup, authentication with token |
| 150 |
community.general.keycloak_realm_rolemapping: |
| 151 |
realm: MyCustomRealm |
| 152 |
auth_client_id: admin-cli |
| 153 |
auth_keycloak_url: https://auth.example.com/auth |
| 154 |
token: TOKEN |
| 155 |
state: present |
| 156 |
group_name: subgroup1 |
| 157 |
parents: |
| 158 |
- name: parent-group |
| 159 |
roles: |
| 160 |
- name: role_name1 |
| 161 |
id: role_id1 |
| 162 |
- name: role_name2 |
| 163 |
id: role_id2 |
| 164 |
delegate_to: localhost |
| 165 |
|
| 166 |
- name: Unmap realm role from a group |
| 167 |
community.general.keycloak_realm_rolemapping: |
| 168 |
realm: MyCustomRealm |
| 169 |
auth_client_id: admin-cli |
| 170 |
auth_keycloak_url: https://auth.example.com/auth |
| 171 |
auth_realm: master |
| 172 |
auth_username: USERNAME |
| 173 |
auth_password: PASSWORD |
| 174 |
state: absent |
| 175 |
group_name: group1 |
| 176 |
roles: |
| 177 |
- name: role_name1 |
| 178 |
id: role_id1 |
| 179 |
- name: role_name2 |
| 180 |
id: role_id2 |
| 181 |
delegate_to: localhost |
| 182 |
""" |
| 183 |
|
| 184 |
RETURN = r""" |
| 185 |
msg: |
| 186 |
description: Message as to what action was taken. |
| 187 |
returned: always |
| 188 |
type: str |
| 189 |
sample: "Role role1 assigned to group group1." |
| 190 |
|
| 191 |
proposed: |
| 192 |
description: Representation of proposed client role mapping. |
| 193 |
returned: always |
| 194 |
type: dict |
| 195 |
sample: {"clientId": "test"} |
| 196 |
|
| 197 |
existing: |
| 198 |
description: |
| 199 |
- Representation of existing client role mapping. |
| 200 |
- The sample is truncated. |
| 201 |
returned: always |
| 202 |
type: dict |
| 203 |
sample: |
| 204 |
{ |
| 205 |
"adminUrl": "http://www.example.com/admin_url", |
| 206 |
"attributes": { |
| 207 |
"request.object.signature.alg": "RS256" |
| 208 |
} |
| 209 |
} |
| 210 |
|
| 211 |
end_state: |
| 212 |
description: |
| 213 |
- Representation of client role mapping after module execution. |
| 214 |
- The sample is truncated. |
| 215 |
returned: on success |
| 216 |
type: dict |
| 217 |
sample: |
| 218 |
{ |
| 219 |
"adminUrl": "http://www.example.com/admin_url", |
| 220 |
"attributes": { |
| 221 |
"request.object.signature.alg": "RS256" |
| 222 |
} |
| 223 |
} |
| 224 |
""" |
| 225 |
|
| 226 |
from ansible.module_utils.basic import AnsibleModule |
| 227 |
|
| 228 |
from ansible_collections.community.general.plugins.module_utils._keycloak import ( |
| 229 |
KeycloakAPI, |
| 230 |
KeycloakError, |
| 231 |
get_token, |
| 232 |
keycloak_argument_spec, |
| 233 |
) |
| 234 |
|
| 235 |
|
| 236 |
def main(): |
| 237 |
""" |
| 238 |
Module execution |
| 239 |
|
| 240 |
:return: |
| 241 |
""" |
| 242 |
argument_spec = keycloak_argument_spec() |
| 243 |
|
| 244 |
roles_spec = dict( |
| 245 |
name=dict(type="str"), |
| 246 |
id=dict(type="str"), |
| 247 |
) |
| 248 |
|
| 249 |
meta_args = dict( |
| 250 |
state=dict(default="present", choices=["present", "absent"]), |
| 251 |
realm=dict(default="master"), |
| 252 |
gid=dict(type="str"), |
| 253 |
group_name=dict(type="str"), |
| 254 |
parents=dict( |
| 255 |
type="list", |
| 256 |
elements="dict", |
| 257 |
options=dict(id=dict(type="str"), name=dict(type="str")), |
| 258 |
), |
| 259 |
roles=dict(type="list", elements="dict", options=roles_spec), |
| 260 |
) |
| 261 |
|
| 262 |
argument_spec.update(meta_args) |
| 263 |
|
| 264 |
module = AnsibleModule( |
| 265 |
argument_spec=argument_spec, |
| 266 |
supports_check_mode=True, |
| 267 |
required_one_of=( |
| 268 |
[["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"]] |
| 269 |
), |
| 270 |
required_together=([["auth_username", "auth_password"]]), |
| 271 |
required_by={"refresh_token": "auth_realm"}, |
| 272 |
) |
| 273 |
|
| 274 |
result = dict(changed=False, msg="", diff={}, proposed={}, existing={}, end_state={}) |
| 275 |
|
| 276 |
# Obtain access token, initialize API |
| 277 |
try: |
| 278 |
connection_header = get_token(module.params) |
| 279 |
except KeycloakError as e: |
| 280 |
module.fail_json(msg=str(e)) |
| 281 |
|
| 282 |
kc = KeycloakAPI(module, connection_header) |
| 283 |
|
| 284 |
realm = module.params.get("realm") |
| 285 |
state = module.params.get("state") |
| 286 |
gid = module.params.get("gid") |
| 287 |
group_name = module.params.get("group_name") |
| 288 |
roles = module.params.get("roles") |
| 289 |
parents = module.params.get("parents") |
| 290 |
|
| 291 |
# Check the parameters |
| 292 |
if gid is None and group_name is None: |
| 293 |
module.fail_json(msg="Either the `group_name` or `gid` has to be specified.") |
| 294 |
|
| 295 |
# Get the potential missing parameters |
| 296 |
if gid is None: |
| 297 |
group_rep = kc.get_group_by_name(group_name, realm=realm, parents=parents) |
| 298 |
if group_rep is not None: |
| 299 |
gid = group_rep["id"] |
| 300 |
else: |
| 301 |
module.fail_json(msg=f"Could not fetch group {group_name}:") |
| 302 |
else: |
| 303 |
group_rep = kc.get_group_by_groupid(gid, realm=realm) |
| 304 |
|
| 305 |
if roles is None: |
| 306 |
module.exit_json(msg="Nothing to do (no roles specified).") |
| 307 |
else: |
| 308 |
for role in roles: |
| 309 |
if role["name"] is None and role["id"] is None: |
| 310 |
module.fail_json(msg="Either the `name` or `id` has to be specified on each role.") |
| 311 |
# Fetch missing role_id |
| 312 |
if role["id"] is None: |
| 313 |
role_rep = kc.get_realm_role(role["name"], realm=realm) |
| 314 |
if role_rep is not None: |
| 315 |
role["id"] = role_rep["id"] |
| 316 |
else: |
| 317 |
module.fail_json(msg=f"Could not fetch realm role {role['name']} by name:") |
| 318 |
# Fetch missing role_name |
| 319 |
else: |
| 320 |
for realm_role in kc.get_realm_roles(realm=realm): |
| 321 |
if realm_role["id"] == role["id"]: |
| 322 |
role["name"] = realm_role["name"] |
| 323 |
break |
| 324 |
|
| 325 |
if role["name"] is None: |
| 326 |
module.fail_json(msg=f"Could not fetch realm role {role['id']} by ID") |
| 327 |
|
| 328 |
assigned_roles_before = group_rep.get("realmRoles", []) |
| 329 |
|
| 330 |
result["existing"] = assigned_roles_before |
| 331 |
result["proposed"] = list(assigned_roles_before) if assigned_roles_before else [] |
| 332 |
|
| 333 |
update_roles = [] |
| 334 |
for role in roles: |
| 335 |
# Fetch roles to assign if state present |
| 336 |
if state == "present": |
| 337 |
if any(assigned == role["name"] for assigned in assigned_roles_before): |
| 338 |
pass |
| 339 |
else: |
| 340 |
update_roles.append( |
| 341 |
{ |
| 342 |
"id": role["id"], |
| 343 |
"name": role["name"], |
| 344 |
} |
| 345 |
) |
| 346 |
result["proposed"].append(role["name"]) |
| 347 |
# Fetch roles to remove if state absent |
| 348 |
else: |
| 349 |
if any(assigned == role["name"] for assigned in assigned_roles_before): |
| 350 |
update_roles.append( |
| 351 |
{ |
| 352 |
"id": role["id"], |
| 353 |
"name": role["name"], |
| 354 |
} |
| 355 |
) |
| 356 |
if role["name"] in result["proposed"]: # Handle double removal |
| 357 |
result["proposed"].remove(role["name"]) |
| 358 |
|
| 359 |
if len(update_roles): |
| 360 |
result["changed"] = True |
| 361 |
if module._diff: |
| 362 |
result["diff"] = dict(before=assigned_roles_before, after=result["proposed"]) |
| 363 |
if module.check_mode: |
| 364 |
module.exit_json(**result) |
| 365 |
|
| 366 |
if state == "present": |
| 367 |
# Assign roles |
| 368 |
kc.add_group_realm_rolemapping(gid=gid, role_rep=update_roles, realm=realm) |
| 369 |
result["msg"] = f"Realm roles {update_roles} assigned to groupId {gid}." |
| 370 |
else: |
| 371 |
# Remove mapping of role |
| 372 |
kc.delete_group_realm_rolemapping(gid=gid, role_rep=update_roles, realm=realm) |
| 373 |
result["msg"] = f"Realm roles {update_roles} removed from groupId {gid}." |
| 374 |
|
| 375 |
if gid is None: |
| 376 |
assigned_roles_after = kc.get_group_by_name(group_name, realm=realm, parents=parents).get("realmRoles", []) |
| 377 |
else: |
| 378 |
assigned_roles_after = kc.get_group_by_groupid(gid, realm=realm).get("realmRoles", []) |
| 379 |
result["end_state"] = assigned_roles_after |
| 380 |
module.exit_json(**result) |
| 381 |
# Do nothing |
| 382 |
else: |
| 383 |
result["changed"] = False |
| 384 |
result["msg"] = ( |
| 385 |
f"Nothing to do, roles {roles} are {'mapped' if state == 'present' else 'not mapped'} with group {group_name}." |
| 386 |
) |
| 387 |
module.exit_json(**result) |
| 388 |
|
| 389 |
|
| 390 |
if __name__ == "__main__": |
| 391 |
main() |