| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2020, Zainab Alsaffar <[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: gitlab_group_members |
| 11 |
short_description: Manage group members on GitLab Server |
| 12 |
description: |
| 13 |
- This module allows to add and remove members to/from a group, or change a member's access level in a group on GitLab. |
| 14 |
version_added: '1.2.0' |
| 15 |
author: Zainab Alsaffar (@zanssa) |
| 16 |
requirements: |
| 17 |
- python-gitlab python module <= 1.15.0 |
| 18 |
- administrator rights on the GitLab server |
| 19 |
extends_documentation_fragment: |
| 20 |
- community.general._auth_basic |
| 21 |
- community.general._gitlab |
| 22 |
- community.general._attributes |
| 23 |
|
| 24 |
attributes: |
| 25 |
check_mode: |
| 26 |
support: full |
| 27 |
diff_mode: |
| 28 |
support: none |
| 29 |
|
| 30 |
options: |
| 31 |
gitlab_group: |
| 32 |
description: |
| 33 |
- The C(full_path) of the GitLab group the member is added to/removed from. |
| 34 |
- Setting this to C(name) or C(path) has been disallowed since community.general 6.0.0. Use C(full_path) instead. |
| 35 |
required: true |
| 36 |
type: str |
| 37 |
gitlab_user: |
| 38 |
description: |
| 39 |
- A username or a list of usernames to add to/remove from the GitLab group. |
| 40 |
- Mutually exclusive with O(gitlab_users_access). |
| 41 |
type: list |
| 42 |
elements: str |
| 43 |
access_level: |
| 44 |
description: |
| 45 |
- The access level for the user. |
| 46 |
- Required if O(state=present), user state is set to present. |
| 47 |
- Mutually exclusive with O(gitlab_users_access). |
| 48 |
type: str |
| 49 |
choices: ['guest', 'reporter', 'developer', 'maintainer', 'owner'] |
| 50 |
gitlab_users_access: |
| 51 |
description: |
| 52 |
- Provide a list of user to access level mappings. |
| 53 |
- Every dictionary in this list specifies a user (by username) and the access level the user should have. |
| 54 |
- Mutually exclusive with O(gitlab_user) and O(access_level). |
| 55 |
- Use together with O(purge_users) to remove all users not specified here from the group. |
| 56 |
type: list |
| 57 |
elements: dict |
| 58 |
suboptions: |
| 59 |
name: |
| 60 |
description: A username or a list of usernames to add to/remove from the GitLab group. |
| 61 |
type: str |
| 62 |
required: true |
| 63 |
access_level: |
| 64 |
description: |
| 65 |
- The access level for the user. |
| 66 |
- Required if O(state=present), user state is set to present. |
| 67 |
type: str |
| 68 |
choices: ['guest', 'reporter', 'developer', 'maintainer', 'owner'] |
| 69 |
required: true |
| 70 |
version_added: 3.6.0 |
| 71 |
state: |
| 72 |
description: |
| 73 |
- State of the member in the group. |
| 74 |
- On V(present), it adds a user to a GitLab group. |
| 75 |
- On V(absent), it removes a user from a GitLab group. |
| 76 |
choices: ['present', 'absent'] |
| 77 |
default: 'present' |
| 78 |
type: str |
| 79 |
purge_users: |
| 80 |
description: |
| 81 |
- Adds/remove users of the given access_level to match the given O(gitlab_user)/O(gitlab_users_access) list. If omitted |
| 82 |
do not purge orphaned members. |
| 83 |
- Is only used when O(state=present). |
| 84 |
type: list |
| 85 |
elements: str |
| 86 |
choices: ['guest', 'reporter', 'developer', 'maintainer', 'owner'] |
| 87 |
version_added: 3.6.0 |
| 88 |
""" |
| 89 |
|
| 90 |
EXAMPLES = r""" |
| 91 |
- name: Add a user to a GitLab Group |
| 92 |
community.general.gitlab_group_members: |
| 93 |
api_url: 'https://gitlab.example.com' |
| 94 |
api_token: 'Your-Private-Token' |
| 95 |
gitlab_group: groupname |
| 96 |
gitlab_user: username |
| 97 |
access_level: developer |
| 98 |
state: present |
| 99 |
|
| 100 |
- name: Remove a user from a GitLab Group |
| 101 |
community.general.gitlab_group_members: |
| 102 |
api_url: 'https://gitlab.example.com' |
| 103 |
api_token: 'Your-Private-Token' |
| 104 |
gitlab_group: groupname |
| 105 |
gitlab_user: username |
| 106 |
state: absent |
| 107 |
|
| 108 |
- name: Add a list of Users to A GitLab Group |
| 109 |
community.general.gitlab_group_members: |
| 110 |
api_url: 'https://gitlab.example.com' |
| 111 |
api_token: 'Your-Private-Token' |
| 112 |
gitlab_group: groupname |
| 113 |
gitlab_user: |
| 114 |
- user1 |
| 115 |
- user2 |
| 116 |
access_level: developer |
| 117 |
state: present |
| 118 |
|
| 119 |
- name: Add a list of Users with Dedicated Access Levels to A GitLab Group |
| 120 |
community.general.gitlab_group_members: |
| 121 |
api_url: 'https://gitlab.example.com' |
| 122 |
api_token: 'Your-Private-Token' |
| 123 |
gitlab_group: groupname |
| 124 |
gitlab_users_access: |
| 125 |
- name: user1 |
| 126 |
access_level: developer |
| 127 |
- name: user2 |
| 128 |
access_level: maintainer |
| 129 |
state: present |
| 130 |
|
| 131 |
- name: Add a user, remove all others which might be on this access level |
| 132 |
community.general.gitlab_group_members: |
| 133 |
api_url: 'https://gitlab.example.com' |
| 134 |
api_token: 'Your-Private-Token' |
| 135 |
gitlab_group: groupname |
| 136 |
gitlab_user: username |
| 137 |
access_level: developer |
| 138 |
pruge_users: developer |
| 139 |
state: present |
| 140 |
|
| 141 |
- name: Remove a list of Users with Dedicated Access Levels to A GitLab Group |
| 142 |
community.general.gitlab_group_members: |
| 143 |
api_url: 'https://gitlab.example.com' |
| 144 |
api_token: 'Your-Private-Token' |
| 145 |
gitlab_group: groupname |
| 146 |
gitlab_users_access: |
| 147 |
- name: user1 |
| 148 |
access_level: developer |
| 149 |
- name: user2 |
| 150 |
access_level: maintainer |
| 151 |
state: absent |
| 152 |
""" |
| 153 |
|
| 154 |
RETURN = r""" # """ |
| 155 |
|
| 156 |
from ansible.module_utils.api import basic_auth_argument_spec |
| 157 |
from ansible.module_utils.basic import AnsibleModule |
| 158 |
|
| 159 |
from ansible_collections.community.general.plugins.module_utils._gitlab import ( |
| 160 |
auth_argument_spec, |
| 161 |
gitlab, |
| 162 |
gitlab_authentication, |
| 163 |
list_all_kwargs, |
| 164 |
) |
| 165 |
|
| 166 |
|
| 167 |
class GitLabGroup: |
| 168 |
def __init__(self, module, gl): |
| 169 |
self._module = module |
| 170 |
self._gitlab = gl |
| 171 |
|
| 172 |
# get user id if the user exists |
| 173 |
def get_user_id(self, gitlab_user): |
| 174 |
return next((u.id for u in self._gitlab.users.list(username=gitlab_user, **list_all_kwargs)), None) |
| 175 |
|
| 176 |
# get group id if group exists |
| 177 |
def get_group_id(self, gitlab_group): |
| 178 |
return next( |
| 179 |
( |
| 180 |
g.id |
| 181 |
for g in self._gitlab.groups.list(search=gitlab_group, **list_all_kwargs) |
| 182 |
if g.full_path == gitlab_group |
| 183 |
), |
| 184 |
None, |
| 185 |
) |
| 186 |
|
| 187 |
# get all members in a group |
| 188 |
def get_members_in_a_group(self, gitlab_group_id): |
| 189 |
group = self._gitlab.groups.get(gitlab_group_id) |
| 190 |
return group.members.list(all=True) |
| 191 |
|
| 192 |
# get single member in a group by user name |
| 193 |
def get_member_in_a_group(self, gitlab_group_id, gitlab_user_id): |
| 194 |
member = None |
| 195 |
group = self._gitlab.groups.get(gitlab_group_id) |
| 196 |
try: |
| 197 |
member = group.members.get(gitlab_user_id) |
| 198 |
if member: |
| 199 |
return member |
| 200 |
except gitlab.exceptions.GitlabGetError: |
| 201 |
return None |
| 202 |
|
| 203 |
# check if the user is a member of the group |
| 204 |
def is_user_a_member(self, members, gitlab_user_id): |
| 205 |
return any(member.id == gitlab_user_id for member in members) |
| 206 |
|
| 207 |
# add user to a group |
| 208 |
def add_member_to_group(self, gitlab_user_id, gitlab_group_id, access_level): |
| 209 |
group = self._gitlab.groups.get(gitlab_group_id) |
| 210 |
group.members.create({"user_id": gitlab_user_id, "access_level": access_level}) |
| 211 |
|
| 212 |
# remove user from a group |
| 213 |
def remove_user_from_group(self, gitlab_user_id, gitlab_group_id): |
| 214 |
group = self._gitlab.groups.get(gitlab_group_id) |
| 215 |
group.members.delete(gitlab_user_id) |
| 216 |
|
| 217 |
# get user's access level |
| 218 |
def get_user_access_level(self, members, gitlab_user_id): |
| 219 |
for member in members: |
| 220 |
if member.id == gitlab_user_id: |
| 221 |
return member.access_level |
| 222 |
|
| 223 |
# update user's access level in a group |
| 224 |
def update_user_access_level(self, members, gitlab_user_id, access_level): |
| 225 |
for member in members: |
| 226 |
if member.id == gitlab_user_id: |
| 227 |
member.access_level = access_level |
| 228 |
member.save() |
| 229 |
|
| 230 |
|
| 231 |
def main(): |
| 232 |
argument_spec = basic_auth_argument_spec() |
| 233 |
argument_spec.update(auth_argument_spec()) |
| 234 |
argument_spec.update( |
| 235 |
dict( |
| 236 |
gitlab_group=dict(type="str", required=True), |
| 237 |
gitlab_user=dict(type="list", elements="str"), |
| 238 |
state=dict(type="str", default="present", choices=["present", "absent"]), |
| 239 |
access_level=dict(type="str", choices=["guest", "reporter", "developer", "maintainer", "owner"]), |
| 240 |
purge_users=dict( |
| 241 |
type="list", elements="str", choices=["guest", "reporter", "developer", "maintainer", "owner"] |
| 242 |
), |
| 243 |
gitlab_users_access=dict( |
| 244 |
type="list", |
| 245 |
elements="dict", |
| 246 |
options=dict( |
| 247 |
name=dict(type="str", required=True), |
| 248 |
access_level=dict( |
| 249 |
type="str", choices=["guest", "reporter", "developer", "maintainer", "owner"], required=True |
| 250 |
), |
| 251 |
), |
| 252 |
), |
| 253 |
) |
| 254 |
) |
| 255 |
|
| 256 |
module = AnsibleModule( |
| 257 |
argument_spec=argument_spec, |
| 258 |
mutually_exclusive=[ |
| 259 |
["api_username", "api_token"], |
| 260 |
["gitlab_user", "gitlab_users_access"], |
| 261 |
["access_level", "gitlab_users_access"], |
| 262 |
["api_username", "api_oauth_token"], |
| 263 |
["api_username", "api_job_token"], |
| 264 |
["api_token", "api_oauth_token"], |
| 265 |
["api_token", "api_job_token"], |
| 266 |
], |
| 267 |
required_together=[ |
| 268 |
["api_username", "api_password"], |
| 269 |
["gitlab_user", "access_level"], |
| 270 |
], |
| 271 |
required_one_of=[ |
| 272 |
["api_username", "api_token", "api_oauth_token", "api_job_token"], |
| 273 |
["gitlab_user", "gitlab_users_access"], |
| 274 |
], |
| 275 |
required_if=[ |
| 276 |
["state", "present", ["access_level", "gitlab_users_access"], True], |
| 277 |
], |
| 278 |
supports_check_mode=True, |
| 279 |
) |
| 280 |
|
| 281 |
# check prerequisites and connect to gitlab server |
| 282 |
gl = gitlab_authentication(module) |
| 283 |
|
| 284 |
access_level_int = { |
| 285 |
"guest": gitlab.const.GUEST_ACCESS, |
| 286 |
"reporter": gitlab.const.REPORTER_ACCESS, |
| 287 |
"developer": gitlab.const.DEVELOPER_ACCESS, |
| 288 |
"maintainer": gitlab.const.MAINTAINER_ACCESS, |
| 289 |
"owner": gitlab.const.OWNER_ACCESS, |
| 290 |
} |
| 291 |
|
| 292 |
gitlab_group = module.params["gitlab_group"] |
| 293 |
state = module.params["state"] |
| 294 |
access_level = module.params["access_level"] |
| 295 |
purge_users = module.params["purge_users"] |
| 296 |
|
| 297 |
if purge_users: |
| 298 |
purge_users = [access_level_int[level] for level in purge_users] |
| 299 |
|
| 300 |
group = GitLabGroup(module, gl) |
| 301 |
|
| 302 |
gitlab_group_id = group.get_group_id(gitlab_group) |
| 303 |
|
| 304 |
# group doesn't exist |
| 305 |
if not gitlab_group_id: |
| 306 |
module.fail_json(msg=f"group '{gitlab_group}' not found.") |
| 307 |
|
| 308 |
members = [] |
| 309 |
if module.params["gitlab_user"] is not None: |
| 310 |
gitlab_users_access = [] |
| 311 |
gitlab_users = module.params["gitlab_user"] |
| 312 |
for gl_user in gitlab_users: |
| 313 |
gitlab_users_access.append( |
| 314 |
{"name": gl_user, "access_level": access_level_int[access_level] if access_level else None} |
| 315 |
) |
| 316 |
elif module.params["gitlab_users_access"] is not None: |
| 317 |
gitlab_users_access = module.params["gitlab_users_access"] |
| 318 |
for user_level in gitlab_users_access: |
| 319 |
user_level["access_level"] = access_level_int[user_level["access_level"]] |
| 320 |
|
| 321 |
if len(gitlab_users_access) == 1 and not purge_users: |
| 322 |
# only single user given |
| 323 |
members = [group.get_member_in_a_group(gitlab_group_id, group.get_user_id(gitlab_users_access[0]["name"]))] |
| 324 |
if members[0] is None: |
| 325 |
members = [] |
| 326 |
elif len(gitlab_users_access) > 1 or purge_users: |
| 327 |
# list of users given |
| 328 |
members = group.get_members_in_a_group(gitlab_group_id) |
| 329 |
else: |
| 330 |
module.exit_json( |
| 331 |
changed="OK", result="Nothing to do, please give at least one user or set purge_users true.", result_data=[] |
| 332 |
) |
| 333 |
|
| 334 |
changed = False |
| 335 |
error = False |
| 336 |
changed_users = [] |
| 337 |
changed_data = [] |
| 338 |
|
| 339 |
for gitlab_user in gitlab_users_access: |
| 340 |
gitlab_user_id = group.get_user_id(gitlab_user["name"]) |
| 341 |
|
| 342 |
# user doesn't exist |
| 343 |
if not gitlab_user_id: |
| 344 |
if state == "absent": |
| 345 |
changed_users.append(f"user '{gitlab_user['name']}' not found, and thus also not part of the group") |
| 346 |
changed_data.append( |
| 347 |
{ |
| 348 |
"gitlab_user": gitlab_user["name"], |
| 349 |
"result": "OK", |
| 350 |
"msg": f"user '{gitlab_user['name']}' not found, and thus also not part of the group", |
| 351 |
} |
| 352 |
) |
| 353 |
else: |
| 354 |
error = True |
| 355 |
changed_users.append(f"user '{gitlab_user['name']}' not found.") |
| 356 |
changed_data.append( |
| 357 |
{ |
| 358 |
"gitlab_user": gitlab_user["name"], |
| 359 |
"result": "FAILED", |
| 360 |
"msg": f"user '{gitlab_user['name']}' not found.", |
| 361 |
} |
| 362 |
) |
| 363 |
continue |
| 364 |
|
| 365 |
is_user_a_member = group.is_user_a_member(members, gitlab_user_id) |
| 366 |
|
| 367 |
# check if the user is a member in the group |
| 368 |
if not is_user_a_member: |
| 369 |
if state == "present": |
| 370 |
# add user to the group |
| 371 |
try: |
| 372 |
if not module.check_mode: |
| 373 |
group.add_member_to_group(gitlab_user_id, gitlab_group_id, gitlab_user["access_level"]) |
| 374 |
changed = True |
| 375 |
changed_users.append(f"Successfully added user '{gitlab_user['name']}' to group") |
| 376 |
changed_data.append( |
| 377 |
{ |
| 378 |
"gitlab_user": gitlab_user["name"], |
| 379 |
"result": "CHANGED", |
| 380 |
"msg": f"Successfully added user '{gitlab_user['name']}' to group", |
| 381 |
} |
| 382 |
) |
| 383 |
except gitlab.exceptions.GitlabCreateError as e: |
| 384 |
error = True |
| 385 |
changed_users.append(f"Failed to updated the access level for the user, '{gitlab_user['name']}'") |
| 386 |
changed_data.append( |
| 387 |
{ |
| 388 |
"gitlab_user": gitlab_user["name"], |
| 389 |
"result": "FAILED", |
| 390 |
"msg": f"Not allowed to add the access level for the member, {gitlab_user['name']}: {e}", |
| 391 |
} |
| 392 |
) |
| 393 |
# state as absent |
| 394 |
else: |
| 395 |
changed_users.append( |
| 396 |
f"User, '{gitlab_user['name']}', is not a member in the group. No change to report" |
| 397 |
) |
| 398 |
changed_data.append( |
| 399 |
{ |
| 400 |
"gitlab_user": gitlab_user["name"], |
| 401 |
"result": "OK", |
| 402 |
"msg": f"User, '{gitlab_user['name']}', is not a member in the group. No change to report", |
| 403 |
} |
| 404 |
) |
| 405 |
# in case that a user is a member |
| 406 |
else: |
| 407 |
if state == "present": |
| 408 |
# compare the access level |
| 409 |
user_access_level = group.get_user_access_level(members, gitlab_user_id) |
| 410 |
if user_access_level == gitlab_user["access_level"]: |
| 411 |
changed_users.append( |
| 412 |
f"User, '{gitlab_user['name']}', is already a member in the group. No change to report" |
| 413 |
) |
| 414 |
changed_data.append( |
| 415 |
{ |
| 416 |
"gitlab_user": gitlab_user["name"], |
| 417 |
"result": "OK", |
| 418 |
"msg": f"User, '{gitlab_user['name']}', is already a member in the group. No change to report", |
| 419 |
} |
| 420 |
) |
| 421 |
else: |
| 422 |
# update the access level for the user |
| 423 |
try: |
| 424 |
if not module.check_mode: |
| 425 |
group.update_user_access_level(members, gitlab_user_id, gitlab_user["access_level"]) |
| 426 |
changed = True |
| 427 |
changed_users.append( |
| 428 |
f"Successfully updated the access level for the user, '{gitlab_user['name']}'" |
| 429 |
) |
| 430 |
changed_data.append( |
| 431 |
{ |
| 432 |
"gitlab_user": gitlab_user["name"], |
| 433 |
"result": "CHANGED", |
| 434 |
"msg": f"Successfully updated the access level for the user, '{gitlab_user['name']}'", |
| 435 |
} |
| 436 |
) |
| 437 |
except gitlab.exceptions.GitlabUpdateError as e: |
| 438 |
error = True |
| 439 |
changed_users.append( |
| 440 |
f"Failed to updated the access level for the user, '{gitlab_user['name']}'" |
| 441 |
) |
| 442 |
changed_data.append( |
| 443 |
{ |
| 444 |
"gitlab_user": gitlab_user["name"], |
| 445 |
"result": "FAILED", |
| 446 |
"msg": f"Not allowed to update the access level for the member, {gitlab_user['name']}: {e}", |
| 447 |
} |
| 448 |
) |
| 449 |
else: |
| 450 |
# remove the user from the group |
| 451 |
try: |
| 452 |
if not module.check_mode: |
| 453 |
group.remove_user_from_group(gitlab_user_id, gitlab_group_id) |
| 454 |
changed = True |
| 455 |
changed_users.append(f"Successfully removed user, '{gitlab_user['name']}', from the group") |
| 456 |
changed_data.append( |
| 457 |
{ |
| 458 |
"gitlab_user": gitlab_user["name"], |
| 459 |
"result": "CHANGED", |
| 460 |
"msg": f"Successfully removed user, '{gitlab_user['name']}', from the group", |
| 461 |
} |
| 462 |
) |
| 463 |
except gitlab.exceptions.GitlabDeleteError as e: |
| 464 |
error = True |
| 465 |
changed_users.append(f"Failed to removed user, '{gitlab_user['name']}', from the group") |
| 466 |
changed_data.append( |
| 467 |
{ |
| 468 |
"gitlab_user": gitlab_user["name"], |
| 469 |
"result": "FAILED", |
| 470 |
"msg": f"Failed to remove user, '{gitlab_user['name']}' from the group: {e}", |
| 471 |
} |
| 472 |
) |
| 473 |
|
| 474 |
# if state = present and purge_users set delete users which are in members having give access level but not in gitlab_users |
| 475 |
if state == "present" and purge_users: |
| 476 |
uppercase_names_in_gitlab_users_access = [] |
| 477 |
for name in gitlab_users_access: |
| 478 |
uppercase_names_in_gitlab_users_access.append(name["name"].upper()) |
| 479 |
|
| 480 |
for member in members: |
| 481 |
if ( |
| 482 |
member.access_level in purge_users |
| 483 |
and member.username.upper() not in uppercase_names_in_gitlab_users_access |
| 484 |
): |
| 485 |
try: |
| 486 |
if not module.check_mode: |
| 487 |
group.remove_user_from_group(member.id, gitlab_group_id) |
| 488 |
changed = True |
| 489 |
changed_users.append( |
| 490 |
f"Successfully removed user '{member.username}', from group. Was not in given list" |
| 491 |
) |
| 492 |
changed_data.append( |
| 493 |
{ |
| 494 |
"gitlab_user": member.username, |
| 495 |
"result": "CHANGED", |
| 496 |
"msg": f"Successfully removed user '{member.username}', from group. Was not in given list", |
| 497 |
} |
| 498 |
) |
| 499 |
except gitlab.exceptions.GitlabDeleteError as e: |
| 500 |
error = True |
| 501 |
changed_users.append(f"Failed to removed user, '{gitlab_user['name']}', from the group") |
| 502 |
changed_data.append( |
| 503 |
{ |
| 504 |
"gitlab_user": gitlab_user["name"], |
| 505 |
"result": "FAILED", |
| 506 |
"msg": f"Failed to remove user, '{gitlab_user['name']}' from the group: {e}", |
| 507 |
} |
| 508 |
) |
| 509 |
|
| 510 |
if len(gitlab_users_access) == 1 and error: |
| 511 |
# if single user given and an error occurred return error for list errors will be per user |
| 512 |
module.fail_json(msg=f"FAILED: '{changed_users[0]} '", result_data=changed_data) |
| 513 |
elif error: |
| 514 |
module.fail_json(msg="FAILED: At least one given user/permission could not be set", result_data=changed_data) |
| 515 |
|
| 516 |
module.exit_json( |
| 517 |
changed=changed, msg="Successfully set memberships", result="\n".join(changed_users), result_data=changed_data |
| 518 |
) |
| 519 |
|
| 520 |
|
| 521 |
if __name__ == "__main__": |
| 522 |
main() |