pyinfra-gitlab-kit 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,922 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import subprocess
6
+ from typing import Any, cast
7
+
8
+ from pyinfra import host
9
+ from pyinfra.api import FunctionCommand, OperationError, operation
10
+
11
+ from ..facts.instance import SopsSecret
12
+
13
+ # ═══════════════════════════════════════════════════════════════════════════════
14
+ # Internal glab API wrapper
15
+ # ═══════════════════════════════════════════════════════════════════════════════
16
+
17
+
18
+ def _run_glab_api(
19
+ method: str,
20
+ path: str,
21
+ *,
22
+ fields: dict[str, str] | None = None,
23
+ list_fields: list[tuple[str, str]] | None = None,
24
+ raw_field: dict[str, str] | None = None,
25
+ json_data: dict | None = None,
26
+ expect_404: bool = False,
27
+ ) -> dict | list | None:
28
+ """
29
+ Call ``glab api`` and return the parsed JSON payload (or ``None`` for 404).
30
+
31
+ Pure subprocess wrapper extracted for unit-testing: monkey-patch this
32
+ symbol to avoid hitting the real GitLab API in tests.
33
+
34
+ + method: HTTP verb (``"GET"``, ``"POST"``, ``"PUT"``, ``"DELETE"``).
35
+ + path: API path under ``/api/v4`` (e.g. ``"groups/acme/variables"``).
36
+ + fields: ``-f key=value`` pairs (URL-encoded form fields). Keys must
37
+ be unique; use ``list_fields`` when the same key must appear multiple
38
+ times, or prefer ``json_data`` for complex payloads.
39
+ + list_fields: ``-f key=value`` pairs where the same key may repeat.
40
+ + raw_field: ``-F key=@-`` pairs (passed through stdin). Used for
41
+ ``SOPS_AGE_KEY`` which contains a newline-terminated armored block.
42
+ + json_data: when provided, the request body is sent as JSON via stdin
43
+ (``--input -`` with ``Content-Type: application/json``). Prefer this
44
+ over ``list_fields`` for array values (e.g. deploy token scopes).
45
+ + expect_404: when True, return ``None`` instead of raising on 404.
46
+ """
47
+ # Read GITLAB_TOKEN / GITLAB_HOST from pyinfra config.ENV when running
48
+ # inside a pyinfra deploy, falling back to os.environ for direct calls.
49
+ gitlab_token: str = ""
50
+ gitlab_host: str | None = None
51
+ try:
52
+ from pyinfra import config as _config
53
+
54
+ _env: dict = getattr(_config, "ENV", {}) or {}
55
+ gitlab_token = cast("str", _env.get("GITLAB_TOKEN")) or os.environ.get("GITLAB_TOKEN", "")
56
+ gitlab_host = _env.get("GITLAB_HOST") or os.environ.get("GITLAB_HOST")
57
+ except Exception:
58
+ gitlab_token = os.environ.get("GITLAB_TOKEN", "")
59
+ gitlab_host = os.environ.get("GITLAB_HOST")
60
+ if not gitlab_host:
61
+ raise OperationError("GITLAB_HOST is required — set it in config.ENV or the environment")
62
+
63
+ env = os.environ.copy()
64
+ env["GITLAB_TOKEN"] = gitlab_token
65
+ env["GITLAB_HOST"] = gitlab_host
66
+
67
+ cmd = ["glab", "api", path, "--method", method.upper(), "--hostname", gitlab_host]
68
+
69
+ stdin_data: str | None = None
70
+ if json_data is not None:
71
+ cmd += ["-H", "Content-Type: application/json", "--input", "-"]
72
+ stdin_data = json.dumps(json_data)
73
+ else:
74
+ for key, value in (fields or {}).items():
75
+ cmd += ["-f", f"{key}={value}"]
76
+ for key, value in list_fields or []:
77
+ cmd += ["-f", f"{key}={value}"]
78
+ if raw_field:
79
+ # glab supports a single -F key=@- per call; chain via stdin.
80
+ # For simplicity we serialise multiple raw fields by joining (rare case).
81
+ for key, value in raw_field.items():
82
+ cmd += ["-F", f"{key}=@-"]
83
+ stdin_data = value # only the last wins; callers should pass one entry
84
+
85
+ try:
86
+ result = subprocess.run(
87
+ cmd,
88
+ env=env,
89
+ input=stdin_data,
90
+ text=True,
91
+ capture_output=True,
92
+ check=False,
93
+ )
94
+ except FileNotFoundError as exc:
95
+ raise OperationError("glab binary not found in PATH") from exc
96
+
97
+ if result.returncode != 0:
98
+ if expect_404 and ("404" in result.stderr or "Not Found" in result.stderr):
99
+ return None
100
+ raise OperationError(f"glab api {method} {path} failed (rc={result.returncode}): {result.stderr.strip()}")
101
+
102
+ if not result.stdout.strip():
103
+ return None
104
+ return json.loads(result.stdout)
105
+
106
+
107
+ # ═══════════════════════════════════════════════════════════════════════════════
108
+ # CI/CD Variable helpers
109
+ # ═══════════════════════════════════════════════════════════════════════════════
110
+
111
+
112
+ def _fn_ensure_variable(
113
+ *,
114
+ list_path: str,
115
+ label: str,
116
+ key: str,
117
+ value: str,
118
+ masked: bool,
119
+ protected: bool,
120
+ variable_type: str,
121
+ raw: bool,
122
+ environment_scope: str,
123
+ present: bool,
124
+ ) -> None:
125
+ """
126
+ Create / update / delete a GitLab CI/CD variable.
127
+
128
+ Idempotent. Works for both group-level (``groups/{g}/variables``) and project-
129
+ level (``projects/{p}/variables``) resources — the caller supplies ``list_path``
130
+ and a human-readable ``label`` for log messages.
131
+
132
+ Compares against the current state and only mutates on diff. The variable value is
133
+ read from GitLab API (which returns it in plain) to detect drift when
134
+ ``masked=False``; for ``masked=True`` we cannot read it back, so we always PUT to
135
+ ensure freshness (still idempotent w.r.t. the controlling config).
136
+ """
137
+ current = _run_glab_api("GET", f"{list_path}/{key}", expect_404=True)
138
+
139
+ if not present:
140
+ if current is None:
141
+ print(f" GitLab {label} variable {key}: already absent")
142
+ return
143
+ _run_glab_api("DELETE", f"{list_path}/{key}")
144
+ print(f" GitLab {label} variable {key}: deleted")
145
+ return
146
+
147
+ fields = {
148
+ "key": key,
149
+ "value": value,
150
+ "masked": "true" if masked else "false",
151
+ "protected": "true" if protected else "false",
152
+ "variable_type": variable_type,
153
+ "raw": "true" if raw else "false",
154
+ "environment_scope": environment_scope,
155
+ }
156
+
157
+ if current is None:
158
+ _run_glab_api("POST", list_path, fields=fields)
159
+ print(f" GitLab {label} variable {key}: created")
160
+ return
161
+
162
+ current = cast("dict[str, Any]", current)
163
+
164
+ # Detect drift on visible attributes; value is masked, so we can't compare it.
165
+ drift = (
166
+ current.get("masked") != masked
167
+ or current.get("protected") != protected
168
+ or current.get("variable_type") != variable_type
169
+ or current.get("raw") != raw
170
+ or current.get("environment_scope") != environment_scope
171
+ or (not masked and current.get("value") != value)
172
+ )
173
+ if drift or masked:
174
+ # When masked we cannot detect value drift → always PUT to be safe.
175
+ _run_glab_api("PUT", f"{list_path}/{key}", fields=fields)
176
+ print(f" GitLab {label} variable {key}: updated")
177
+ else:
178
+ print(f" GitLab {label} variable {key}: already up to date")
179
+
180
+
181
+ def _fn_ensure_group_variable(
182
+ *,
183
+ group: str,
184
+ key: str,
185
+ value: str,
186
+ masked: bool,
187
+ protected: bool,
188
+ variable_type: str,
189
+ raw: bool,
190
+ environment_scope: str,
191
+ present: bool,
192
+ ) -> None:
193
+ from urllib.parse import quote_plus
194
+
195
+ encoded_group = quote_plus(group)
196
+ _fn_ensure_variable(
197
+ list_path=f"groups/{encoded_group}/variables",
198
+ label=f"group {group}",
199
+ key=key,
200
+ value=value,
201
+ masked=masked,
202
+ protected=protected,
203
+ variable_type=variable_type,
204
+ raw=raw,
205
+ environment_scope=environment_scope,
206
+ present=present,
207
+ )
208
+
209
+
210
+ def _fn_ensure_project_variable(
211
+ *,
212
+ project: str,
213
+ key: str,
214
+ value: str,
215
+ masked: bool,
216
+ protected: bool,
217
+ variable_type: str,
218
+ raw: bool,
219
+ environment_scope: str,
220
+ present: bool,
221
+ ) -> None:
222
+ from urllib.parse import quote_plus
223
+
224
+ encoded_project = quote_plus(project)
225
+ _fn_ensure_variable(
226
+ list_path=f"projects/{encoded_project}/variables",
227
+ label=f"project {project}",
228
+ key=key,
229
+ value=value,
230
+ masked=masked,
231
+ protected=protected,
232
+ variable_type=variable_type,
233
+ raw=raw,
234
+ environment_scope=environment_scope,
235
+ present=present,
236
+ )
237
+
238
+
239
+ # ═══════════════════════════════════════════════════════════════════════════════
240
+ # Protected branch helpers
241
+ # ═══════════════════════════════════════════════════════════════════════════════
242
+
243
+
244
+ def _fn_ensure_protected_branch(
245
+ *,
246
+ project: str,
247
+ branch: str,
248
+ push_access_level: int,
249
+ merge_access_level: int,
250
+ allow_force_push: bool,
251
+ code_owner_approval_required: bool,
252
+ present: bool,
253
+ ) -> None:
254
+ """
255
+ Create / replace / delete a protected branch rule on a project.
256
+
257
+ Idempotent.
258
+ The GitLab API does not support PUT on this resource: when a rule exists
259
+ with different access levels, we DELETE then POST.
260
+ """
261
+ from urllib.parse import quote_plus
262
+
263
+ encoded_project = quote_plus(project)
264
+ encoded_branch = quote_plus(branch)
265
+ list_path = f"projects/{encoded_project}/protected_branches"
266
+
267
+ current = _run_glab_api("GET", f"{list_path}/{encoded_branch}", expect_404=True)
268
+
269
+ if not present:
270
+ if current is None:
271
+ print(f" Protected branch {project}@{branch}: already absent")
272
+ return
273
+ _run_glab_api("DELETE", f"{list_path}/{encoded_branch}")
274
+ print(f" Protected branch {project}@{branch}: deleted")
275
+ return
276
+
277
+ fields = {
278
+ "name": branch,
279
+ "push_access_level": str(push_access_level),
280
+ "merge_access_level": str(merge_access_level),
281
+ "allow_force_push": "true" if allow_force_push else "false",
282
+ "code_owner_approval_required": "true" if code_owner_approval_required else "false",
283
+ }
284
+
285
+ if current is not None:
286
+ current = cast("dict[str, Any]", current)
287
+ # Compare access levels (GitLab returns lists of access-level objects).
288
+ push_levels = [lvl.get("access_level") for lvl in current.get("push_access_levels", [])]
289
+ merge_levels = [lvl.get("access_level") for lvl in current.get("merge_access_levels", [])]
290
+ if (
291
+ push_levels == [push_access_level]
292
+ and merge_levels == [merge_access_level]
293
+ and current.get("allow_force_push") == allow_force_push
294
+ and current.get("code_owner_approval_required") == code_owner_approval_required
295
+ ):
296
+ print(f" Protected branch {project}@{branch}: already up to date")
297
+ return
298
+ _run_glab_api("DELETE", f"{list_path}/{encoded_branch}")
299
+
300
+ _run_glab_api("POST", list_path, fields=fields)
301
+ print(f" Protected branch {project}@{branch}: applied")
302
+
303
+
304
+ # ═══════════════════════════════════════════════════════════════════════════════
305
+ # Deploy token helpers
306
+ # ═══════════════════════════════════════════════════════════════════════════════
307
+
308
+
309
+ def _fn_ensure_deploy_token(
310
+ project: str,
311
+ token_name: str,
312
+ scopes: list[str],
313
+ username: str,
314
+ present: bool,
315
+ token_file: str | None,
316
+ ) -> None:
317
+ """
318
+ FunctionCommand body for :func:`gitlab_deploy_token`.
319
+ """
320
+ encoded = project.replace("/", "%2F")
321
+ list_path = f"projects/{encoded}/deploy_tokens"
322
+
323
+ # Check current state.
324
+ existing = _run_glab_api("GET", list_path, expect_404=True) or []
325
+
326
+ if not present:
327
+ current = next((t for t in existing if t.get("name") == token_name), None)
328
+ if current:
329
+ _run_glab_api("DELETE", f"{list_path}/{current['id']}")
330
+ return
331
+
332
+ # Token already exists → idempotent (token value cannot be retrieved afterwards).
333
+ if any(t.get("name") == token_name for t in existing):
334
+ print(f" Deploy token {token_name!r} already exists on project {project!r}")
335
+ return
336
+
337
+ # Create new token. Use JSON — glab's -f form encoding cannot handle
338
+ # the repeated scopes array key properly (last value wins).
339
+ created = _run_glab_api(
340
+ "POST",
341
+ list_path,
342
+ json_data={"name": token_name, "username": username, "scopes": scopes},
343
+ )
344
+
345
+ if created:
346
+ created = cast("dict[str, Any]", created)
347
+ print(f" Deploy token {token_name!r} created on project {project!r}")
348
+ if token_file:
349
+ with open(token_file, "w") as fh:
350
+ json.dump(
351
+ {"username": created.get("username"), "token": created.get("token")},
352
+ fh,
353
+ )
354
+
355
+
356
+ # ═══════════════════════════════════════════════════════════════════════════════
357
+ # Runner token helpers
358
+ # ═══════════════════════════════════════════════════════════════════════════════
359
+
360
+
361
+ def _fn_create_runner_token(
362
+ secrets_file: str,
363
+ token_key: str,
364
+ description: str,
365
+ runner_type: str,
366
+ group_id: int | None,
367
+ project_id: int | None,
368
+ tags: str,
369
+ ) -> None:
370
+ """
371
+ Called at execute time to create a GitLab runner via the API and store the token in
372
+ SOPS.
373
+ """
374
+ from pyinfra import config # import here to get live config.ENV at execute time
375
+
376
+ gitlab_token = config.ENV.get("GITLAB_TOKEN") or os.environ.get("GITLAB_TOKEN", "")
377
+ gitlab_host = config.ENV.get("GITLAB_HOST") or os.environ.get("GITLAB_HOST")
378
+ if not gitlab_host:
379
+ raise OperationError("GITLAB_HOST is required — set it in config.ENV or the environment")
380
+
381
+ env = os.environ.copy()
382
+ env["GITLAB_TOKEN"] = gitlab_token
383
+ env["GITLAB_HOST"] = gitlab_host
384
+
385
+ cmd = [
386
+ "glab",
387
+ "api",
388
+ "/user/runners",
389
+ "--hostname",
390
+ gitlab_host,
391
+ "-f",
392
+ f"runner_type={runner_type}",
393
+ "-f",
394
+ f"description={description}",
395
+ ]
396
+ if group_id:
397
+ cmd += ["-f", f"group_id={group_id}"]
398
+ if project_id:
399
+ cmd += ["-f", f"project_id={project_id}"]
400
+ if tags:
401
+ cmd += ["-f", f"tag_list={tags}"]
402
+
403
+ result = subprocess.check_output(cmd, env=env, text=True)
404
+ data = json.loads(result)
405
+ token = data["token"]
406
+
407
+ subprocess.check_call(
408
+ [
409
+ "sops",
410
+ "--set",
411
+ f'["{token_key}"] "{token}"',
412
+ secrets_file,
413
+ ]
414
+ )
415
+ print(f" Runner token stored in {secrets_file} under '{token_key}'")
416
+
417
+
418
+ def _fn_delete_runner_token(
419
+ secrets_file: str,
420
+ token_key: str,
421
+ ) -> None:
422
+ """
423
+ Called at execute time to remove the runner token from SOPS.
424
+ """
425
+ subprocess.check_call(
426
+ [
427
+ "sops",
428
+ "--set",
429
+ f'["{token_key}"] null',
430
+ secrets_file,
431
+ ]
432
+ )
433
+ print(f" Runner token '{token_key}' removed from {secrets_file}")
434
+
435
+
436
+ # ═══════════════════════════════════════════════════════════════════════════════
437
+ # Public operations
438
+ # ═══════════════════════════════════════════════════════════════════════════════
439
+
440
+
441
+ @operation()
442
+ def gitlab_group_variable(
443
+ group: str,
444
+ key: str,
445
+ value: str,
446
+ *,
447
+ masked: bool = True,
448
+ protected: bool = True,
449
+ variable_type: str = "env_var",
450
+ raw: bool = False,
451
+ environment_scope: str = "*",
452
+ present: bool = True,
453
+ ):
454
+ """
455
+ Ensure a GitLab CI/CD group-level variable matches the desired state.
456
+
457
+ + group: GitLab group path (e.g. ``"acme"`` or ``"acme/odoo"``).
458
+ + key: variable name (e.g. ``"SOPS_AGE_KEY"``).
459
+ + value: variable value (must already match GitLab masking rules when
460
+ ``masked=True`` — see GitLab docs).
461
+ + masked: hide the value in CI logs (default: ``True``).
462
+ + protected: only expose to protected refs (default: ``True``).
463
+ + variable_type: ``"env_var"`` (default) or ``"file"``.
464
+ + raw: when ``True``, GitLab will not expand ``$variable`` references
465
+ (default: ``False``).
466
+ + environment_scope: glob of environments allowed to read the variable
467
+ (default: ``"*"``).
468
+ + present: when ``False``, deletes the variable.
469
+
470
+ Requires ``glab`` installed locally and ``GITLAB_TOKEN`` (PAT or group
471
+ access token with ``api`` scope) + ``GITLAB_HOST``. Intended
472
+ for use on ``@local`` only.
473
+
474
+ The mutation is performed by a :class:`FunctionCommand`; idempotency is
475
+ checked at execute time inside that function (rather than via a
476
+ :class:`FactBase`) because the GitLab API call needs ``GITLAB_TOKEN``
477
+ which is typically not available in the fact-gathering phase.
478
+ """
479
+ if not group or not key:
480
+ raise OperationError("group and key are required")
481
+ if present and value is None:
482
+ raise OperationError("value is required when present=True")
483
+
484
+ yield FunctionCommand(
485
+ _fn_ensure_group_variable,
486
+ [],
487
+ {
488
+ "group": group,
489
+ "key": key,
490
+ "value": value if value is not None else "",
491
+ "masked": masked,
492
+ "protected": protected,
493
+ "variable_type": variable_type,
494
+ "raw": raw,
495
+ "environment_scope": environment_scope,
496
+ "present": present,
497
+ },
498
+ )
499
+
500
+
501
+ @operation()
502
+ def gitlab_project_variable(
503
+ project: str,
504
+ key: str,
505
+ value: str,
506
+ *,
507
+ masked: bool = True,
508
+ protected: bool = True,
509
+ variable_type: str = "env_var",
510
+ raw: bool = False,
511
+ environment_scope: str = "*",
512
+ present: bool = True,
513
+ ):
514
+ """
515
+ Ensure a GitLab CI/CD project-level variable matches the desired state.
516
+
517
+ + project: GitLab project path (e.g. ``"acme/odoo"``).
518
+ + key: variable name (e.g. ``"SOPS_AGE_KEY"``).
519
+ + value: variable value (must already match GitLab masking rules when
520
+ ``masked=True`` — see GitLab docs).
521
+ + masked: hide the value in CI logs (default: ``True``).
522
+ + protected: only expose to protected refs (default: ``True``).
523
+ + variable_type: ``"env_var"`` (default) or ``"file"``.
524
+ + raw: when ``True``, GitLab will not expand ``$variable`` references
525
+ (default: ``False``).
526
+ + environment_scope: glob of environments allowed to read the variable
527
+ (default: ``"*"``).
528
+ + present: when ``False``, deletes the variable.
529
+
530
+ Requires ``glab`` installed locally and ``GITLAB_TOKEN`` (PAT or project
531
+ access token with ``api`` scope, role ``Maintainer``) + optionally
532
+ ``GITLAB_HOST``. Intended for use on ``@local`` only.
533
+
534
+ The mutation is performed by a :class:`FunctionCommand`; idempotency is
535
+ checked at execute time inside that function (rather than via a
536
+ :class:`FactBase`) because the GitLab API call needs ``GITLAB_TOKEN``
537
+ which is typically not available in the fact-gathering phase.
538
+ """
539
+ if not project or not key:
540
+ raise OperationError("project and key are required")
541
+ if present and value is None:
542
+ raise OperationError("value is required when present=True")
543
+
544
+ yield FunctionCommand(
545
+ _fn_ensure_project_variable,
546
+ [],
547
+ {
548
+ "project": project,
549
+ "key": key,
550
+ "value": value if value is not None else "",
551
+ "masked": masked,
552
+ "protected": protected,
553
+ "variable_type": variable_type,
554
+ "raw": raw,
555
+ "environment_scope": environment_scope,
556
+ "present": present,
557
+ },
558
+ )
559
+
560
+
561
+ @operation()
562
+ def gitlab_protected_branch(
563
+ project: str,
564
+ branch: str,
565
+ *,
566
+ push_access_level: int = 40,
567
+ merge_access_level: int = 40,
568
+ allow_force_push: bool = False,
569
+ code_owner_approval_required: bool = False,
570
+ present: bool = True,
571
+ ):
572
+ """
573
+ Ensure a protected-branch rule matches the desired state.
574
+
575
+ + project: GitLab project path (e.g. ``"acme/odoo"``).
576
+ + branch: branch name or wildcard (e.g. ``"main"``, ``"release/*"``).
577
+ The op parameter is named ``branch`` (not ``name``) to avoid
578
+ colliding with pyinfra's reserved ``name=`` operation kwarg.
579
+ + push_access_level: GitLab access level allowed to push (default: ``40``
580
+ = Maintainer). 0=No-access, 30=Developer, 40=Maintainer, 60=Admin.
581
+ + merge_access_level: same scale, for merges (default: ``40``).
582
+ + allow_force_push: allow force-push from authorised users (default:
583
+ ``False``).
584
+ + code_owner_approval_required: require CODEOWNERS approval (default:
585
+ ``False``).
586
+ + present: when ``False``, removes the protection rule.
587
+
588
+ Idempotent. When the rule exists with different access levels, it is
589
+ DELETE+POSTed (the GitLab API does not support PUT on this resource).
590
+ """
591
+ if not project or not branch:
592
+ raise OperationError("project and branch are required")
593
+
594
+ yield FunctionCommand(
595
+ _fn_ensure_protected_branch,
596
+ [],
597
+ {
598
+ "project": project,
599
+ "branch": branch,
600
+ "push_access_level": push_access_level,
601
+ "merge_access_level": merge_access_level,
602
+ "allow_force_push": allow_force_push,
603
+ "code_owner_approval_required": code_owner_approval_required,
604
+ "present": present,
605
+ },
606
+ )
607
+
608
+
609
+ @operation()
610
+ def gitlab_deploy_token(
611
+ project: str,
612
+ token_name: str,
613
+ scopes: list[str] | None = None,
614
+ username: str | None = None,
615
+ present: bool = True,
616
+ token_file: str | None = None,
617
+ ):
618
+ """
619
+ Ensure a GitLab project deploy token matches the desired state.
620
+
621
+ + project: GitLab project path (e.g. ``"acme/odoo"``).
622
+ + token_name: display name (e.g. ``"foundry-deploy"``). Must be unique
623
+ per project.
624
+ + scopes: list of scopes to grant (default: ``["read_repository"]``).
625
+ + username: custom username (default: ``"gitlab+deploy-token-1"``).
626
+ GitLab auto-generates a username if not provided; explicitly
627
+ passing one produces a deterministic credential.
628
+ + present: when ``False``, deletes the deploy token if it exists.
629
+ + token_file: optional path where the operation writes the created
630
+ token (as JSON ``{"username": ..., "token": ...}``). Only
631
+ written when a new token is created; skipped when the token
632
+ already exists (the token value cannot be retrieved afterwards).
633
+
634
+ Requires ``glab`` installed locally and ``GITLAB_TOKEN`` (PAT or project
635
+ access token with ``api`` scope, role ``Maintainer``) + optionally
636
+ ``GITLAB_HOST``. Intended for use on ``@local`` only.
637
+
638
+ The mutation is performed by a :class:`FunctionCommand`; idempotency is
639
+ checked at execute time inside that function.
640
+ """
641
+ if not project or not token_name:
642
+ raise OperationError("project and token_name are required")
643
+
644
+ yield FunctionCommand(
645
+ _fn_ensure_deploy_token,
646
+ [],
647
+ {
648
+ "project": project,
649
+ "token_name": token_name,
650
+ "scopes": scopes or ["read_repository"],
651
+ "username": username or "gitlab+deploy-token-1",
652
+ "present": present,
653
+ "token_file": token_file,
654
+ },
655
+ )
656
+
657
+
658
+ @operation()
659
+ def runner_token(
660
+ description: str,
661
+ secrets_file: str,
662
+ token_key: str = "gitlab_runner_token",
663
+ runner_type: str = "group_type",
664
+ group_id: int | None = None,
665
+ project_id: int | None = None,
666
+ tags: str = "",
667
+ present: bool = True,
668
+ ):
669
+ """
670
+ Ensure a GitLab runner authentication token (``glrt-…``) exists in a SOPS-encrypted
671
+ secrets file.
672
+
673
+ + description: runner display name in the GitLab UI (also used for idempotency)
674
+ + secrets_file: absolute path to the SOPS-encrypted YAML file
675
+ + token_key: key in the YAML where the token is stored (default: ``"gitlab_runner_token"``)
676
+ + runner_type: ``"group_type"``, ``"project_type"``, or ``"instance_type"``
677
+ + group_id: GitLab group ID — required when ``runner_type="group_type"``
678
+ + project_id: GitLab project ID — required when ``runner_type="project_type"``
679
+ + tags: comma-separated tag list applied to the runner at creation time
680
+ + present: ``True`` to create, ``False`` to remove (default: ``True``)
681
+
682
+ Requires ``glab`` to be installed and ``GITLAB_TOKEN`` / ``GITLAB_HOST`` set
683
+ (e.g. via ``config.ENV``). Intended for use on ``@local`` only.
684
+
685
+ .. note::
686
+ On a fresh setup, run the deploy **twice**: the first run creates the token in
687
+ SOPS (Phase 0), the second run registers the runner using that token (Phase 2).
688
+ Subsequent runs are fully idempotent.
689
+ """
690
+ current_token = host.get_fact(SopsSecret, secrets_file=secrets_file, key=token_key)
691
+
692
+ if present:
693
+ if current_token:
694
+ host.noop(f"Runner token '{token_key}' already present in SOPS")
695
+ return
696
+
697
+ yield FunctionCommand(
698
+ _fn_create_runner_token,
699
+ [],
700
+ {
701
+ "secrets_file": secrets_file,
702
+ "token_key": token_key,
703
+ "description": description,
704
+ "runner_type": runner_type,
705
+ "group_id": group_id,
706
+ "project_id": project_id,
707
+ "tags": tags,
708
+ },
709
+ )
710
+ else:
711
+ if not current_token:
712
+ host.noop(f"Runner token '{token_key}' already absent from SOPS")
713
+ return
714
+
715
+ yield FunctionCommand(
716
+ _fn_delete_runner_token,
717
+ [],
718
+ {
719
+ "secrets_file": secrets_file,
720
+ "token_key": token_key,
721
+ },
722
+ )
723
+
724
+
725
+ # ═══════════════════════════════════════════════════════════════════════════════
726
+ # Project & protected tag helpers
727
+ # ═══════════════════════════════════════════════════════════════════════════════
728
+
729
+
730
+ def _fn_ensure_project(
731
+ *,
732
+ group: str,
733
+ name: str,
734
+ visibility: str,
735
+ present: bool,
736
+ ) -> None:
737
+ """
738
+ Create / delete a GitLab project under *group*.
739
+
740
+ Idempotent. The full project path is ``{group}/{name}``. When the project must be
741
+ created, the group is resolved to its numeric ``namespace_id`` via the API, then
742
+ the project is created under it.
743
+ """
744
+ from urllib.parse import quote_plus
745
+
746
+ full_path = f"{group}/{name}"
747
+ encoded_full = quote_plus(full_path)
748
+
749
+ current = _run_glab_api("GET", f"projects/{encoded_full}", expect_404=True)
750
+
751
+ if not present:
752
+ if current is None:
753
+ print(f" GitLab project {full_path}: already absent")
754
+ return
755
+ current = cast("dict[str, Any]", current)
756
+ _run_glab_api("DELETE", f"projects/{current['id']}")
757
+ print(f" GitLab project {full_path}: deleted")
758
+ return
759
+
760
+ if current is not None:
761
+ current = cast("dict[str, Any]", current)
762
+ if current.get("visibility") != visibility:
763
+ _run_glab_api(
764
+ "PUT",
765
+ f"projects/{current['id']}",
766
+ fields={"visibility": visibility},
767
+ )
768
+ print(f" GitLab project {full_path}: visibility updated to {visibility}")
769
+ else:
770
+ print(f" GitLab project {full_path}: already up to date")
771
+ return
772
+
773
+ encoded_group = quote_plus(group)
774
+ group_info = _run_glab_api("GET", f"groups/{encoded_group}")
775
+ group_info = cast("dict[str, Any]", group_info)
776
+ namespace_id = group_info["id"]
777
+
778
+ _run_glab_api(
779
+ "POST",
780
+ "projects",
781
+ fields={
782
+ "name": name,
783
+ "path": name,
784
+ "namespace_id": str(namespace_id),
785
+ "visibility": visibility,
786
+ },
787
+ )
788
+ print(f" GitLab project {full_path}: created")
789
+
790
+
791
+ def _fn_ensure_protected_tag(
792
+ *,
793
+ project: str,
794
+ tag_pattern: str,
795
+ create_access_level: int,
796
+ present: bool,
797
+ ) -> None:
798
+ """
799
+ Create / replace / delete a protected tag rule on a project.
800
+
801
+ Idempotent.
802
+ The GitLab API has no PUT for protected tags: when a rule exists with a
803
+ different ``create_access_level`` we DELETE then POST.
804
+ """
805
+ from urllib.parse import quote_plus
806
+
807
+ encoded_project = quote_plus(project)
808
+ encoded_pattern = quote_plus(tag_pattern)
809
+ list_path = f"projects/{encoded_project}/protected_tags"
810
+
811
+ current = _run_glab_api("GET", f"{list_path}/{encoded_pattern}", expect_404=True)
812
+
813
+ if not present:
814
+ if current is None:
815
+ print(f" Protected tag {project}@{tag_pattern}: already absent")
816
+ return
817
+ _run_glab_api("DELETE", f"{list_path}/{encoded_pattern}")
818
+ print(f" Protected tag {project}@{tag_pattern}: deleted")
819
+ return
820
+
821
+ if current is not None:
822
+ current = cast("dict[str, Any]", current)
823
+ create_levels = [lvl.get("access_level") for lvl in current.get("create_access_levels", [])]
824
+ if create_levels == [create_access_level]:
825
+ print(f" Protected tag {project}@{tag_pattern}: already up to date")
826
+ return
827
+ _run_glab_api("DELETE", f"{list_path}/{encoded_pattern}")
828
+
829
+ _run_glab_api(
830
+ "POST",
831
+ list_path,
832
+ fields={
833
+ "name": tag_pattern,
834
+ "create_access_level": str(create_access_level),
835
+ },
836
+ )
837
+ print(f" Protected tag {project}@{tag_pattern}: applied")
838
+
839
+
840
+ @operation()
841
+ def gitlab_project(
842
+ group: str,
843
+ name: str,
844
+ *,
845
+ visibility: str = "private",
846
+ present: bool = True,
847
+ ):
848
+ """
849
+ Ensure a GitLab project exists under *group* with the desired visibility.
850
+
851
+ + group: GitLab group path the project lives under (e.g.
852
+ ``"acme-locked-targets"``).
853
+ + name: project slug (e.g. ``"web"``). The full path is
854
+ ``{group}/{name}``.
855
+ + visibility: ``"private"`` (default), ``"internal"`` or ``"public"``.
856
+ + present: when ``False``, deletes the project if it exists.
857
+
858
+ Requires ``glab`` installed locally and ``GITLAB_TOKEN`` (a group access
859
+ token with ``api`` scope and at least Maintainer role on the group) +
860
+ ``GITLAB_HOST``. Intended for use on ``@local`` only.
861
+
862
+ The mutation is performed by a :class:`FunctionCommand`; idempotency is
863
+ checked at execute time inside that function because the GitLab API call
864
+ needs ``GITLAB_TOKEN`` which is typically not available in the
865
+ fact-gathering phase.
866
+ """
867
+ if not group or not name:
868
+ raise OperationError("group and name are required")
869
+
870
+ yield FunctionCommand(
871
+ _fn_ensure_project,
872
+ [],
873
+ {
874
+ "group": group,
875
+ "name": name,
876
+ "visibility": visibility,
877
+ "present": present,
878
+ },
879
+ )
880
+
881
+
882
+ @operation()
883
+ def gitlab_protected_tag(
884
+ project: str,
885
+ tag_pattern: str,
886
+ *,
887
+ create_access_level: int = 40,
888
+ present: bool = True,
889
+ ):
890
+ """
891
+ Ensure a protected tag rule matches the desired state on a project.
892
+
893
+ Used to make content-addressed vault tags immutable: protecting the
894
+ pattern (e.g. ``"16.0-*"``) restricts who may create or overwrite
895
+ matching tags.
896
+
897
+ + project: GitLab project path (e.g. ``"acme-locked-targets/web"``).
898
+ + tag_pattern: tag name or glob to protect (e.g. ``"16.0-*"``).
899
+ + create_access_level: minimum access level allowed to create matching
900
+ tags (default: ``40`` = Maintainer). ``0`` means "no one".
901
+ + present: when ``False``, removes the protection rule.
902
+
903
+ Requires ``glab`` installed locally and ``GITLAB_TOKEN`` (group access
904
+ token with ``api`` scope) + ``GITLAB_HOST``. Intended for use on
905
+ ``@local`` only.
906
+
907
+ The mutation is performed by a :class:`FunctionCommand`; idempotency is
908
+ checked at execute time inside that function.
909
+ """
910
+ if not project or not tag_pattern:
911
+ raise OperationError("project and tag_pattern are required")
912
+
913
+ yield FunctionCommand(
914
+ _fn_ensure_protected_tag,
915
+ [],
916
+ {
917
+ "project": project,
918
+ "tag_pattern": tag_pattern,
919
+ "create_access_level": create_access_level,
920
+ "present": present,
921
+ },
922
+ )