Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2021, Raphaël Droz ([email protected])
4 # Copyright (c) 2019, Guillaume Martinez ([email protected])
5 # Copyright (c) 2018, Samy Coenen <[email protected]>
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: gitlab_runner
13 short_description: Create, modify and delete GitLab Runners
14 description:
15 - Register, update and delete runners on GitLab Server side with the GitLab API.
16 - All operations are performed using the GitLab API v4.
17 - For details, consult the full API documentation at U(https://docs.gitlab.com/ee/api/runners.html) and
18 U(https://docs.gitlab.com/ee/api/users.html#create-a-runner-linked-to-a-user).
19 - A valid private API token is required for all operations. You can create as many tokens as you like using the GitLab web
20 interface at U(https://$GITLAB_URL/profile/personal_access_tokens).
21 - A valid registration token is required for registering a new runner. To create shared runners, you need to ask your administrator
22 to give you this token. It can be found at U(https://$GITLAB_URL/admin/runners/).
23 - This module does not handle the C(gitlab-runner) process part, but only manages the runner on GitLab Server side through
24 its API. Once the module has created the runner, you may use the generated token to run C(gitlab-runner register) command.
25 notes:
26 - To create a new runner at least the O(api_token), O(description) and O(api_url) options are required.
27 - Runners need to have unique descriptions, since this attribute is used as key for idempotency.
28 author:
29 - Samy Coenen (@SamyCoenen)
30 - Guillaume Martinez (@Lunik)
31 requirements:
32 - python-gitlab >= 1.5.0 for legacy runner registration workflow (runner registration token -
33 U(https://docs.gitlab.com/runner/register/#register-with-a-runner-registration-token-deprecated))
34 - python-gitlab >= 4.0.0 for new runner registration workflow (runner authentication token -
35 U(https://docs.gitlab.com/runner/register/#register-with-a-runner-authentication-token))
36 extends_documentation_fragment:
37 - community.general._auth_basic
38 - community.general._gitlab
39 - community.general._attributes
40
41 attributes:
42 check_mode:
43 support: full
44 diff_mode:
45 support: none
46
47 options:
48 group:
49 description:
50 - ID or full path of the group in the form group/subgroup.
51 - Mutually exclusive with O(owned) and O(project).
52 - Must be group's numeric ID if O(registration_token) is not set and O(state=present).
53 type: str
54 version_added: '6.5.0'
55 project:
56 description:
57 - ID or full path of the project in the form of group/name.
58 - Mutually exclusive with O(owned) since community.general 4.5.0.
59 - Mutually exclusive with O(group).
60 - Must be project's numeric ID if O(registration_token) is not set and O(state=present).
61 type: str
62 version_added: '3.7.0'
63 description:
64 description:
65 - The unique name of the runner.
66 required: true
67 type: str
68 aliases:
69 - name
70 state:
71 description:
72 - Make sure that the runner with the same name exists with the same configuration or delete the runner with the same
73 name.
74 default: present
75 choices: ["present", "absent"]
76 type: str
77 registration_token:
78 description:
79 - The registration token is used to register new runners before GitLab 16.0.
80 - Required if O(state=present) for GitLab < 16.0.
81 - If set, the runner is created using the old runner creation workflow.
82 - If not set, the runner is created using the new runner creation workflow, introduced in GitLab 16.0.
83 - If not set, requires python-gitlab >= 4.0.0.
84 type: str
85 owned:
86 description:
87 - Searches only runners available to the user when searching for existing, when false admin token required.
88 - Mutually exclusive with O(project) since community.general 4.5.0.
89 - Mutually exclusive with O(group).
90 default: false
91 type: bool
92 version_added: 2.0.0
93 active:
94 description:
95 - Define if the runners is immediately active after creation.
96 - Mutually exclusive with O(paused).
97 default: true
98 type: bool
99 paused:
100 description:
101 - Define if the runners is active or paused after creation.
102 - Mutually exclusive with O(active).
103 default: false
104 type: bool
105 version_added: 8.1.0
106 locked:
107 description:
108 - Determines if the runner is locked or not.
109 default: false
110 type: bool
111 access_level:
112 description:
113 - Determines if a runner can pick up jobs only from protected branches.
114 - If O(access_level_on_creation) is not explicitly set to V(true), this option is ignored on registration and is only
115 applied on updates.
116 - If set to V(not_protected), runner can pick up jobs from both protected and unprotected branches.
117 - If set to V(ref_protected), runner can pick up jobs only from protected branches.
118 - Before community.general 8.0.0 the default was V(ref_protected). This was changed to no default in community.general
119 8.0.0. If this option is not specified explicitly, GitLab uses V(not_protected) on creation, and the value set is
120 not changed on any updates.
121 choices: ["not_protected", "ref_protected"]
122 type: str
123 access_level_on_creation:
124 description:
125 - Whether the runner should be registered with an access level or not.
126 - If set to V(true), the value of O(access_level) is used for runner registration.
127 - If set to V(false), GitLab registers the runner with the default access level.
128 - The default of this option changed to V(true) in community.general 7.0.0. Before, it was V(false).
129 default: true
130 type: bool
131 version_added: 6.3.0
132 maximum_timeout:
133 description:
134 - The maximum time that a runner has to complete a specific job.
135 - Use V(0) to disable the timeout. This is available since community.general 12.1.0.
136 default: 3600
137 type: int
138 run_untagged:
139 description:
140 - Run untagged jobs or not.
141 default: true
142 type: bool
143 tag_list:
144 description: The tags that apply to the runner.
145 default: []
146 type: list
147 elements: str
148 """
149
150 EXAMPLES = r"""
151 - name: Create an instance-level runner
152 community.general.gitlab_runner:
153 api_url: https://gitlab.example.com/
154 api_token: "{{ access_token }}"
155 description: Docker Machine t1
156 state: present
157 active: true
158 tag_list: ['docker']
159 run_untagged: false
160 locked: false
161 register: runner # Register module output to run C(gitlab-runner register) command in another task
162
163 - name: Create a group-level runner
164 community.general.gitlab_runner:
165 api_url: https://gitlab.example.com/
166 api_token: "{{ access_token }}"
167 description: Docker Machine t1
168 state: present
169 active: true
170 tag_list: ['docker']
171 run_untagged: false
172 locked: false
173 group: top-level-group/subgroup
174 register: runner # Register module output to run C(gitlab-runner register) command in another task
175
176 - name: Create a project-level runner
177 community.general.gitlab_runner:
178 api_url: https://gitlab.example.com/
179 api_token: "{{ access_token }}"
180 description: Docker Machine t1
181 state: present
182 active: true
183 tag_list: ['docker']
184 run_untagged: false
185 locked: false
186 project: top-level-group/subgroup/project
187 register: runner # Register module output to run C(gitlab-runner register) command in another task
188
189 - name: "Register instance-level runner with registration token (deprecated)"
190 community.general.gitlab_runner:
191 api_url: https://gitlab.example.com/
192 api_token: "{{ access_token }}"
193 registration_token: 4gfdsg345
194 description: Docker Machine t1
195 state: present
196 active: true
197 tag_list: ['docker']
198 run_untagged: false
199 locked: false
200 register: runner # Register module output to run C(gitlab-runner register) command in another task
201
202 - name: "Delete runner"
203 community.general.gitlab_runner:
204 api_url: https://gitlab.example.com/
205 api_token: "{{ access_token }}"
206 description: Docker Machine t1
207 state: absent
208
209 - name: Delete an owned runner as a non-admin
210 community.general.gitlab_runner:
211 api_url: https://gitlab.example.com/
212 api_token: "{{ access_token }}"
213 description: Docker Machine t1
214 owned: true
215 state: absent
216
217 - name: "Register a project-level runner with registration token (deprecated)"
218 community.general.gitlab_runner:
219 api_url: https://gitlab.example.com/
220 api_token: "{{ access_token }}"
221 registration_token: 4gfdsg345
222 description: MyProject runner
223 state: present
224 project: mygroup/mysubgroup/myproject
225 register: runner # Register module output to run C(gitlab-runner register) command in another task
226 """
227
228 RETURN = r"""
229 msg:
230 description: Success or failure message.
231 returned: always
232 type: str
233 sample: "Success"
234
235 result:
236 description: JSON-parsed response from the server.
237 returned: always
238 type: dict
239
240 error:
241 description: The error message returned by the GitLab API.
242 returned: failed
243 type: str
244 sample: "400: path is already in use"
245
246 runner:
247 description: API object.
248 returned: always
249 type: dict
250 """
251
252 from ansible.module_utils.api import basic_auth_argument_spec
253 from ansible.module_utils.basic import AnsibleModule
254
255 from ansible_collections.community.general.plugins.module_utils._gitlab import (
256 auth_argument_spec,
257 gitlab,
258 gitlab_authentication,
259 list_all_kwargs,
260 )
261 from ansible_collections.community.general.plugins.module_utils._version import LooseVersion
262
263
264 class GitLabRunner:
265 def __init__(self, module, gitlab_instance, group=None, project=None):
266 self._module = module
267 self._gitlab = gitlab_instance
268 self.runner_object = None
269
270 # Whether to operate on GitLab-instance-wide or project-wide runners
271 # See https://gitlab.com/gitlab-org/gitlab-ce/issues/60774
272 # for group runner token access
273 if project:
274 self._runners_endpoint = project.runners.list
275 elif group:
276 self._runners_endpoint = group.runners.list
277 elif module.params["owned"]:
278 self._runners_endpoint = gitlab_instance.runners.list
279 else:
280 self._runners_endpoint = gitlab_instance.runners.all
281
282 def create_or_update_runner(self, description, options):
283 changed = False
284
285 arguments = {
286 "locked": options["locked"],
287 "run_untagged": options["run_untagged"],
288 "maximum_timeout": options["maximum_timeout"],
289 "tag_list": options["tag_list"],
290 }
291
292 if options.get("paused") is not None:
293 arguments["paused"] = options["paused"]
294 else:
295 arguments["active"] = options["active"]
296
297 if options.get("access_level") is not None:
298 arguments["access_level"] = options["access_level"]
299 # Because we have already call userExists in main()
300 if self.runner_object is None:
301 arguments["description"] = description
302 if options.get("registration_token") is not None:
303 arguments["token"] = options["registration_token"]
304 elif options.get("group") is not None:
305 arguments["runner_type"] = "group_type"
306 arguments["group_id"] = options["group"]
307 elif options.get("project") is not None:
308 arguments["runner_type"] = "project_type"
309 arguments["project_id"] = options["project"]
310 else:
311 arguments["runner_type"] = "instance_type"
312
313 access_level_on_creation = self._module.params["access_level_on_creation"]
314 if not access_level_on_creation:
315 arguments.pop("access_level", None)
316
317 runner = self.create_runner(arguments)
318 changed = True
319 else:
320 changed, runner = self.update_runner(self.runner_object, arguments)
321 if changed:
322 if self._module.check_mode:
323 self._module.exit_json(changed=True, msg=f"Successfully updated the runner {description}")
324
325 try:
326 runner.save()
327 except Exception as e:
328 self._module.fail_json(msg=f"Failed to update runner: {e} ")
329
330 self.runner_object = runner
331 return changed
332
333 """
334 @param arguments Attributes of the runner
335 """
336
337 def create_runner(self, arguments):
338 if self._module.check_mode:
339
340 class MockRunner:
341 def __init__(self):
342 self._attrs = {}
343
344 return MockRunner()
345
346 try:
347 if arguments.get("token") is not None:
348 runner = self._gitlab.runners.create(arguments)
349 elif LooseVersion(gitlab.__version__) < LooseVersion("4.0.0"):
350 self._module.fail_json(msg="New runner creation workflow requires python-gitlab 4.0.0 or higher")
351 else:
352 runner = self._gitlab.user.runners.create(arguments)
353 except gitlab.exceptions.GitlabCreateError as e:
354 self._module.fail_json(msg=f"Failed to create runner: {e}")
355
356 return runner
357
358 """
359 @param runner Runner object
360 @param arguments Attributes of the runner
361 """
362
363 def update_runner(self, runner, arguments):
364 changed = False
365
366 for arg_key, arg_value in arguments.items():
367 if arg_value is not None or arg_key == "maximum_timeout":
368 if isinstance(arg_value, list):
369 list1 = getattr(runner, arg_key)
370 list1.sort()
371 list2 = arg_value
372 list2.sort()
373 if list1 != list2:
374 setattr(runner, arg_key, arg_value)
375 changed = True
376 else:
377 if getattr(runner, arg_key) != arg_value:
378 setattr(runner, arg_key, arg_value)
379 changed = True
380
381 return (changed, runner)
382
383 """
384 @param description Description of the runner
385 """
386
387 def find_runner(self, description):
388 runners = self._runners_endpoint(**list_all_kwargs)
389
390 for runner in runners:
391 # python-gitlab 2.2 through at least 2.5 returns a list of dicts for list() instead of a Runner
392 # object, so we need to handle both
393 if hasattr(runner, "description"):
394 if runner.description == description:
395 return self._gitlab.runners.get(runner.id)
396 else:
397 if runner["description"] == description:
398 return self._gitlab.runners.get(runner["id"])
399
400 """
401 @param description Description of the runner
402 """
403
404 def exists_runner(self, description):
405 # When runner exists, object will be stored in self.runner_object.
406 runner = self.find_runner(description)
407
408 if runner:
409 self.runner_object = runner
410 return True
411 return False
412
413 def delete_runner(self):
414 if self._module.check_mode:
415 return True
416
417 runner = self.runner_object
418
419 return runner.delete()
420
421
422 def main():
423 argument_spec = basic_auth_argument_spec()
424 argument_spec.update(auth_argument_spec())
425 argument_spec.update(
426 dict(
427 description=dict(type="str", required=True, aliases=["name"]),
428 active=dict(type="bool", default=True),
429 paused=dict(type="bool", default=False),
430 owned=dict(type="bool", default=False),
431 tag_list=dict(type="list", elements="str", default=[]),
432 run_untagged=dict(type="bool", default=True),
433 locked=dict(type="bool", default=False),
434 access_level=dict(type="str", choices=["not_protected", "ref_protected"]),
435 access_level_on_creation=dict(type="bool", default=True),
436 maximum_timeout=dict(type="int", default=3600),
437 registration_token=dict(type="str", no_log=True),
438 project=dict(type="str"),
439 group=dict(type="str"),
440 state=dict(type="str", default="present", choices=["absent", "present"]),
441 )
442 )
443
444 module = AnsibleModule(
445 argument_spec=argument_spec,
446 mutually_exclusive=[
447 ["api_username", "api_token"],
448 ["api_username", "api_oauth_token"],
449 ["api_username", "api_job_token"],
450 ["api_token", "api_oauth_token"],
451 ["api_token", "api_job_token"],
452 ["project", "owned"],
453 ["group", "owned"],
454 ["project", "group"],
455 ["active", "paused"],
456 ],
457 required_together=[
458 ["api_username", "api_password"],
459 ],
460 required_one_of=[
461 ["api_username", "api_token", "api_oauth_token", "api_job_token"],
462 ],
463 supports_check_mode=True,
464 )
465
466 # check prerequisites and connect to gitlab server
467 gitlab_instance = gitlab_authentication(module)
468
469 state = module.params["state"]
470 runner_description = module.params["description"]
471 runner_active = module.params["active"]
472 runner_paused = module.params["paused"]
473 tag_list = module.params["tag_list"]
474 run_untagged = module.params["run_untagged"]
475 runner_locked = module.params["locked"]
476 access_level = module.params["access_level"]
477 if module.params["maximum_timeout"] == 0:
478 maximum_timeout = None
479 else:
480 maximum_timeout = module.params["maximum_timeout"]
481 registration_token = module.params["registration_token"]
482 project = module.params["project"]
483 group = module.params["group"]
484
485 gitlab_project = None
486 gitlab_group = None
487
488 if project:
489 try:
490 gitlab_project = gitlab_instance.projects.get(project)
491 except gitlab.exceptions.GitlabGetError as e:
492 module.fail_json(msg=f"No such a project {project}", exception=e)
493 elif group:
494 try:
495 gitlab_group = gitlab_instance.groups.get(group)
496 except gitlab.exceptions.GitlabGetError as e:
497 module.fail_json(msg=f"No such a group {group}", exception=e)
498
499 gitlab_runner = GitLabRunner(module, gitlab_instance, gitlab_group, gitlab_project)
500 runner_exists = gitlab_runner.exists_runner(runner_description)
501
502 if state == "absent":
503 if runner_exists:
504 gitlab_runner.delete_runner()
505 module.exit_json(changed=True, msg=f"Successfully deleted runner {runner_description}")
506 else:
507 module.exit_json(changed=False, msg="Runner deleted or does not exists")
508
509 if state == "present":
510 runner_values = {
511 "active": runner_active,
512 "tag_list": tag_list,
513 "run_untagged": run_untagged,
514 "locked": runner_locked,
515 "access_level": access_level,
516 "maximum_timeout": maximum_timeout,
517 "registration_token": registration_token,
518 "group": group,
519 "project": project,
520 }
521 if LooseVersion(gitlab_runner._gitlab.version()[0]) >= LooseVersion("14.8.0"):
522 # the paused attribute for runners is available since 14.8
523 runner_values["paused"] = runner_paused
524 if gitlab_runner.create_or_update_runner(runner_description, runner_values):
525 module.exit_json(
526 changed=True,
527 runner=gitlab_runner.runner_object._attrs,
528 msg=f"Successfully created or updated the runner {runner_description}",
529 )
530 else:
531 module.exit_json(
532 changed=False,
533 runner=gitlab_runner.runner_object._attrs,
534 msg=f"No need to update the runner {runner_description}",
535 )
536
537
538 if __name__ == "__main__":
539 main()