Debian Codegraph @

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

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