Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2019, Guillaume Martinez ([email protected])
4 # Copyright (c) 2015, Werner Dijkerman ([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_group
12 short_description: Creates/updates/deletes GitLab Groups
13 description:
14 - When the group does not exist in GitLab, it is created.
15 - When the group does exist and O(state=absent), the group is deleted.
16 author:
17 - Werner Dijkerman (@dj-wasabi)
18 - Guillaume Martinez (@Lunik)
19 requirements:
20 - python-gitlab python module
21 extends_documentation_fragment:
22 - community.general._auth_basic
23 - community.general._gitlab
24 - community.general._attributes
25
26 attributes:
27 check_mode:
28 support: full
29 diff_mode:
30 support: none
31
32 options:
33 auto_devops_enabled:
34 description:
35 - Default to Auto DevOps pipeline for all projects within this group.
36 type: bool
37 version_added: 3.7.0
38 avatar_path:
39 description:
40 - Absolute path image to configure avatar. File size should not exceed 200 kb.
41 - This option is only used on creation, not for updates.
42 type: path
43 version_added: 4.2.0
44 default_branch:
45 description:
46 - All merge requests and commits are made against this branch unless you specify a different one.
47 type: str
48 version_added: 9.5.0
49 description:
50 description:
51 - A description for the group.
52 type: str
53 enabled_git_access_protocol:
54 description:
55 - V(all) means SSH and HTTP(S) is enabled.
56 - V(ssh) means only SSH is enabled.
57 - V(http) means only HTTP(S) is enabled.
58 - Only available for top level groups.
59 choices: ["all", "ssh", "http"]
60 type: str
61 version_added: 9.5.0
62 force_delete:
63 description:
64 - Force delete group even if projects in it.
65 - Used only when O(state=absent).
66 type: bool
67 default: false
68 version_added: 7.5.0
69 lfs_enabled:
70 description:
71 - Projects in this group can use Git LFS.
72 type: bool
73 version_added: 9.5.0
74 lock_duo_features_enabled:
75 description:
76 - Enforce GitLab Duo features for all subgroups.
77 - Only available for top level groups.
78 type: bool
79 version_added: 9.5.0
80 membership_lock:
81 description:
82 - Users cannot be added to projects in this group.
83 type: bool
84 version_added: 9.5.0
85 mentions_disabled:
86 description:
87 - Group mentions are disabled.
88 type: bool
89 version_added: 9.5.0
90 name:
91 description:
92 - Name of the group you want to create.
93 required: true
94 type: str
95 parent:
96 description:
97 - Allow to create subgroups.
98 - ID or Full path of parent group in the form of group/name.
99 type: str
100 path:
101 description:
102 - The path of the group you want to create, this is O(api_url)/O(path).
103 - If not supplied, O(name) is used.
104 type: str
105 prevent_forking_outside_group:
106 description:
107 - Prevent forking outside of the group.
108 type: bool
109 version_added: 9.5.0
110 prevent_sharing_groups_outside_hierarchy:
111 description:
112 - Members cannot invite groups outside of this group and its subgroups.
113 - Only available for top level groups.
114 type: bool
115 version_added: 9.5.0
116 project_creation_level:
117 description:
118 - Determine if developers can create projects in the group.
119 choices: ["developer", "maintainer", "noone"]
120 type: str
121 version_added: 3.7.0
122 request_access_enabled:
123 description:
124 - Users can request access (if visibility is public or internal).
125 type: bool
126 version_added: 9.5.0
127 service_access_tokens_expiration_enforced:
128 description:
129 - Service account token expiration.
130 - Changes do not affect existing token expiration dates.
131 - Only available for top level groups.
132 type: bool
133 version_added: 9.5.0
134 share_with_group_lock:
135 description:
136 - Projects cannot be shared with other groups.
137 type: bool
138 version_added: 9.5.0
139 require_two_factor_authentication:
140 description:
141 - Require all users in this group to setup two-factor authentication.
142 type: bool
143 version_added: 3.7.0
144 state:
145 description:
146 - Create or delete group.
147 - Possible values are present and absent.
148 default: present
149 type: str
150 choices: ["present", "absent"]
151 subgroup_creation_level:
152 description:
153 - Allowed to create subgroups.
154 choices: ["maintainer", "owner"]
155 type: str
156 version_added: 3.7.0
157 two_factor_grace_period:
158 description:
159 - Delay 2FA enforcement (hours).
160 type: str
161 version_added: 9.5.0
162 visibility:
163 description:
164 - Default visibility of the group.
165 choices: ["private", "internal", "public"]
166 default: private
167 type: str
168 wiki_access_level:
169 description:
170 - V(enabled) means everyone can access the wiki.
171 - V(private) means only members of this group can access the wiki.
172 - V(disabled) means group-level wiki is disabled.
173 choices: ["enabled", "private", "disabled"]
174 type: str
175 version_added: 9.5.0
176 """
177
178 EXAMPLES = r"""
179 - name: "Delete GitLab Group"
180 community.general.gitlab_group:
181 api_url: https://gitlab.example.com/
182 api_token: "{{ access_token }}"
183 name: my_first_group
184 state: absent
185
186 - name: "Create GitLab Group"
187 community.general.gitlab_group:
188 api_url: https://gitlab.example.com/
189 validate_certs: true
190 api_username: dj-wasabi
191 api_password: "MySecretPassword"
192 name: my_first_group
193 path: my_first_group
194 state: present
195
196 # The group will by created at https://gitlab.dj-wasabi.local/super_parent/parent/my_first_group
197 - name: "Create GitLab SubGroup"
198 community.general.gitlab_group:
199 api_url: https://gitlab.example.com/
200 validate_certs: true
201 api_username: dj-wasabi
202 api_password: "MySecretPassword"
203 name: my_first_group
204 path: my_first_group
205 state: present
206 parent: "super_parent/parent"
207
208 # Other group which only allows sub-groups - no projects
209 - name: "Create GitLab Group for SubGroups only"
210 community.general.gitlab_group:
211 api_url: https://gitlab.example.com/
212 validate_certs: true
213 api_username: dj-wasabi
214 api_password: "MySecretPassword"
215 name: my_main_group
216 path: my_main_group
217 state: present
218 project_creation_level: noone
219 auto_devops_enabled: false
220 subgroup_creation_level: maintainer
221 """
222
223 RETURN = r"""
224 msg:
225 description: Success or failure message.
226 returned: always
227 type: str
228 sample: "Success"
229
230 result:
231 description: JSON-parsed response from the server.
232 returned: always
233 type: dict
234
235 error:
236 description: The error message returned by the GitLab API.
237 returned: failed
238 type: str
239 sample: "400: path is already in use"
240
241 group:
242 description: API object.
243 returned: always
244 type: dict
245 """
246
247 from ansible.module_utils.api import basic_auth_argument_spec
248 from ansible.module_utils.basic import AnsibleModule
249
250 from ansible_collections.community.general.plugins.module_utils._gitlab import (
251 auth_argument_spec,
252 find_group,
253 gitlab,
254 gitlab_authentication,
255 )
256
257
258 class GitLabGroup:
259 def __init__(self, module, gitlab_instance):
260 self._module = module
261 self._gitlab = gitlab_instance
262 self.group_object = None
263
264 """
265 @param group Group object
266 """
267
268 def get_group_id(self, group):
269 if group is not None:
270 return group.id
271 return None
272
273 """
274 @param name Name of the group
275 @param parent Parent group full path
276 @param options Group options
277 """
278
279 def create_or_update_group(self, name, parent, options):
280 changed = False
281
282 payload = {
283 "auto_devops_enabled": options["auto_devops_enabled"],
284 "default_branch": options["default_branch"],
285 "description": options["description"],
286 "lfs_enabled": options["lfs_enabled"],
287 "membership_lock": options["membership_lock"],
288 "mentions_disabled": options["mentions_disabled"],
289 "name": name,
290 "path": options["path"],
291 "prevent_forking_outside_group": options["prevent_forking_outside_group"],
292 "project_creation_level": options["project_creation_level"],
293 "request_access_enabled": options["request_access_enabled"],
294 "require_two_factor_authentication": options["require_two_factor_authentication"],
295 "share_with_group_lock": options["share_with_group_lock"],
296 "subgroup_creation_level": options["subgroup_creation_level"],
297 "visibility": options["visibility"],
298 "wiki_access_level": options["wiki_access_level"],
299 }
300 if options.get("enabled_git_access_protocol") and parent is None:
301 payload["enabled_git_access_protocol"] = options["enabled_git_access_protocol"]
302 if options.get("lock_duo_features_enabled") and parent is None:
303 payload["lock_duo_features_enabled"] = options["lock_duo_features_enabled"]
304 if options.get("prevent_sharing_groups_outside_hierarchy") and parent is None:
305 payload["prevent_sharing_groups_outside_hierarchy"] = options["prevent_sharing_groups_outside_hierarchy"]
306 if options.get("service_access_tokens_expiration_enforced") and parent is None:
307 payload["service_access_tokens_expiration_enforced"] = options["service_access_tokens_expiration_enforced"]
308 if options.get("two_factor_grace_period"):
309 payload["two_factor_grace_period"] = int(options["two_factor_grace_period"])
310
311 # Because we have already call userExists in main()
312 if self.group_object is None:
313 payload["parent_id"] = self.get_group_id(parent)
314 group = self.create_group(payload)
315
316 # add avatar to group
317 if options["avatar_path"]:
318 try:
319 group.avatar = open(options["avatar_path"], "rb")
320 except OSError as e:
321 self._module.fail_json(msg=f"Cannot open {options['avatar_path']}: {e}")
322 changed = True
323 else:
324 changed, group = self.update_group(self.group_object, payload)
325
326 self.group_object = group
327 if changed:
328 if self._module.check_mode:
329 self._module.exit_json(changed=True, msg=f"Successfully created or updated the group {name}")
330
331 try:
332 group.save()
333 except Exception as e:
334 self._module.fail_json(msg=f"Failed to update group: {e} ")
335 return True
336 else:
337 return False
338
339 """
340 @param arguments Attributes of the group
341 """
342
343 def create_group(self, arguments):
344 if self._module.check_mode:
345 return True
346
347 try:
348 # Filter out None values
349 filtered = {arg_key: arg_value for arg_key, arg_value in arguments.items() if arg_value is not None}
350
351 group = self._gitlab.groups.create(filtered)
352 except gitlab.exceptions.GitlabCreateError as e:
353 self._module.fail_json(msg=f"Failed to create group: {e} ")
354
355 return group
356
357 """
358 @param group Group Object
359 @param arguments Attributes of the group
360 """
361
362 def update_group(self, group, arguments):
363 changed = False
364
365 for arg_key, arg_value in arguments.items():
366 if arg_value is not None:
367 if getattr(group, arg_key) != arg_value:
368 setattr(group, arg_key, arg_value)
369 changed = True
370
371 return (changed, group)
372
373 """
374 @param force To delete even if projects inside
375 """
376
377 def delete_group(self, force=False):
378 group = self.group_object
379
380 if not force and len(group.projects.list(all=False)) >= 1:
381 self._module.fail_json(
382 msg=(
383 "There are still projects in this group. "
384 "These needs to be moved or deleted before this group can be removed. "
385 "Use 'force_delete' to 'true' to force deletion of existing projects."
386 )
387 )
388 else:
389 if self._module.check_mode:
390 return True
391
392 try:
393 group.delete()
394 except Exception as e:
395 self._module.fail_json(msg=f"Failed to delete group: {e} ")
396
397 """
398 @param name Name of the group
399 @param full_path Complete path of the Group including parent group path. <parent_path>/<group_path>
400 """
401
402 def exists_group(self, project_identifier):
403 # When group/user exists, object will be stored in self.group_object.
404 group = find_group(self._gitlab, project_identifier)
405 if group:
406 self.group_object = group
407 return True
408 return False
409
410
411 def main():
412 argument_spec = basic_auth_argument_spec()
413 argument_spec.update(auth_argument_spec())
414 argument_spec.update(
415 dict(
416 auto_devops_enabled=dict(type="bool"),
417 avatar_path=dict(type="path"),
418 default_branch=dict(type="str"),
419 description=dict(type="str"),
420 enabled_git_access_protocol=dict(type="str", choices=["all", "ssh", "http"]),
421 force_delete=dict(type="bool", default=False),
422 lfs_enabled=dict(type="bool"),
423 lock_duo_features_enabled=dict(type="bool"),
424 membership_lock=dict(type="bool"),
425 mentions_disabled=dict(type="bool"),
426 name=dict(type="str", required=True),
427 parent=dict(type="str"),
428 path=dict(type="str"),
429 prevent_forking_outside_group=dict(type="bool"),
430 prevent_sharing_groups_outside_hierarchy=dict(type="bool"),
431 project_creation_level=dict(type="str", choices=["developer", "maintainer", "noone"]),
432 request_access_enabled=dict(type="bool"),
433 require_two_factor_authentication=dict(type="bool"),
434 service_access_tokens_expiration_enforced=dict(type="bool"),
435 share_with_group_lock=dict(type="bool"),
436 state=dict(type="str", default="present", choices=["absent", "present"]),
437 subgroup_creation_level=dict(type="str", choices=["maintainer", "owner"]),
438 two_factor_grace_period=dict(type="str"),
439 visibility=dict(type="str", default="private", choices=["internal", "private", "public"]),
440 wiki_access_level=dict(type="str", choices=["enabled", "private", "disabled"]),
441 )
442 )
443
444 module = AnsibleModule(
445 argument_spec=argument_spec,
446 mutually_exclusive=[
447 ["api_token", "api_job_token"],
448 ["api_token", "api_oauth_token"],
449 ["api_username", "api_job_token"],
450 ["api_username", "api_oauth_token"],
451 ["api_username", "api_token"],
452 ],
453 required_together=[
454 ["api_username", "api_password"],
455 ],
456 required_one_of=[["api_username", "api_token", "api_oauth_token", "api_job_token"]],
457 supports_check_mode=True,
458 )
459
460 # check prerequisites and connect to gitlab server
461 gitlab_instance = gitlab_authentication(module)
462
463 auto_devops_enabled = module.params["auto_devops_enabled"]
464 avatar_path = module.params["avatar_path"]
465 default_branch = module.params["default_branch"]
466 description = module.params["description"]
467 enabled_git_access_protocol = module.params["enabled_git_access_protocol"]
468 force_delete = module.params["force_delete"]
469 group_name = module.params["name"]
470 group_path = module.params["path"]
471 group_visibility = module.params["visibility"]
472 lfs_enabled = module.params["lfs_enabled"]
473 lock_duo_features_enabled = module.params["lock_duo_features_enabled"]
474 membership_lock = module.params["membership_lock"]
475 mentions_disabled = module.params["mentions_disabled"]
476 parent_identifier = module.params["parent"]
477 prevent_forking_outside_group = module.params["prevent_forking_outside_group"]
478 prevent_sharing_groups_outside_hierarchy = module.params["prevent_sharing_groups_outside_hierarchy"]
479 project_creation_level = module.params["project_creation_level"]
480 request_access_enabled = module.params["request_access_enabled"]
481 require_two_factor_authentication = module.params["require_two_factor_authentication"]
482 service_access_tokens_expiration_enforced = module.params["service_access_tokens_expiration_enforced"]
483 share_with_group_lock = module.params["share_with_group_lock"]
484 state = module.params["state"]
485 subgroup_creation_level = module.params["subgroup_creation_level"]
486 two_factor_grace_period = module.params["two_factor_grace_period"]
487 wiki_access_level = module.params["wiki_access_level"]
488
489 # Define default group_path based on group_name
490 if group_path is None:
491 group_path = group_name.replace(" ", "_")
492
493 gitlab_group = GitLabGroup(module, gitlab_instance)
494
495 parent_group = None
496 if parent_identifier:
497 parent_group = find_group(gitlab_instance, parent_identifier)
498 if not parent_group:
499 module.fail_json(msg="Failed to create GitLab group: Parent group doesn't exist")
500
501 group_exists = gitlab_group.exists_group(f"{parent_group.full_path}/{group_path}")
502 else:
503 group_exists = gitlab_group.exists_group(group_path)
504
505 if state == "absent":
506 if group_exists:
507 gitlab_group.delete_group(force=force_delete)
508 module.exit_json(changed=True, msg=f"Successfully deleted group {group_name}")
509 else:
510 module.exit_json(changed=False, msg="Group deleted or does not exist")
511
512 if state == "present":
513 if gitlab_group.create_or_update_group(
514 group_name,
515 parent_group,
516 {
517 "auto_devops_enabled": auto_devops_enabled,
518 "avatar_path": avatar_path,
519 "default_branch": default_branch,
520 "description": description,
521 "enabled_git_access_protocol": enabled_git_access_protocol,
522 "lfs_enabled": lfs_enabled,
523 "lock_duo_features_enabled": lock_duo_features_enabled,
524 "membership_lock": membership_lock,
525 "mentions_disabled": mentions_disabled,
526 "path": group_path,
527 "prevent_forking_outside_group": prevent_forking_outside_group,
528 "prevent_sharing_groups_outside_hierarchy": prevent_sharing_groups_outside_hierarchy,
529 "project_creation_level": project_creation_level,
530 "request_access_enabled": request_access_enabled,
531 "require_two_factor_authentication": require_two_factor_authentication,
532 "service_access_tokens_expiration_enforced": service_access_tokens_expiration_enforced,
533 "share_with_group_lock": share_with_group_lock,
534 "subgroup_creation_level": subgroup_creation_level,
535 "two_factor_grace_period": two_factor_grace_period,
536 "visibility": group_visibility,
537 "wiki_access_level": wiki_access_level,
538 },
539 ):
540 module.exit_json(
541 changed=True,
542 msg=f"Successfully created or updated the group {group_name}",
543 group=gitlab_group.group_object._attrs,
544 )
545 else:
546 module.exit_json(
547 changed=False, msg=f"No need to update the group {group_name}", group=gitlab_group.group_object._attrs
548 )
549
550
551 if __name__ == "__main__":
552 main()