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,254 @@
1
+ from __future__ import annotations
2
+
3
+ from pyinfra import host
4
+ from pyinfra.api import HiddenValue, OperationError, StringCommand, operation
5
+ from pyinfra.operations import apt, files, systemd
6
+
7
+ from ..facts.runner import GitlabRunnerConcurrency, GitlabRunnerRegistrations, OsReleaseCodename
8
+
9
+
10
+ def hide(value: str | HiddenValue) -> HiddenValue:
11
+ """
12
+ Wrap a value so pyinfra masks it wherever the command is shown.
13
+
14
+ A value that is already wrapped comes back as it is: wrapping twice would mask the mask, and the
15
+ command would run with the literal string ``*MASKED*`` in place of the token.
16
+ """
17
+ return value if isinstance(value, HiddenValue) else HiddenValue(value)
18
+
19
+
20
+ def unmask(value: str | HiddenValue) -> str:
21
+ """
22
+ Return the real value of an argument the caller may have wrapped in
23
+ :class:`HiddenValue`.
24
+
25
+ pyinfra prints an operation's arguments, so a runner token passed as a plain string
26
+ ends up in the terminal and in whatever collects that output. Callers wrap it; this is
27
+ where it comes back out — and the same value stays wrapped inside the command, where
28
+ pyinfra unmasks it at execution.
29
+ """
30
+ return value.unmask() if isinstance(value, HiddenValue) else value
31
+
32
+
33
+ @operation()
34
+ def package(version: str = "17.9.0", present: bool = True):
35
+ """
36
+ Ensure the ``gitlab-runner`` APT package matches the desired state.
37
+
38
+ + version: pinned version to install (e.g. ``"17.9.0"``)
39
+ + present: when ``False``, removes the package and the APT repository
40
+
41
+ Both ``gitlab-runner`` and ``gitlab-runner-helper-images`` are managed
42
+ together to avoid unmet-dependencies errors introduced in v17.7.1.
43
+ Uses the OS codename from ``OsReleaseCodename`` so it works on any
44
+ Debian/Ubuntu release.
45
+ """
46
+ if not present:
47
+ yield from apt.packages._inner(
48
+ packages=["gitlab-runner", "gitlab-runner-helper-images"],
49
+ present=False,
50
+ )
51
+ yield from apt.repo._inner(
52
+ src="deb https://packages.gitlab.com/runner/gitlab-runner/debian/ bookworm main",
53
+ present=False,
54
+ filename="runner_gitlab-runner",
55
+ )
56
+ return
57
+
58
+ codename = host.get_fact(OsReleaseCodename)
59
+
60
+ yield from apt.packages._inner(
61
+ packages=["curl", "ca-certificates", "gnupg"],
62
+ update=True,
63
+ )
64
+
65
+ yield from apt.key._inner(
66
+ src="https://packages.gitlab.com/runner/gitlab-runner/gpgkey",
67
+ )
68
+
69
+ yield from apt.repo._inner(
70
+ src=f"deb https://packages.gitlab.com/runner/gitlab-runner/debian/ {codename} main",
71
+ filename="runner_gitlab-runner",
72
+ )
73
+
74
+ yield from apt.packages._inner(
75
+ packages=[
76
+ f"gitlab-runner={version}-1",
77
+ f"gitlab-runner-helper-images={version}-1",
78
+ ],
79
+ update=True,
80
+ )
81
+
82
+
83
+ @operation()
84
+ def registration(
85
+ url: str,
86
+ token: str | HiddenValue,
87
+ description: str,
88
+ executor: str = "shell",
89
+ tags: str = "",
90
+ run_untagged: bool = True,
91
+ docker_image: str = "alpine:latest",
92
+ present: bool = True,
93
+ ):
94
+ """
95
+ Ensure a runner is registered with the GitLab instance (idempotent).
96
+
97
+ + url: GitLab instance URL (e.g. ``"https://gitlab.com"``)
98
+ + token: runner authentication token (``glrt-…`` format)
99
+ + description: display name shown in GitLab UI — also used for idempotency check
100
+ + executor: ``"shell"`` or ``"docker"`` (default: ``"shell"``)
101
+ + tags: comma-separated tag list — ignored for ``glrt-`` tokens (configured server-side)
102
+ + run_untagged: ignored for ``glrt-`` tokens (configured server-side)
103
+ + docker_image: default image when executor is ``"docker"`` (default: ``"alpine:latest"``)
104
+ + present: when ``False``, unregisters the runner
105
+
106
+ Re-running the deploy is safe: registration is skipped when a runner with the
107
+ same ``description`` already appears in ``/etc/gitlab-runner/config.toml``.
108
+
109
+ Note: ``glrt-`` tokens (new runner creation workflow, GitLab ≥ 16.0) do not accept
110
+ ``--tag-list``, ``--run-untagged`` and similar flags — those are configured in the
111
+ GitLab UI when creating the runner.
112
+ """
113
+ if not url:
114
+ raise OperationError("url is required")
115
+ if not token:
116
+ raise OperationError("token is required")
117
+ if not description:
118
+ raise OperationError("description is required")
119
+
120
+ registered = host.get_fact(GitlabRunnerRegistrations)
121
+
122
+ if not present:
123
+ if description in registered:
124
+ yield f"gitlab-runner unregister --name '{description}'"
125
+ else:
126
+ host.noop(f"GitLab Runner '{description}' not registered")
127
+ return
128
+
129
+ if description in registered:
130
+ host.noop(f"GitLab Runner '{description}' already registered")
131
+ return
132
+
133
+ new_workflow = unmask(token).startswith("glrt-")
134
+
135
+ # The token stays wrapped: pyinfra masks it wherever the command is shown, and puts the real
136
+ # value back when it runs it.
137
+ parts: list[str | StringCommand] = [
138
+ "gitlab-runner register --non-interactive",
139
+ f"--url '{url}'",
140
+ StringCommand("--token '", hide(token), "'", _separator=""),
141
+ f"--description '{description}'",
142
+ f"--executor '{executor}'",
143
+ ]
144
+
145
+ # Legacy registration tokens support per-runner tag/untagged config.
146
+ # New glrt- tokens: these are set in the GitLab UI at runner creation time.
147
+ if not new_workflow:
148
+ if tags:
149
+ parts.append(f"--tag-list '{tags}'")
150
+ if run_untagged:
151
+ parts.append("--run-untagged")
152
+
153
+ if executor == "docker":
154
+ parts.append(f"--docker-image '{docker_image}'")
155
+
156
+ yield StringCommand(*parts)
157
+
158
+
159
+ @operation()
160
+ def concurrency(value: int = 1):
161
+ """
162
+ Ensure the runner's global concurrent job limit.
163
+
164
+ + param value: number of jobs the runner executes at once (minimum 1)
165
+
166
+ Writes ``concurrent`` in ``/etc/gitlab-runner/config.toml`` and restarts the
167
+ service only when the value changes. The registered config always carries the
168
+ line, so the edit is a substitution rather than an append.
169
+ """
170
+ if value < 1:
171
+ raise OperationError("concurrency must be at least 1")
172
+
173
+ if host.get_fact(GitlabRunnerConcurrency) == value:
174
+ host.noop(f"gitlab-runner already runs {value} jobs concurrently")
175
+ return
176
+
177
+ yield from files.line._inner(
178
+ path="/etc/gitlab-runner/config.toml",
179
+ line=r"^concurrent = [0-9]+$",
180
+ replace=f"concurrent = {value}",
181
+ )
182
+ yield from systemd.service._inner(service="gitlab-runner", restarted=True)
183
+
184
+
185
+ @operation()
186
+ def service(running: bool = True, enabled: bool = True):
187
+ """
188
+ Manage the gitlab-runner systemd service.
189
+
190
+ + running: whether the service should be running (default: ``True``)
191
+ + enabled: whether the service should start on boot (default: ``True``)
192
+ """
193
+ yield from systemd.service._inner(
194
+ service="gitlab-runner",
195
+ running=running,
196
+ enabled=enabled,
197
+ daemon_reload=True,
198
+ )
199
+
200
+
201
+ @operation()
202
+ def gitlab_runner(
203
+ url: str,
204
+ token: str | HiddenValue,
205
+ description: str,
206
+ executor: str = "shell",
207
+ tags: str = "",
208
+ run_untagged: bool = True,
209
+ docker_image: str = "alpine:latest",
210
+ version: str = "17.9.0",
211
+ present: bool = True,
212
+ ):
213
+ """
214
+ Ensure a complete GitLab Runner matches the desired state.
215
+
216
+ Composes :func:`package`, :func:`registration`, and :func:`service` via their
217
+ ``_inner`` functions to provide a single-entry-point operation for provisioning
218
+ a GitLab Runner host.
219
+
220
+ + url: GitLab instance URL (e.g. ``"https://gitlab.com"``)
221
+ + token: runner authentication token (``glrt-…`` format)
222
+ + description: display name shown in GitLab UI — also used for idempotency
223
+ + executor: ``"shell"`` or ``"docker"`` (default: ``"shell"``)
224
+ + tags: comma-separated tag list
225
+ + run_untagged: whether to run untagged jobs (default: ``True``)
226
+ + docker_image: default image when executor is ``"docker"`` (default: ``"alpine:latest"``)
227
+ + version: pinned gitlab-runner package version (default: ``"17.9.0"``)
228
+ + present: when ``False``, unregisters, stops, and uninstalls the runner
229
+
230
+ The individual sub-operations remain usable on their own for partial
231
+ management (e.g. only update the package without touching registration).
232
+ """
233
+ if not present:
234
+ yield from registration._inner(
235
+ url=url,
236
+ token=token,
237
+ description=description,
238
+ present=False,
239
+ )
240
+ yield from service._inner(running=False, enabled=False)
241
+ yield from package._inner(version=version, present=False)
242
+ return
243
+
244
+ yield from package._inner(version=version)
245
+ yield from registration._inner(
246
+ url=url,
247
+ token=token,
248
+ description=description,
249
+ executor=executor,
250
+ tags=tags,
251
+ run_untagged=run_untagged,
252
+ docker_image=docker_image,
253
+ )
254
+ yield from service._inner(running=True, enabled=True)
File without changes
@@ -0,0 +1,173 @@
1
+ Metadata-Version: 2.5
2
+ Name: pyinfra-gitlab-kit
3
+ Version: 0.1.1
4
+ Summary: GitLab automation with pyinfra — runners, CI variables, protected branches, deploy tokens
5
+ Project-URL: Homepage, https://github.com/maisim/pyinfra-gitlab-kit
6
+ Project-URL: Repository, https://github.com/maisim/pyinfra-gitlab-kit
7
+ Project-URL: Issues, https://github.com/maisim/pyinfra-gitlab-kit/issues
8
+ Project-URL: Changelog, https://github.com/maisim/pyinfra-gitlab-kit/releases
9
+ Author-email: Simon Maillard <simon@ogesta.fr>
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: ci,gitlab,infrastructure,pyinfra,runner
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: System Administrators
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Operating System :: POSIX :: Linux
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Requires-Python: <4.0,>=3.10
24
+ Requires-Dist: pyinfra<4,>=3.11
25
+ Requires-Dist: typing-extensions>=4.6
26
+ Description-Content-Type: text/markdown
27
+
28
+ # pyinfra-gitlab-kit
29
+
30
+ > **⚠️ ALPHA RELEASE**: This project is currently in the **Alpha** stage. The API, operation arguments, and features are subject to change at any time without backward compatibility. Do not use in production environments.
31
+
32
+ > **Packaging status**: this repository is the source of truth and is public. Install the latest
33
+ > release from PyPI; while the project is alpha, pin the version you use.
34
+
35
+ GitLab automation operations, facts, and deploys for [pyinfra](https://pyinfra.com/): install and
36
+ register GitLab Runner, manage project and group resources through the GitLab API, and install the
37
+ `glab` CLI.
38
+
39
+ [![CI](https://github.com/maisim/pyinfra-gitlab-kit/actions/workflows/python-publish.yml/badge.svg)](https://github.com/maisim/pyinfra-gitlab-kit/actions/workflows/python-publish.yml)
40
+ [![PyPI](https://img.shields.io/pypi/v/pyinfra-gitlab-kit)](https://pypi.org/project/pyinfra-gitlab-kit/)
41
+ [![Python versions](https://img.shields.io/pypi/pyversions/pyinfra-gitlab-kit)](https://pypi.org/project/pyinfra-gitlab-kit/)
42
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
43
+
44
+ ## Install
45
+
46
+ ```bash
47
+ pip install pyinfra-gitlab-kit
48
+ uv add pyinfra-gitlab-kit
49
+ ```
50
+
51
+ Requires pyinfra 3.11+ (`pyinfra>=3.11,<4`).
52
+
53
+ ## Package structure
54
+
55
+ ```
56
+ pyinfra_gitlab_kit/
57
+ operations/
58
+ glab.py — glab CLI install / uninstall
59
+ instance.py — GitLab API resources (projects, variables, protected refs, deploy tokens)
60
+ runner.py — GitLab Runner package, registration, service, concurrency
61
+ facts/
62
+ glab.py — GlabVersion
63
+ instance.py — SopsSecret (SOPS-decrypted values)
64
+ runner.py — GitlabRunnerRegistrations, GitlabRunnerConcurrency, OsReleaseCodename
65
+ deploys/
66
+ glab.py — install_glab (data-driven glab install)
67
+ runner.py — docker_kernel_tuning (sysctl for Docker executor)
68
+ ```
69
+
70
+ ## Operations
71
+
72
+ ### GitLab API (`operations.instance`)
73
+
74
+ All API operations target `GITLAB_HOST` and authenticate with `GITLAB_TOKEN`
75
+ (environment variables, or pyinfra `config.ENV`). They are intended for `@local`.
76
+
77
+ | Operation | Description |
78
+ | ------------------------- | ----------------------------------------------------------------------------- |
79
+ | `gitlab_project` | Ensure a project under a group, with the requested visibility. |
80
+ | `gitlab_project_variable` | Ensure a project-level CI variable (masked, protected, raw, file-type). |
81
+ | `gitlab_group_variable` | Ensure a group-level CI variable. |
82
+ | `gitlab_protected_branch` | Ensure a branch protection rule. |
83
+ | `gitlab_protected_tag` | Ensure a protected-tag rule (for immutable, content-addressed tags). |
84
+ | `gitlab_deploy_token` | Ensure a project deploy token with the given scopes. |
85
+ | `runner_token` | Manage a GitLab runner authentication token stored in SOPS. |
86
+
87
+ These wrap internal `_fn_ensure_*` helpers callable outside pyinfra's operation system (for example
88
+ from other Python code). Refer to the docstrings for full signatures.
89
+
90
+ ### GitLab Runner (`operations.runner`)
91
+
92
+ | Operation | Description |
93
+ | --------------- | -------------------------------------------------------- |
94
+ | `package` | APT install of GitLab Runner (Debian / Ubuntu). |
95
+ | `registration` | Register a runner via `gitlab-runner register`. |
96
+ | `service` | Enable / start the systemd service. |
97
+ | `concurrency` | Set the global `concurrent` job limit in `config.toml`. |
98
+ | `gitlab_runner` | Composite: `package` → `registration` → `service`. |
99
+
100
+ ### glab CLI (`operations.glab`)
101
+
102
+ | Operation | Description |
103
+ | ---------- | --------------------------------------------------------- |
104
+ | `glab_cli` | Install or remove the `glab` binary from GitHub releases. |
105
+
106
+ ## Facts
107
+
108
+ | Fact | Returns | Description |
109
+ | --------------------------- | ------------- | ---------------------------------------------------------- |
110
+ | `GlabVersion` | `str \| None` | Installed `glab` version. |
111
+ | `SopsSecret` | `str \| None` | Decrypted value of a SOPS-encrypted file. |
112
+ | `GitlabRunnerRegistrations` | `list[str]` | Runner names from `/etc/gitlab-runner/config.toml`. |
113
+ | `GitlabRunnerConcurrency` | `int` | Global `concurrent` limit (defaults to `1` when absent). |
114
+ | `OsReleaseCodename` | `str` | Debian / Ubuntu codename from `/etc/os-release`. |
115
+
116
+ ## Deploys
117
+
118
+ | Deploy | Description |
119
+ | ---------------------- | ------------------------------------------------------------------ |
120
+ | `docker_kernel_tuning` | Sysctl `kernel.keys.maxkeys=2000` for the Docker executor. |
121
+ | `install_glab` | Install the `glab` CLI, versioned from host data (`glab_version`). |
122
+
123
+ ## Usage
124
+
125
+ ### Via the pyinfra CLI
126
+
127
+ ```python
128
+ # runner_deploy.py
129
+ from pyinfra import host
130
+ from pyinfra_gitlab_kit import gitlab_runner
131
+
132
+ gitlab_runner(
133
+ url=host.data.get("gitlab_url"),
134
+ token=host.data.get("gitlab_runner_token"),
135
+ description=host.data.get("gitlab_runner_description"),
136
+ )
137
+ ```
138
+
139
+ ```bash
140
+ pyinfra -y @docker/ubuntu deploy.py
141
+ ```
142
+
143
+ ### As a Python API
144
+
145
+ ```python
146
+ from pyinfra_gitlab_kit.operations.instance import (
147
+ _fn_ensure_project_variable,
148
+ _fn_ensure_protected_branch,
149
+ _fn_ensure_deploy_token,
150
+ )
151
+
152
+ # Set GITLAB_HOST and GITLAB_TOKEN before calling.
153
+ _fn_ensure_project_variable(
154
+ project="acme/odoo",
155
+ key="SOPS_AGE_KEY",
156
+ value="<value from your secret store>",
157
+ masked=False,
158
+ protected=True,
159
+ variable_type="file",
160
+ raw=True,
161
+ environment_scope="*",
162
+ present=True,
163
+ )
164
+ ```
165
+
166
+ ## Contributing
167
+
168
+ Contributions are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for the development setup,
169
+ tests, and commit conventions.
170
+
171
+ ## License
172
+
173
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,17 @@
1
+ pyinfra_gitlab_kit/__init__.py,sha256=Pjw1UuBabHjiF9QGJg3w0mZhpYoQK-DGIG7uYqtwEDM,1430
2
+ pyinfra_gitlab_kit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ pyinfra_gitlab_kit/deploys/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ pyinfra_gitlab_kit/deploys/glab.py,sha256=-mw-LYfIexE3-4Xqgn1SQyyrRlJoupNMEuqXpin5rGs,1355
5
+ pyinfra_gitlab_kit/deploys/runner.py,sha256=LpcloJIZLOP3wSj-esupfoS5uk70ashOeXPjfeVzP7M,1166
6
+ pyinfra_gitlab_kit/facts/__init__.py,sha256=CKSJ4DoBzr8wa2LplYPA-xVog2l7PzTkcFVyHICGQj4,502
7
+ pyinfra_gitlab_kit/facts/glab.py,sha256=QskaP4S1V3kaEa2pDn83Yk6qKUbxjJuadLCOJftYGGQ,800
8
+ pyinfra_gitlab_kit/facts/instance.py,sha256=eGj2XL-eF53kXSIJpFWxd7RFU6uvdMob5k-XCKh75-c,1028
9
+ pyinfra_gitlab_kit/facts/runner.py,sha256=JVjvV0HC7PU57rEfofyWxThE_pNQ5uIb1cEVTo8okU0,2370
10
+ pyinfra_gitlab_kit/operations/__init__.py,sha256=CKSJ4DoBzr8wa2LplYPA-xVog2l7PzTkcFVyHICGQj4,502
11
+ pyinfra_gitlab_kit/operations/glab.py,sha256=qOOE2GfUTnwIs2bKAXgw-Ahs7T7cjUF7LK8XzT8oC_w,3644
12
+ pyinfra_gitlab_kit/operations/instance.py,sha256=Tn9vtbGPD61gfTV85BPo-vguz9JadSIjNO_RabY4BXI,33488
13
+ pyinfra_gitlab_kit/operations/runner.py,sha256=ZA6h-4udMDkGgqqXLRhwzL5dbzbfNhBnOCNfovR_P1c,8960
14
+ pyinfra_gitlab_kit-0.1.1.dist-info/METADATA,sha256=0loz8Nxub2REFlK2TNmxThHP42XoWnz7mc-dhl-DEIs,7540
15
+ pyinfra_gitlab_kit-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
16
+ pyinfra_gitlab_kit-0.1.1.dist-info/licenses/LICENSE,sha256=FZaS2_BP8PPu3bdbR-V2d-YSFUiFyeWLs0WlpNpS9Og,1071
17
+ pyinfra_gitlab_kit-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Simon Maillard
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.