feat(gitea_runner): add the gitea_runner role #293

Merged
Defame1297 merged 3 commits from feat/gitea-runner-role into main 2026-11-22 17:28:20 +00:00
27 changed files with 1987 additions and 2 deletions

No files matched your search

+2 -2
View File
@@ -4,7 +4,7 @@ An Ansible Collection of reusable, hardened roles for a self-hosted home lab:
Linux baseline, firewall, SSH, user management and, in later releases, Proxmox,
Gitea and Gitea Actions runner roles.
Status: roles arrive in waves. Release 1.9.0 holds the `docker`, `fail2ban`, `gitea`, `network_interfaces`, `sshd`, `system_baseline`, `systemd_hardening`, `traefik`, `ufw` and `user_management` roles (and the internal `_binary_update`, which `gitea` and `traefik` call).
Status: roles arrive in waves. Release 1.9.0 holds the `docker`, `fail2ban`, `gitea`, `network_interfaces`, `sshd`, `system_baseline`, `systemd_hardening`, `traefik`, `ufw` and `user_management` roles (and the internal `_binary_update`, which `gitea` and `traefik` call; `gitea_runner`, still unreleased, calls it too).
## Consuming
@@ -40,7 +40,7 @@ the environment that uses it) are met.
Still to come:
- Wave 2: `pve_vm`, `pve_lxc`, `gitea_runner`, `tailscale`, `cloudflared`, `pihole`.
- Wave 2: `pve_vm`, `pve_lxc`, `tailscale`, `cloudflared`, `pihole`.
- Wave 3: `rke2`, `proxmox_host`.
- Later, wave not yet assigned: `opnsense`, `proxmox_firewall`.
@@ -0,0 +1,10 @@
---
minor_changes:
- >-
gitea_runner - New role. Installs a Gitea Actions runner (``gitea-runner``) with Docker as a systemd service, with a
sha256-verified binary, registers it with a token minted on a Gitea host (optionally scoped to an owner or
repository), renders ``config.yaml``, and optionally schedules a weekly Docker prune that skips while a job runs,
installs pinned molecule test tooling behind a host-executor label, and removes the runner on request. With
``gitea_runner_update`` it downloads and verifies a new release before stopping anything and swaps it in through
the internal ``_binary_update`` role, with rollback on failure. A forced re-registration mints the new token before
it touches the current registration and is refused under CI.
+100
View File
@@ -0,0 +1,100 @@
# gitea_runner
Installs a Gitea Actions runner (`gitea-runner`) with Docker as a systemd service, registers it against a Gitea instance with a token minted on the `gitea_runner_token_host`, renders its `config.yaml`, optionally schedules a Docker prune, installs molecule test tooling behind a host-executor label, and optionally updates or removes the runner. Variables and their types are defined in [`meta/argument_specs.yml`](meta/argument_specs.yml), which is the source of truth.
## Supported platforms
Ubuntu 24.04 (noble), the image the molecule scenario runs on. The role uses `ansible.builtin.apt` and installs `docker.io`, so Debian-family hosts only, and needs outbound access to dl.gitea.com and Docker Hub (the Docker check pulls `ubuntu:24.04`); with the molecule tooling enabled also PyPI and Ansible Galaxy. On an unprivileged LXC host, Docker needs nesting enabled on the container.
## Requirements and run order
- Use it by its fully qualified name, `mortis.kamino.gitea_runner`.
- Hard dependency on the token host: `tasks/mint_token.yml` delegates `gitea actions generate-runner-token` to the inventory host named by `gitea_runner_token_host`. That host must be in the inventory and must already have Gitea installed (for example by `mortis.kamino.gitea`), with `app.ini` in place. A first install of the runner fails when it is down or has no Gitea. Registration only runs when `<gitea_runner_work_dir>/.runner` does not exist, so later runs do not need it. Under `--check` the registration is reported and not run.
- Registration inputs: `gitea_runner_token_host`, `gitea_runner_instance_url` and `gitea_runner_name` have empty role defaults and are asserted non-empty only in `tasks/mint_token.yml`, so a run that never registers is not blocked.
- Keep in step with the Gitea installation on the token host: the delegated command uses `gitea_runner_gitea_user`, `gitea_runner_gitea_install_dir` and `gitea_runner_gitea_app_dir` (defaults `git`, `/usr/local/bin`, `/etc/gitea`, the same as the defaults of `mortis.kamino.gitea`). They are separate variables from the `gitea` role's: changing the `gitea` role's values on the token host does not change these, and registration then runs the wrong path or user there. Set both.
- The registration token is generated on the fly, held in a `no_log` fact and passed to `gitea-runner register` through the `GITEA_RUNNER_REGISTRATION_TOKEN` environment variable, not argv. It is never written to a file by the role.
- The role creates `gitea_runner_group` and `gitea_runner_user` when they are missing; an existing account (for example the SSH login user) is reused.
- Docker is installed by this role (`tasks/docker.yml`) on first install, not by `mortis.kamino.docker`.
- Fact gathering must be on for `gitea_runner_force_register`: the backup name uses `ansible_date_time`.
- Updates: the update path stages the verified binary and hands the swap to `mortis.kamino._binary_update`, an internal role of this Collection.
- `gitea_runner_version` is asserted at role start to be a plain `X.Y.Z` release number, with no leading `v`. Pin it in inventory to move the runner independently of Collection releases; the role default changes only with a release.
- The executor and job image of a job come from its label's suffix (`:host` or `docker://<image>`); a label with no suffix runs its jobs on the host. `config.yaml` has no keys for them.
## Role variables
| Variable | Default | Description |
|---|---|---|
| `gitea_runner_remove` | `false` | Stop and disable the service, remove the unit, the binary and the Docker prune units. The role ends there: nothing is installed or registered in the same run, and the runner is not deregistered in Gitea. |
| `gitea_runner_remove_data` | `false` | With `gitea_runner_remove`, also delete the work directory, including the registration. |
| `gitea_runner_force_register` | `false` | Mint the token first (a failed mint stops before anything is touched), then back up `.runner`, stop the service, remove `.runner` and register again with the current `gitea_runner_instance_url` and `gitea_runner_registration_scope`; configure starts the service. Only the newest backup is kept. Refused when `GITHUB_ACTIONS`, `GITEA_ACTIONS` or `CI` is set on the controller; under `--check` nothing is removed or registered. |
| `gitea_runner_update` | `false` | Run the update tasks when the installed version differs from `gitea_runner_version`: download and verify to a staging path, then `mortis.kamino._binary_update` stops, backs up, swaps, restarts, checks the version and rolls back on failure. |
| `gitea_runner_version` | pinned in `defaults/main.yml` | Release to install, `X.Y.Z`. |
| `gitea_runner_download_url` | dl.gitea.com, linux amd64 (templated) | Binary URL. |
| `gitea_runner_checksum_url` | dl.gitea.com `.sha256` (templated) | Checksum file the runner binary is verified against (sha256) on install and update; it must list the file name of `gitea_runner_download_url`. |
| `gitea_runner_user` / `gitea_runner_group` | `gitea-runner` / `gitea-runner` | Daemon account; the user joins the `docker` group. |
| `gitea_runner_home` | `/home/gitea-runner` | Home of the daemon account. |
| `gitea_runner_install_dir` | `/usr/local/bin` | Binary directory. |
| `gitea_runner_work_dir` | `/var/lib/gitea-runner` | Registration file and `config.yaml`. Not passed to the runner as a job work directory: jobs use the upstream defaults. |
| `gitea_runner_service_unit` | `/etc/systemd/system/gitea-runner.service` | Unit path. |
| `gitea_runner_name` | empty (asserted when registering) | Registered runner name. |
| `gitea_runner_instance_url` | empty (asserted when registering) | Instance to register against. |
| `gitea_runner_token_host` | empty (asserted when registering) | Inventory host that mints the registration token. |
| `gitea_runner_registration_scope` | empty (instance-wide) | `--scope` of the token: an owner (user or organisation) or `owner/repo`. Format asserted at role start; read only when registering. |
| `gitea_runner_gitea_install_dir` | `/usr/local/bin` | Gitea binary directory on the token host. |
| `gitea_runner_gitea_user` | `git` | User of the delegated command on the token host. |
| `gitea_runner_gitea_app_dir` | `/etc/gitea` | `app.ini` directory on the token host. |
| `gitea_runner_log_level` | `info` | `log.level`. |
| `gitea_runner_capacity` | `1` | `runner.capacity`, concurrent jobs. |
| `gitea_runner_labels` | `docker`, `ubuntu-lxc` | Workflow labels; the molecule label is appended when enabled. |
| `gitea_runner_container_privileged` | `false` | `container.privileged`. |
| `gitea_runner_container_docker_host` | `unix:///var/run/docker.sock` | `container.docker_host`; `-` keeps the socket out of job containers. |
| `gitea_runner_container_volumes` | none (commented example in defaults) | Extra job container mounts; the key is omitted when undefined. |
| `gitea_runner_docker_prune_enabled` | `false` | Weekly systemd timer that prunes Docker data; skipped while a job container runs. |
| `gitea_runner_docker_prune_schedule` | `Sun *-*-* 04:30:00` | `OnCalendar` of the prune timer. |
| `gitea_runner_docker_prune_container_age`, `_image_age` | `24h`, `168h` | `until` filters (creation time) for containers, and for images and build cache. |
| `gitea_runner_docker_prune_job_max_age` | `21600` | Seconds; the prune skips while a younger container runs and ignores older ones as leaked job containers. |
| `gitea_runner_molecule_enabled` | `false` | Install molecule tooling and add the host label. |
| `gitea_runner_molecule_label` | `molecule` | Host-executor label name, registered as `<label>:host`. |
| `gitea_runner_molecule_venv` | `/opt/molecule-venv` | Tooling virtualenv. |
| `gitea_runner_collections_requirements_file` | empty (asserted when the molecule tooling is enabled) | Collections file on the control host that the molecule install reads; a change reinstalls the collections. |
| `gitea_runner_molecule_collections_path` | `/opt/molecule-collections` | Collections for the tested roles, installed from that file. |
| `gitea_runner_molecule_version`, `_plugins_version`, `_ansible_core_version`, `_docker_sdk_version` | pinned in `defaults/main.yml` | Tooling pins. |
## Tags
`gitea_runner` (everything), `remove`, `prereqs`, `docker`, `install`, `register`, `configure`, `health`, `update`, `molecule`, `prune`. The input asserts and the `prereqs` tasks are also tagged `always`.
## Example play
```yaml
- name: Install a Gitea Actions runner
hosts: runners
roles:
- role: mortis.kamino.gitea_runner
vars:
gitea_runner_instance_url: https://git.example.com/
gitea_runner_token_host: git-server
gitea_runner_name: runner-1
gitea_runner_capacity: 2
```
The play needs the token host in the inventory with Gitea installed.
Update with `-e gitea_runner_update=true`. Remove with `-e "gitea_runner_remove=true gitea_runner_remove_data=true"`.
Change the registration scope of a registered runner: set `gitea_runner_registration_scope`, then run the play by hand, not from CI, with `-e gitea_runner_force_register=true`. A plain run never re-registers, because `.runner` exists. The token is minted before `.runner` is touched, so a bad scope or an unreachable token host leaves the current registration running. Afterwards, in Site Administration → Actions → Runners: delete the old runner entry, now offline (a leftover copy of the old `.runner` would still authenticate against it), and reset the instance-wide registration token (the CLI returns the latest active one, so the old token stays valid and could register a new instance-wide runner). Confirm `GITEA_RUNNER_REGISTRATION_TOKEN` is not set in the Gitea server's environment.
## Tests
The `default` molecule scenario runs without a Gitea server and without Docker: a stub `docker.service`, a stub runner binary and a seeded `.runner` stand in for them, and the downloads come from local `file://` URLs. It covers the converge with the prune timer and an update through `_binary_update` (and its idempotence), the rendered `config.yaml` and unit, the prune gate script, a failed checksum that leaves the runner running, the input asserts, the CI refusal of a forced re-registration and the mint-before-drop order, and the remove path. Registration, the Docker install and the molecule tooling install are not covered.
## Notes
- Idempotent: yes.
- The role is not a state selector. `main.yml` always runs prerequisites and configure unless `gitea_runner_remove` is true; Docker and the binary install only when the binary is absent; registration only when `.runner` is absent (or `gitea_runner_force_register` removed it); remove only when `gitea_runner_remove` is true, and then every later task is skipped.
- Trust: with `gitea_runner_molecule_enabled`, jobs on the host-executor label run as the runner user, who is in the `docker` group, so they are root-equivalent on the runner host, which holds the registration and the secrets of every job it runs. Anyone who can run a workflow on that label can use it. Enable it only on a host whose registration scope (`gitea_runner_registration_scope`) is limited to repositories whose pushers you trust, and keep the job secrets of other repositories off that runner.
- The runner binary is verified against `gitea_runner_checksum_url` on install and update; a mismatch fails the download task, and on an update leaves the running binary in place.
- Handlers: `Restart Gitea Runner` runs when the config template changes or a registration happens.
- The Docker prune units (`gitea-runner-docker-prune.{service,timer}`) are written only while `gitea_runner_docker_prune_enabled` is true. Setting it back to false leaves them in place: run `systemctl disable --now gitea-runner-docker-prune.timer` by hand. `gitea_runner_remove` deletes them and the gate script. A run skipped because a job was running is not retried until the next timer elapse: shorten `gitea_runner_docker_prune_schedule` (e.g. `*-*-* 04:30:00`) if that happens.
- The play fails when `gitea-runner` is not `active` after start.
- `no_log` covers the token mint, the token fact and the registration command.
+91
View File
@@ -0,0 +1,91 @@
---
gitea_runner_remove_data: false
gitea_runner_remove: false
# Set true to force re-registration (e.g. after gitea_runner_instance_url or
# gitea_runner_registration_scope changes): mints the token, stops the daemon, removes the
# existing .runner file, then re-registers. Refused under CI. The old runner stays in Gitea as
# offline: delete it in Site Administration > Actions > Runners.
# The old registration is kept as .runner.bak.<timestamp> (0600); only the most recent backup is
# kept, previous ones are pruned before each forced run. Rollback:
# cp .runner.bak.<timestamp> .runner && systemctl restart gitea-runner
gitea_runner_force_register: false
# Runner logging
gitea_runner_log_level: info
# Runner behavior
# Jobs run at the same time (`runner.capacity`); size the host's memory and cores for it.
gitea_runner_capacity: 1
# Labels exposed to Gitea Actions
gitea_runner_labels:
- docker
- ubuntu-lxc
# Container executor settings
gitea_runner_container_privileged: false
gitea_runner_container_docker_host: unix:///var/run/docker.sock
# Weekly Docker prune (systemd timer). Off by default.
# The ages filter on creation time of the image, not on when it was pulled.
gitea_runner_docker_prune_enabled: false
gitea_runner_docker_prune_schedule: "Sun *-*-* 04:30:00"
gitea_runner_docker_prune_container_age: 24h
gitea_runner_docker_prune_image_age: 168h
# Seconds. The prune skips while a container younger than this runs and ignores older ones as
# leaked. Keep it above the longest job timeout.
gitea_runner_docker_prune_job_max_age: 21600
# Optional extra mounts
# gitea_runner_container_volumes:
# - /cache:/cache
gitea_runner_update: false
gitea_runner_version: "6.0.1"
# Gitea Runner defaults
gitea_runner_user: "gitea-runner"
gitea_runner_group: "gitea-runner"
gitea_runner_home: "/home/gitea-runner"
# Upstream renamed the project (and its release artifacts) from act_runner
# to gitea-runner; the old act_runner/... path now 301s to a 404.
gitea_runner_download_url: "https://dl.gitea.com/gitea-runner/{{ gitea_runner_version }}/gitea-runner-{{ gitea_runner_version }}-linux-amd64"
gitea_runner_checksum_url: "https://dl.gitea.com/gitea-runner/{{ gitea_runner_version }}/gitea-runner-{{ gitea_runner_version }}-linux-amd64.sha256"
gitea_runner_install_dir: "/usr/local/bin"
gitea_runner_work_dir: "/var/lib/gitea-runner"
gitea_runner_service_unit: "/etc/systemd/system/gitea-runner.service"
# No role default: set in inventory. Required only when the runner registers (asserted in
# tasks/mint_token.yml).
gitea_runner_name: ""
gitea_runner_instance_url: ""
# Inventory host that has Gitea installed and mints the registration token.
gitea_runner_token_host: ""
# Who the runner takes jobs from: empty = instance-wide, an owner (user or organisation) or
# owner/repo. Read only when registering: on an already registered runner a change takes
# effect with gitea_runner_force_register.
gitea_runner_registration_scope: ""
# How the delegated token command runs on gitea_runner_token_host. Keep in step with
# the gitea role on that host (separate variables, resolved per play).
gitea_runner_gitea_install_dir: "/usr/local/bin"
gitea_runner_gitea_user: "git"
gitea_runner_gitea_app_dir: "/etc/gitea"
# Optional molecule tooling for role tests. A host-executor label runs the molecule job on this
# host, against its own Docker daemon, so no job container needs the Docker socket. The tooling
# lives in a venv and is installed at provision time, so a CI run installs nothing.
# A job on that label runs as the runner user, who is in the docker group, so it is
# root-equivalent on this host: see Notes in the README before enabling it.
gitea_runner_molecule_enabled: false
gitea_runner_molecule_label: molecule
gitea_runner_molecule_venv: /opt/molecule-venv
gitea_runner_molecule_collections_path: /opt/molecule-collections
# Collections requirements file, on the control host, that the molecule install reads. No
# default: required when gitea_runner_molecule_enabled is true.
gitea_runner_collections_requirements_file: ""
gitea_runner_molecule_version: "26.11.0"
gitea_runner_molecule_plugins_version: "26.11.0"
# Held below 2.22: ansible-core 2.22 requires Python 3.13 or newer, and the venv uses the
# system Python of Ubuntu 24.04 (3.12).
gitea_runner_molecule_ansible_core_version: "2.21.6"
gitea_runner_molecule_docker_sdk_version: "7.2.0"
+6
View File
@@ -0,0 +1,6 @@
---
- name: Restart Gitea Runner
become: true
ansible.builtin.systemd:
name: gitea-runner
state: restarted
+287
View File
@@ -0,0 +1,287 @@
---
argument_specs:
main:
short_description: Install, register and run a Gitea Actions runner with a Docker executor
description:
- >-
Validates the inputs, then either removes the runner (C(gitea_runner_remove), which ends the role) or creates
the runner user, installs Docker and the C(gitea-runner) binary on first install, registers the runner when no
C(.runner) file exists, renders C(config.yaml), writes the systemd unit and starts the service. Optionally
schedules a Docker prune, updates the binary (C(gitea_runner_update)) with rollback through the internal
C(mortis.kamino._binary_update) role, and installs molecule test tooling (C(gitea_runner_molecule_enabled)).
The role builds no container image.
- >-
Registration delegates C(gitea actions generate-runner-token) to the inventory host C(gitea_runner_token_host),
which must have Gitea installed (for example by C(mortis.kamino.gitea)). The delegated command reads
C(gitea_runner_gitea_user), C(gitea_runner_gitea_install_dir) and C(gitea_runner_gitea_app_dir), which must
match the Gitea installation on that host; variables of the C(gitea) role do not reach this role.
C(gitea_runner_token_host), C(gitea_runner_instance_url) and C(gitea_runner_name) have empty role defaults and
are asserted only when registration runs, so a run that never registers is not blocked.
- >-
Reads gathered facts (C(ansible_date_time), for the forced re-registration backup name) and
C(ansible_check_mode).
options:
gitea_runner_remove:
type: bool
default: false
description:
- >-
When true the service is stopped and disabled, and the unit file, the binary, the Docker prune units and
the prune gate script are removed. The role ends there: nothing is installed, registered or configured in
the same run. The runner is not deregistered in Gitea.
gitea_runner_remove_data:
type: bool
default: false
description:
- Only read while C(gitea_runner_remove) is true. When true C(gitea_runner_work_dir), including the registration file, is deleted.
gitea_runner_force_register:
type: bool
default: false
description:
- >-
When true the registration token is minted first (a failed mint stops before anything is touched). Then,
when a registration exists, the previous C(.runner.bak.*) backups are pruned, C(.runner) is copied to
C(.runner.bak.<timestamp>) (mode 0600), the service is stopped, C(.runner) is removed and the runner is
registered again. Use it after C(gitea_runner_instance_url) or C(gitea_runner_registration_scope) changes.
Refused when C(GITHUB_ACTIONS), C(GITEA_ACTIONS) or C(CI) is set on the controller. Under C(--check)
nothing is removed or registered. The old runner stays in Gitea as offline; delete it in Site
Administration, Actions, Runners.
gitea_runner_update:
type: bool
default: false
description:
- >-
When true the update tasks run after configuration. The installed version is compared with
C(gitea_runner_version) and only a difference triggers a verified download to a staging path next to the
live binary. The swap is then handed to C(mortis.kamino._binary_update), which stops the service, backs
up the live binary, swaps, restarts, checks the version and rolls back on failure. A failed download
leaves the runner running.
gitea_runner_version:
type: str
description:
- >-
Runner release to install, for example C(6.0.1). The role default is a pinned version, see
C(defaults/main.yml); pin it in inventory to move the runner independently of Collection releases.
- >-
Asserted at role start to be C(X.Y.Z) digits only, with no leading C(v): it is used in the download URL
and compared with the version the binary reports.
gitea_runner_download_url:
type: raw
description:
- >-
URL of the runner binary. The role default is a Jinja expression built from C(gitea_runner_version) that
points at dl.gitea.com for linux amd64.
gitea_runner_checksum_url:
type: raw
description:
- >-
URL of the checksum file the runner binary is verified against (sha256) on install and update. It must list the
file name of C(gitea_runner_download_url). The role default is the dl.gitea.com C(.sha256) file built from
C(gitea_runner_version).
gitea_runner_user:
type: str
default: gitea-runner
description:
- System user that runs the daemon. Created by the role and added to the C(docker) group.
gitea_runner_group:
type: str
default: gitea-runner
description:
- Primary group of the runner user and group of its work directory. Created by the role.
gitea_runner_home:
type: path
default: /home/gitea-runner
description:
- Home of the runner user. The molecule tooling copies the collections requirements file there.
gitea_runner_install_dir:
type: path
default: /usr/local/bin
description:
- Directory that holds the C(gitea-runner) binary.
gitea_runner_work_dir:
type: path
default: /var/lib/gitea-runner
description:
- Directory with C(.runner) and C(config.yaml). It is not passed to the runner as a job work directory.
gitea_runner_service_unit:
type: path
default: /etc/systemd/system/gitea-runner.service
description:
- Path of the systemd unit file.
gitea_runner_name:
type: str
default: ""
description:
- >-
Name the runner registers with. The role default is empty; an empty value fails the registration
(C(tasks/mint_token.yml)), so runs that never register are not blocked.
gitea_runner_instance_url:
type: str
default: ""
description:
- >-
Gitea instance the runner registers against, for example C(https://git.example.com/). The role default is
empty; an empty value fails the registration (C(tasks/mint_token.yml)), so runs that never register are not
blocked.
gitea_runner_token_host:
type: str
default: ""
description:
- >-
Inventory host that has Gitea installed and mints the registration token; the token command is delegated
to it. The role default is empty; an empty value, or a host that is not in the inventory, fails the
registration.
gitea_runner_registration_scope:
type: str
default: ""
description:
- >-
Scope passed as C(--scope) to C(gitea actions generate-runner-token): an owner (user or organisation) or
C(owner/repo). Empty registers an instance-wide runner and passes no C(--scope). The format is asserted at
role start. Only read when registering, so on a runner that already has C(.runner) a change takes effect
with C(gitea_runner_force_register).
gitea_runner_gitea_install_dir:
type: path
default: /usr/local/bin
description:
- >-
Directory of the C(gitea) binary on C(gitea_runner_token_host), used by the delegated token command. Keep it
in step with the Gitea installation on that host.
gitea_runner_gitea_user:
type: str
default: git
description:
- >-
User that runs the delegated token command on C(gitea_runner_token_host). Keep it in step with the Gitea
installation on that host.
gitea_runner_gitea_app_dir:
type: path
default: /etc/gitea
description:
- >-
Directory of C(app.ini) on C(gitea_runner_token_host), passed with C(--config) to the delegated token
command. Keep it in step with the Gitea installation on that host.
gitea_runner_log_level:
type: str
default: info
description:
- Value of C(log.level) in C(config.yaml).
gitea_runner_capacity:
type: int
default: 1
description:
- Value of C(runner.capacity), the number of jobs run at once. Size the host's memory and cores for it.
gitea_runner_labels:
type: list
elements: str
default: [docker, ubuntu-lxc]
description:
- >-
Labels exposed to workflows. The executor and job image come from each label's suffix (C(:host) or
C(docker://<image>)); a label with no suffix runs its jobs on the host. When
C(gitea_runner_molecule_enabled) is true the label C(<gitea_runner_molecule_label>:host) is added
automatically.
gitea_runner_container_privileged:
type: bool
default: false
description:
- Value of C(container.privileged).
gitea_runner_container_docker_host:
type: str
default: "unix:///var/run/docker.sock"
description:
- >-
Value of C(container.docker_host). C(-) lets the runner find the daemon but does not mount the socket into
job containers.
gitea_runner_docker_prune_enabled:
type: bool
default: false
description:
- >-
When true a systemd timer runs C(gitea-runner-docker-prune.service), which prunes stopped containers, unused
images, build cache and anonymous volumes.
It is skipped while a container younger than C(gitea_runner_docker_prune_job_max_age) runs. Named volumes are kept.
- Setting it back to false leaves the units in place; C(gitea_runner_remove) deletes them.
gitea_runner_docker_prune_schedule:
type: str
default: "Sun *-*-* 04:30:00"
description:
- >-
C(OnCalendar) value of the prune timer. Only read when C(gitea_runner_docker_prune_enabled) is true, and
then asserted at role start to hold no newline or C(%).
gitea_runner_docker_prune_container_age:
type: str
default: 24h
description:
- >-
Stopped containers older than this are removed (the C(until) filter of C(docker container prune)). A number
with C(s), C(m) or C(h), asserted at role start when the prune is enabled.
gitea_runner_docker_prune_image_age:
type: str
default: 168h
description:
- >-
Unused images and build cache older than this are removed (the C(until) filter). It compares the creation
time of the image, not the pull time, so an old-built pinned image that no container uses is removed and pulled again.
Same format as C(gitea_runner_docker_prune_container_age).
gitea_runner_docker_prune_job_max_age:
type: int
default: 21600
description:
- >-
Seconds. The prune is skipped while a container younger than this runs (a job may use it). An older
container is treated as a leaked job container: it is logged and ignored. Keep it above the longest job timeout.
gitea_runner_container_volumes:
type: list
elements: str
description:
- Extra mounts for job containers, rendered as C(container.volumes). No role default exists and the key is omitted when undefined.
gitea_runner_molecule_enabled:
type: bool
default: false
description:
- >-
When true the molecule venv and collections are installed and the C(<gitea_runner_molecule_label>:host)
label is added to the runner. The runner user is in the C(docker) group, so a job on that label is
root-equivalent on the host. Needs C(gitea_runner_collections_requirements_file).
gitea_runner_molecule_label:
type: str
default: molecule
description:
- Name of the host-executor label, registered as C(<label>:host).
gitea_runner_molecule_venv:
type: path
default: /opt/molecule-venv
description:
- Virtualenv that holds the pinned molecule tooling.
gitea_runner_collections_requirements_file:
type: str
default: ""
description:
- >-
Collections requirements file, on the control host, that the molecule install reads. No role default:
asserted non-empty at role start when C(gitea_runner_molecule_enabled) is true.
- Its checksum is the molecule install stamp, so a change reinstalls the collections.
gitea_runner_molecule_collections_path:
type: path
default: /opt/molecule-collections
description:
- Collections path that receives the collections of the requirements file.
gitea_runner_molecule_version:
type: str
description:
- Pinned molecule release installed into the venv; see C(defaults/main.yml).
gitea_runner_molecule_plugins_version:
type: str
description:
- Pinned molecule-plugins release installed into the venv; see C(defaults/main.yml).
gitea_runner_molecule_ansible_core_version:
type: str
description:
- >-
Pinned ansible-core release installed into the venv; see C(defaults/main.yml). Held below 2.22, which
needs a newer Python than Ubuntu 24.04 ships.
gitea_runner_molecule_docker_sdk_version:
type: str
description:
- Pinned Docker SDK for Python release installed into the venv; see C(defaults/main.yml).
+18
View File
@@ -0,0 +1,18 @@
---
galaxy_info:
role_name: gitea_runner
namespace: mortis
author: Defame1297
license: GPL-3.0-or-later
description: Install, register, configure, update and remove a Gitea Actions runner with Docker and optional molecule test tooling.
min_ansible_version: "2.19"
platforms:
- name: Ubuntu
versions:
- noble
galaxy_tags:
- gitea
- actions
- runner
- docker
dependencies: []
@@ -0,0 +1,9 @@
---
# Role variables come from the inventory group_vars in molecule.yml. The first run updates the
# stub runner from 6.0.0 to 6.0.1 through mortis.kamino._binary_update; the idempotence run finds
# 6.0.1 and changes nothing.
- name: Converge
hosts: all
gather_facts: true
roles:
- role: mortis.kamino.gitea_runner
@@ -0,0 +1,16 @@
---
# Run by verify.yml in a child ansible-playbook process, because the CI guard reads the
# controller's environment (lookup env), which a play cannot change; the child gets its
# environment from the task that starts it, so the result does not depend on what the runner
# exports. With a CI variable set it fails at the CI guard; with them blank it fails at the
# registration inputs assert of the mint, because gitea_runner_token_host is empty. Either way
# it must stop before the registration is backed up, stopped or removed.
- name: Force a re-registration with a controlled environment
hosts: all
gather_facts: false
tasks:
- name: Run the role with gitea_runner_force_register
ansible.builtin.include_role:
name: mortis.kamino.gitea_runner
vars:
gitea_runner_force_register: true
@@ -0,0 +1,62 @@
---
# Runs on the repository's own runner (label kamino-molecule), in the molecule-ubuntu2404 image
# (MOLECULE_IMAGE, the pin in .gitea/workflows/molecule.yml). No Gitea server and no Docker
# daemon: prepare.yml seeds a stub docker.service, a stub runner binary that reports an older
# version, and a .runner file, so the role skips the Docker install and the registration, and
# the update downloads its new stub from local file:// URLs. The scenario downloads nothing.
# The container runs systemd as PID 1 with a writable cgroup; no privileged mode.
driver:
name: docker
platforms:
- name: runner-instance
image: ${MOLECULE_IMAGE}
pre_build_image: true
pull: true
command: /sbin/init
cgroupns_mode: host
volumes:
- /sys/fs/cgroup:/sys/fs/cgroup:rw
tmpfs:
- /run
- /run/lock
security_opts:
- apparmor=unconfined
provisioner:
name: ansible
# One source for every play, so a verify play that runs the role again renders the same
# configuration.
inventory:
group_vars:
all:
gitea_runner_update: true
gitea_runner_download_url: "file:///opt/molecule-download/gitea-runner-{{ gitea_runner_version }}-linux-amd64"
gitea_runner_checksum_url: "file:///opt/molecule-download/gitea-runner-{{ gitea_runner_version }}-linux-amd64.sha256"
gitea_runner_log_level: debug
gitea_runner_capacity: 2
gitea_runner_labels:
- "molecule-docker:docker://ubuntu:24.04"
- "molecule-shell:host"
gitea_runner_container_docker_host: "-"
gitea_runner_container_volumes:
- /cache:/cache
gitea_runner_docker_prune_enabled: true
gitea_runner_docker_prune_job_max_age: 3600
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
- destroy
@@ -0,0 +1,85 @@
---
# Stand-ins for what the scenario cannot have: a Docker daemon (the runner unit requires
# docker.service), an installed and registered runner (so the role skips the Docker install and
# the registration, which need Docker Hub and a Gitea server), and the release files of two
# newer versions behind file:// URLs. 6.0.1 has a matching checksum file, 6.0.2 a wrong one.
# The stub binary answers --version and, for `daemon`, sleeps like a running service.
- name: Prepare
hosts: all
gather_facts: false
tasks:
- name: Write a stub docker.service
ansible.builtin.copy:
dest: /etc/systemd/system/docker.service
mode: "0644"
content: |
[Unit]
Description=Docker stub for molecule
[Service]
Type=oneshot
ExecStart=/bin/true
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
- name: Start the stub docker.service
ansible.builtin.systemd:
name: docker
state: started
daemon_reload: true
- name: Create the download directory
ansible.builtin.file:
path: /opt/molecule-download
state: directory
mode: "0755"
- name: Write the installed stub runner and the release files
ansible.builtin.copy:
dest: "{{ gitea_runner_test_stub.dest }}"
mode: "0755"
content: |
#!/bin/sh
case "$1" in
--version) echo "gitea-runner version v{{ gitea_runner_test_stub.version }}" ;;
daemon) exec sleep infinity ;;
*) echo "stub runner: unexpected arguments: $*" >&2; exit 2 ;;
esac
loop:
- {dest: /usr/local/bin/gitea-runner, version: 6.0.0}
- {dest: /opt/molecule-download/gitea-runner-6.0.1-linux-amd64, version: 6.0.1}
- {dest: /opt/molecule-download/gitea-runner-6.0.2-linux-amd64, version: 6.0.2}
loop_control:
loop_var: gitea_runner_test_stub
label: "{{ gitea_runner_test_stub.dest }}"
- name: Hash the 6.0.1 release file
ansible.builtin.stat:
path: /opt/molecule-download/gitea-runner-6.0.1-linux-amd64
checksum_algorithm: sha256
register: gitea_runner_test_release
- name: Write the checksum files, the 6.0.2 one wrong
ansible.builtin.copy:
dest: "/opt/molecule-download/gitea-runner-{{ gitea_runner_test_sum.version }}-linux-amd64.sha256"
mode: "0644"
content: "{{ gitea_runner_test_sum.sum }} gitea-runner-{{ gitea_runner_test_sum.version }}-linux-amd64\n"
loop:
- {version: 6.0.1, sum: "{{ gitea_runner_test_release.stat.checksum }}"}
- {version: 6.0.2, sum: "{{ '0' * 64 }}"}
loop_control:
loop_var: gitea_runner_test_sum
label: "{{ gitea_runner_test_sum.version }}"
# Mode 0644 on purpose: configure must tighten it to 0600.
- name: Create the work directory with a stand-in registration
ansible.builtin.file:
path: /var/lib/gitea-runner
state: directory
mode: "0750"
- name: Write the stand-in registration
ansible.builtin.copy:
dest: /var/lib/gitea-runner/.runner
mode: "0644"
content: '{"molecule": "not a registration"}'
@@ -0,0 +1,28 @@
---
# One refused input: runs the main entry point with that input and asserts that the expected
# assert, not something else, stopped it. Input: gitea_runner_test_refused (name, vars, expect).
# Task vars cannot come from a template as a whole, so each input under test is passed with
# its usual value as the default.
- name: "Run the role, case {{ gitea_runner_test_refused.name }}"
block:
- name: "Include the role, case {{ gitea_runner_test_refused.name }}"
ansible.builtin.include_role:
name: mortis.kamino.gitea_runner
vars:
gitea_runner_version: "{{ gitea_runner_test_refused.vars.gitea_runner_version | default('6.0.1') }}"
gitea_runner_registration_scope: "{{ gitea_runner_test_refused.vars.gitea_runner_registration_scope | default('') }}"
gitea_runner_docker_prune_schedule: "{{ gitea_runner_test_refused.vars.gitea_runner_docker_prune_schedule | default('Sun *-*-* 04:30:00') }}"
gitea_runner_docker_prune_image_age: "{{ gitea_runner_test_refused.vars.gitea_runner_docker_prune_image_age | default('168h') }}"
gitea_runner_molecule_enabled: "{{ gitea_runner_test_refused.vars.gitea_runner_molecule_enabled | default(false) }}"
# Only reached when the include returned. The message must not contain the expected
# text, so the rescue below cannot mistake it for the assert.
- name: "Fail because the include returned, case {{ gitea_runner_test_refused.name }}"
ansible.builtin.fail:
msg: The role accepted the input
rescue:
- name: "The expected assert fired, case {{ gitea_runner_test_refused.name }}"
ansible.builtin.assert:
that: gitea_runner_test_refused.expect in ansible_failed_result.msg | default('')
fail_msg: "Expected '{{ gitea_runner_test_refused.expect }}', got: {{ ansible_failed_result.msg | default('') }}"
quiet: true
@@ -0,0 +1,401 @@
---
- name: Verify the converged runner
hosts: all
gather_facts: false
tasks:
- name: Read config.yaml
ansible.builtin.slurp:
src: /var/lib/gitea-runner/config.yaml
register: gitea_runner_test_config_raw
- name: Parse config.yaml
ansible.builtin.set_fact:
gitea_runner_test_config: "{{ gitea_runner_test_config_raw.content | b64decode | from_yaml }}"
# Only keys gitea-runner reads: an executor, engine, image, workdir or auto_remove key
# would be ignored by the runner and give a false picture.
- name: Config.yaml holds the inputs and nothing else
ansible.builtin.assert:
that:
- gitea_runner_test_config.keys() | sort == ['container', 'log', 'runner']
- "gitea_runner_test_config.log == {'level': 'debug'}"
- gitea_runner_test_config.runner.keys() | sort == ['capacity', 'labels']
- gitea_runner_test_config.runner.capacity == 2
- gitea_runner_test_config.runner.labels == ['molecule-docker:docker://ubuntu:24.04', 'molecule-shell:host']
- gitea_runner_test_config.container.keys() | sort == ['docker_host', 'privileged', 'volumes']
- gitea_runner_test_config.container.privileged is false
- gitea_runner_test_config.container.docker_host == '-'
- gitea_runner_test_config.container.volumes == ['/cache:/cache']
quiet: true
- name: Stat the registration file, the staged binary and the backup
ansible.builtin.stat:
path: "{{ gitea_runner_test_path }}"
loop:
- /var/lib/gitea-runner/.runner
- /usr/local/bin/gitea-runner.new
- /usr/local/bin/gitea-runner.bak
loop_control:
loop_var: gitea_runner_test_path
register: gitea_runner_test_files
- name: The registration is private to the runner user, and the update left nothing behind
ansible.builtin.assert:
that:
- gitea_runner_test_files.results[0].stat.mode == '0600'
- gitea_runner_test_files.results[0].stat.pw_name == 'gitea-runner'
- not gitea_runner_test_files.results[1].stat.exists
- not gitea_runner_test_files.results[2].stat.exists
quiet: true
- name: Ask the installed binary for its version
ansible.builtin.command:
argv: [/usr/local/bin/gitea-runner, --version]
register: gitea_runner_test_version
changed_when: false
- name: Ask systemd about the runner
ansible.builtin.systemd:
name: gitea-runner
register: gitea_runner_test_unit
# /proc/<pid> belongs to the user the process runs as.
- name: Read the owner of the runner's main process
ansible.builtin.stat:
path: "/proc/{{ gitea_runner_test_unit.status.MainPID }}"
register: gitea_runner_test_owner
- name: The update swapped in 6.0.1 and the runner runs it as its own user
ansible.builtin.assert:
that:
- "'v6.0.1' in gitea_runner_test_version.stdout"
- gitea_runner_test_unit.status.ActiveState == 'active'
- gitea_runner_test_unit.status.UnitFileState == 'enabled'
- gitea_runner_test_unit.status.ExecStart is search('/usr/local/bin/gitea-runner daemon --config /var/lib/gitea-runner/config.yaml')
- gitea_runner_test_owner.stat.pw_name == 'gitea-runner'
quiet: true
- name: Ask systemd about the prune timer
ansible.builtin.systemd:
name: gitea-runner-docker-prune.timer
register: gitea_runner_test_timer
- name: Read the prune service
ansible.builtin.slurp:
src: /etc/systemd/system/gitea-runner-docker-prune.service
register: gitea_runner_test_prune_service
- name: The prune timer is armed and the service carries the gate and the ages
vars:
gitea_runner_test_prune_text: "{{ gitea_runner_test_prune_service.content | b64decode }}"
ansible.builtin.assert:
that:
- gitea_runner_test_timer.status.ActiveState == 'active'
- gitea_runner_test_timer.status.UnitFileState == 'enabled'
- "'ExecCondition=/usr/local/sbin/gitea-runner-docker-prune-gate 3600' in gitea_runner_test_prune_text"
- "'container prune --force --filter until=24h' in gitea_runner_test_prune_text"
- "'image prune --all --force --filter until=168h' in gitea_runner_test_prune_text"
quiet: true
# The prune gate script against a stub docker CLI: no container, a young one (a job may be
# running), an old one (a leaked job container), and a failing docker ps. The stub answers
# `ps -q` from a file and `inspect` with a start time it computes from the container id.
- name: Verify the prune gate script
hosts: all
gather_facts: false
tasks:
- name: Stat the docker CLI
ansible.builtin.stat:
path: /usr/bin/docker
register: gitea_runner_test_docker_cli
- name: The image has no docker CLI the stub would replace
ansible.builtin.assert:
that: not gitea_runner_test_docker_cli.stat.exists
fail_msg: /usr/bin/docker exists in the test image; this play would overwrite it.
quiet: true
- name: Write the stub docker CLI
ansible.builtin.copy:
dest: /usr/bin/docker
mode: "0755"
content: |
#!/bin/sh
case "$1" in
ps) [ -e /tmp/molecule-docker-fail ] && exit 1; cat /tmp/molecule-docker-ids ;;
inspect)
case "$4" in
young) date -u +%Y-%m-%dT%H:%M:%SZ ;;
old) date -u -d '2 hours ago' +%Y-%m-%dT%H:%M:%SZ ;;
*) exit 1 ;;
esac ;;
*) exit 1 ;;
esac
- name: Run each gate case
ansible.builtin.shell:
cmd: |
rm -f /tmp/molecule-docker-fail
printf '%s' '{{ gitea_runner_test_case.ids }}' > /tmp/molecule-docker-ids
{{ 'touch /tmp/molecule-docker-fail' if gitea_runner_test_case.fail else ':' }}
/usr/local/sbin/gitea-runner-docker-prune-gate 3600
loop:
- {name: none, ids: "", fail: false, rc: 0, out: ""}
- {name: young, ids: "young", fail: false, rc: 1, out: "skipping the prune"}
- {name: old, ids: "old", fail: false, rc: 0, out: "ignoring container old"}
- {name: ps-fails, ids: "", fail: true, rc: 1, out: "docker ps failed"}
loop_control:
loop_var: gitea_runner_test_case
label: "{{ gitea_runner_test_case.name }}"
register: gitea_runner_test_gate
# The rc is the result under test; the next task asserts it.
failed_when: false
changed_when: false
- name: The gate let the prune run only when no young container ran
ansible.builtin.assert:
that:
- item.rc == item.gitea_runner_test_case.rc
- item.gitea_runner_test_case.out in item.stdout
fail_msg: "case {{ item.gitea_runner_test_case.name }}: rc {{ item.rc }}, output {{ item.stdout }}"
quiet: true
loop: "{{ gitea_runner_test_gate.results }}"
loop_control:
label: "{{ item.gitea_runner_test_case.name }}"
- name: Remove the stub docker CLI and its files
ansible.builtin.file:
path: "{{ gitea_runner_test_path }}"
state: absent
loop: [/usr/bin/docker, /tmp/molecule-docker-ids, /tmp/molecule-docker-fail]
loop_control:
loop_var: gitea_runner_test_path
# 6.0.2 has a wrong checksum file (prepare.yml): the download must fail before anything is
# stopped, so the runner keeps running 6.0.1.
- name: Verify a failed download leaves the runner running
hosts: all
gather_facts: false
tasks:
- name: Update to a release whose checksum does not match
block:
- name: Include the role with gitea_runner_version 6.0.2
ansible.builtin.include_role:
name: mortis.kamino.gitea_runner
vars:
gitea_runner_version: 6.0.2
- name: Fail because the include returned
ansible.builtin.fail:
msg: The role accepted a binary with a wrong checksum
rescue:
- name: The staging failed, and nothing else failed first
ansible.builtin.assert:
that:
- "'Staging gitea-runner 6.0.2 failed' in ansible_failed_result.msg"
- "'still runs 6.0.1' in ansible_failed_result.msg"
quiet: true
- name: Ask the installed binary for its version after the failed update
ansible.builtin.command:
argv: [/usr/local/bin/gitea-runner, --version]
register: gitea_runner_test_version
changed_when: false
- name: Ask systemd about the runner after the failed update
ansible.builtin.systemd:
name: gitea-runner
register: gitea_runner_test_unit
- name: Stat the staged binary after the failed update
ansible.builtin.stat:
path: /usr/local/bin/gitea-runner.new
register: gitea_runner_test_staged
- name: The runner still runs 6.0.1 and no staged file is left
ansible.builtin.assert:
that:
- "'v6.0.1' in gitea_runner_test_version.stdout"
- gitea_runner_test_unit.status.ActiveState == 'active'
- not gitea_runner_test_staged.stat.exists
quiet: true
# Each input assert, through the main entry point. Every one runs in validate.yml, before any
# change.
- name: Verify the input asserts
hosts: all
gather_facts: false
tasks:
- name: Run each refused input
ansible.builtin.include_tasks: tasks/refused_input.yml
loop:
- name: version with a leading v
vars: {gitea_runner_version: v6.0.1}
expect: plain release number
- name: scope with two slashes
vars: {gitea_runner_registration_scope: owner/repo/extra}
expect: gitea_runner_registration_scope must be empty
- name: prune schedule with a newline
vars: {gitea_runner_docker_prune_schedule: "daily\nExecStartPre=/bin/false"}
expect: plain OnCalendar value
- name: prune age without a unit
vars: {gitea_runner_docker_prune_image_age: "168"}
expect: plain OnCalendar value
- name: molecule tooling without a requirements file
vars: {gitea_runner_molecule_enabled: true}
expect: gitea_runner_collections_requirements_file must name
loop_control:
loop_var: gitea_runner_test_refused
label: "{{ gitea_runner_test_refused.name }}"
# The CI guard and the mint-before-drop order of a forced re-registration, through a child
# ansible-playbook against this instance (see force_register.yml). Neither case may touch the
# registration or stop the runner.
- name: Verify the forced re-registration guards
hosts: all
gather_facts: false
vars:
gitea_runner_test_inventory: "{{ lookup('ansible.builtin.env', 'MOLECULE_INVENTORY_FILE') }}"
gitea_runner_test_env_blank: {GITHUB_ACTIONS: "", GITEA_ACTIONS: "", CI: "", ANSIBLE_NOCOLOR: "1"}
tasks:
- name: Require the molecule inventory
ansible.builtin.assert:
that: gitea_runner_test_inventory | length > 0
fail_msg: MOLECULE_INVENTORY_FILE is not set, so the child play cannot reach this instance.
quiet: true
- name: Force a re-registration under each CI variable, as a child process with only that one set
delegate_to: localhost
ansible.builtin.command:
argv:
- ansible-playbook
- -i
- "{{ gitea_runner_test_inventory }}"
- --limit
- "{{ inventory_hostname }}"
- "{{ playbook_dir }}/force_register.yml"
environment: "{{ gitea_runner_test_env_blank | combine({item: 'true'}) }}"
loop:
- GITHUB_ACTIONS
- GITEA_ACTIONS
- CI
register: gitea_runner_test_ci
# The child is expected to fail (the CI guard fires). Its rc and output are asserted in the next task.
failed_when: false
changed_when: false
# Ansible 2.19 prints task failures to stderr, so both streams are checked.
- name: The CI guard fired for every variable
ansible.builtin.assert:
that:
- item.rc != 0
- "'refuses to run under CI' in (item.stdout ~ item.stderr)"
- "'Registration needs' not in (item.stdout ~ item.stderr)"
quiet: true
loop: "{{ gitea_runner_test_ci.results }}"
loop_control:
label: "{{ item.item }}"
- name: Force a re-registration outside CI with no token host, as a child process
delegate_to: localhost
ansible.builtin.command:
argv:
- ansible-playbook
- -i
- "{{ gitea_runner_test_inventory }}"
- --limit
- "{{ inventory_hostname }}"
- "{{ playbook_dir }}/force_register.yml"
environment: "{{ gitea_runner_test_env_blank }}"
register: gitea_runner_test_mint
# The child is expected to fail (the mint assert fires). Its rc and output are asserted below.
failed_when: false
changed_when: false
- name: The mint assert stopped it
ansible.builtin.assert:
that:
- gitea_runner_test_mint.rc != 0
- "'Registration needs gitea_runner_token_host' in (gitea_runner_test_mint.stdout ~ gitea_runner_test_mint.stderr)"
- "'refuses to run under CI' not in (gitea_runner_test_mint.stdout ~ gitea_runner_test_mint.stderr)"
quiet: true
- name: Read the registration after the forced runs
ansible.builtin.slurp:
src: /var/lib/gitea-runner/.runner
register: gitea_runner_test_registration
- name: Find registration backups
ansible.builtin.find:
paths: /var/lib/gitea-runner
patterns: ".runner.bak.*"
hidden: true
register: gitea_runner_test_backups
- name: Ask systemd about the runner after the forced runs
ansible.builtin.systemd:
name: gitea-runner
register: gitea_runner_test_unit
- name: The registration is untouched and the runner still runs
ansible.builtin.assert:
that:
- (gitea_runner_test_registration.content | b64decode | from_json) == gitea_runner_test_stand_in
quiet: true
vars:
gitea_runner_test_stand_in: {molecule: not a registration}
- name: No backup was taken and the runner still runs
ansible.builtin.assert:
that:
- gitea_runner_test_backups.files | length == 0
- gitea_runner_test_unit.status.ActiveState == 'active'
quiet: true
# The remove path. Last on purpose: it runs once, outside the idempotence step, and nothing runs
# after verify except molecule's own cleanup and destroy of the container. The download URL still
# points at a valid 6.0.1 release, so a role that went on to install after the removal would put
# the binary back; its absence shows the role ended after the removal.
- name: Verify the remove path
hosts: all
gather_facts: false
tasks:
- name: Run the role with the remove flags
ansible.builtin.include_role:
name: mortis.kamino.gitea_runner
vars:
gitea_runner_remove: true
gitea_runner_remove_data: true
- name: Stat what the removal deletes
ansible.builtin.stat:
path: "{{ gitea_runner_test_path }}"
loop:
- /etc/systemd/system/gitea-runner.service
- /usr/local/bin/gitea-runner
- /var/lib/gitea-runner
- /etc/systemd/system/gitea-runner-docker-prune.service
- /etc/systemd/system/gitea-runner-docker-prune.timer
- /usr/local/sbin/gitea-runner-docker-prune-gate
- /etc/systemd/system/multi-user.target.wants/gitea-runner.service
loop_control:
loop_var: gitea_runner_test_path
register: gitea_runner_test_removed
- name: Ask systemd whether the runner and the timer are still active
ansible.builtin.systemd:
name: "{{ gitea_runner_test_unit_name }}"
loop: [gitea-runner, gitea-runner-docker-prune.timer]
loop_control:
loop_var: gitea_runner_test_unit_name
register: gitea_runner_test_after
# The module errors for a unit that no longer exists, which is also a pass.
failed_when: false
- name: Everything is gone, nothing was installed again, and nothing runs
ansible.builtin.assert:
that:
- gitea_runner_test_removed.results | map(attribute='stat') | map(attribute='exists') | select | list | length == 0
- >-
gitea_runner_test_after.results | map(attribute='status', default={})
| map(attribute='ActiveState', default='inactive') | select('equalto', 'active') | list | length == 0
quiet: true
+92
View File
@@ -0,0 +1,92 @@
---
- name: Deploy runner config
become: true
ansible.builtin.template:
src: config.yaml.j2
dest: "{{ gitea_runner_work_dir }}/config.yaml"
owner: "{{ gitea_runner_user }}"
group: "{{ gitea_runner_group }}"
mode: "0644"
notify: Restart Gitea Runner
tags: [gitea_runner, configure]
- name: Ensure runner workdir ownership
become: true
ansible.builtin.file:
path: "{{ gitea_runner_work_dir }}"
owner: "{{ gitea_runner_user }}"
group: "{{ gitea_runner_group }}"
recurse: true
tags: [gitea_runner, configure]
- name: Check current runner registration file state
# become: the work dir is 0750 gitea_runner_user, unreadable when ansible_user is another
# account.
become: true
ansible.builtin.stat:
path: "{{ gitea_runner_work_dir }}/.runner"
register: gitea_runner_file_state
tags: [gitea_runner, configure]
- name: Restrict runner registration file permissions
become: true
ansible.builtin.file:
path: "{{ gitea_runner_work_dir }}/.runner"
mode: "0600"
when: gitea_runner_file_state.stat.exists
tags: [gitea_runner, configure]
- name: Create systemd service
become: true
ansible.builtin.copy:
dest: "{{ gitea_runner_service_unit }}"
owner: root
group: root
mode: "0644"
content: |
[Unit]
Description=Gitea Actions Runner
After=network.target docker.service
Requires=docker.service
[Service]
User={{ gitea_runner_user }}
Group={{ gitea_runner_group }}
WorkingDirectory={{ gitea_runner_work_dir }}
ExecStart={{ gitea_runner_install_dir }}/gitea-runner daemon \
--config {{ gitea_runner_work_dir }}/config.yaml
Restart=always
RestartSec=5
TimeoutStopSec=300
KillSignal=SIGTERM
[Install]
WantedBy=multi-user.target
tags: [gitea_runner, configure]
- name: Reload systemd
become: true
ansible.builtin.systemd:
daemon_reload: true
tags: [gitea_runner, configure]
- name: Ensure runner is enabled and running
become: true
ansible.builtin.systemd:
name: gitea-runner
enabled: true
state: started
tags: [gitea_runner, configure]
- name: Check runner service status
become: true
ansible.builtin.systemd:
name: gitea-runner
register: gitea_runner_service_status
tags: [gitea_runner, configure, health]
- name: Fail if runner service is not running
ansible.builtin.fail:
msg: "Gitea runner service is not running"
when: gitea_runner_service_status.status.ActiveState != "active"
tags: [gitea_runner, configure, health]
+44
View File
@@ -0,0 +1,44 @@
---
- name: Install Docker dependencies
become: true
ansible.builtin.apt:
name:
- ca-certificates
- curl
- gnupg
- lsb-release
state: present
update_cache: true
tags: [gitea_runner, docker, install]
- name: Install Docker
become: true
ansible.builtin.apt:
name:
- docker.io
state: present
tags: [gitea_runner, docker, install]
- name: Enable and start Docker
become: true
ansible.builtin.systemd:
name: docker
enabled: true
state: started
tags: [gitea_runner, docker, install]
- name: Add the runner user to the docker group
become: true
ansible.builtin.user:
name: "{{ gitea_runner_user }}"
groups: docker
append: true
tags: [gitea_runner, docker, install]
# Pulls ubuntu:24.04 from Docker Hub. Also proves Docker runs inside a container host
# (an LXC needs nesting enabled).
- name: Verify Docker can run a container
become: true
ansible.builtin.command: docker run --rm ubuntu:24.04 echo ok
changed_when: false
tags: [gitea_runner, docker, install, health]
+16
View File
@@ -0,0 +1,16 @@
---
# The one download of the runner binary, shared by install.yml (straight onto the live path,
# since nothing runs yet) and update.yml (into a staging path next to it, before
# mortis.kamino._binary_update stops the daemon and swaps it in). get_url checks the published
# sha256 before it moves the file to gitea_runner_download_dest, so a failed or tampered
# download leaves that path as it was.
# Tagged install and update: an include does not pass its tags on to the tasks it includes,
# so under --tags update a task tagged install only would be skipped.
- name: Download and verify the Gitea Runner binary
become: true
ansible.builtin.get_url:
url: "{{ gitea_runner_download_url }}"
dest: "{{ gitea_runner_download_dest }}"
checksum: "sha256:{{ gitea_runner_checksum_url }}"
mode: "0755"
tags: [gitea_runner, install, update]
+16
View File
@@ -0,0 +1,16 @@
---
- name: Ensure runner work directory exists
become: true
ansible.builtin.file:
path: "{{ gitea_runner_work_dir }}"
state: directory
owner: "{{ gitea_runner_user }}"
group: "{{ gitea_runner_group }}"
mode: "0750"
tags: [gitea_runner, install]
- name: Download Gitea Runner binary
ansible.builtin.include_tasks: download.yml
vars:
gitea_runner_download_dest: "{{ gitea_runner_install_dir }}/gitea-runner"
tags: [gitea_runner, install]
+139
View File
@@ -0,0 +1,139 @@
---
- name: Validate the role inputs
ansible.builtin.import_tasks: validate.yml
tags: [gitea_runner, always]
# Re-registering mints a live token and drops the current registration, so it is an
# operator action: refused under CI.
- name: Refuse forced re-registration under CI
ansible.builtin.assert:
that:
- lookup('ansible.builtin.env', 'GITHUB_ACTIONS') | length == 0
- lookup('ansible.builtin.env', 'GITEA_ACTIONS') | length == 0
- lookup('ansible.builtin.env', 'CI') | length == 0
fail_msg: >-
gitea_runner_force_register refuses to run under CI (GITHUB_ACTIONS, GITEA_ACTIONS or CI is set):
run the play by hand from an operator's shell.
quiet: true
when: gitea_runner_force_register | bool
tags: [gitea_runner, register]
# Mint before anything below backs up, stops or removes the registration, so an unknown
# owner or an unreachable token host leaves the current runner running.
- name: Mint runner token before forced re-registration
ansible.builtin.include_tasks: mint_token.yml
when: gitea_runner_force_register | bool
tags: [gitea_runner, register]
# The removal ends the role: none of the tasks below runs, so a removed runner is not
# installed and registered again in the same run.
- name: Remove Gitea runner (explicit only)
ansible.builtin.include_tasks: remove.yml
when: gitea_runner_remove | bool
tags: [gitea_runner, remove]
- name: Install, register, configure and update the runner
when: not (gitea_runner_remove | bool)
block:
- name: Include prerequisites
ansible.builtin.include_tasks: prereqs.yml
tags: [gitea_runner, prereqs, always]
- name: Find previous runner registration backups
# become: the work dir is 0750 gitea_runner_user, unreadable when ansible_user is another
# account.
become: true
ansible.builtin.find:
paths: "{{ gitea_runner_work_dir }}"
patterns: ".runner.bak.*"
hidden: true
register: gitea_runner_old_backups
when:
- gitea_runner_force_register | bool
- gitea_runner_state.stat.exists
tags: [gitea_runner, register]
- name: Remove previous runner registration backups
become: true
ansible.builtin.file:
path: "{{ gitea_runner_old_backup.path }}"
state: absent
loop: "{{ gitea_runner_old_backups.files | default([]) }}"
loop_control:
loop_var: gitea_runner_old_backup
label: "{{ gitea_runner_old_backup.path }}"
when:
- gitea_runner_force_register | bool
- gitea_runner_state.stat.exists
tags: [gitea_runner, register]
- name: Back up runner registration before forced removal
become: true
ansible.builtin.copy:
src: "{{ gitea_runner_work_dir }}/.runner"
dest: "{{ gitea_runner_work_dir }}/.runner.bak.{{ ansible_date_time.iso8601_basic_short }}"
remote_src: true
owner: "{{ gitea_runner_state.stat.pw_name }}"
group: "{{ gitea_runner_state.stat.gr_name }}"
mode: "0600"
when:
- gitea_runner_force_register | bool
- gitea_runner_state.stat.exists
tags: [gitea_runner, register]
- name: Stop Gitea Runner service before forced re-register
become: true
ansible.builtin.systemd:
name: gitea-runner
state: stopped
when:
- gitea_runner_force_register | bool
- gitea_runner_state.stat.exists
tags: [gitea_runner, register]
- name: Remove stale runner registration (force re-register)
become: true
ansible.builtin.file:
path: "{{ gitea_runner_work_dir }}/.runner"
state: absent
when: gitea_runner_force_register | bool
tags: [gitea_runner, register]
- name: Refresh registration fact after forced removal
ansible.builtin.set_fact:
gitea_runner_registered: false
when: gitea_runner_force_register | bool
tags: [gitea_runner, register]
- name: Install Docker
ansible.builtin.include_tasks: docker.yml
when: not gitea_runner_installed
tags: [gitea_runner, docker, install, health]
- name: Install Gitea runner (first install only)
ansible.builtin.include_tasks: install.yml
when: not gitea_runner_installed
tags: [gitea_runner, install]
- name: Register runner
ansible.builtin.include_tasks: register.yml
when: not gitea_runner_registered
tags: [gitea_runner, register]
- name: Configure runner
ansible.builtin.include_tasks: configure.yml
tags: [gitea_runner, configure, health]
- name: Schedule the Docker prune
ansible.builtin.include_tasks: prune.yml
tags: [gitea_runner, prune]
- name: Update runner binary
ansible.builtin.include_tasks: update.yml
when: gitea_runner_update | bool
tags: [gitea_runner, update]
- name: Install the molecule test tooling
ansible.builtin.include_tasks: molecule.yml
when: gitea_runner_molecule_enabled | bool
tags: [gitea_runner, molecule]
+46
View File
@@ -0,0 +1,46 @@
---
# The registration inputs have empty role defaults; refuse to register without them.
- name: Require registration inputs
ansible.builtin.assert:
that:
- gitea_runner_token_host | length > 0
- gitea_runner_token_host in groups['all']
- gitea_runner_instance_url | length > 0
- gitea_runner_name | length > 0
fail_msg: >-
Registration needs gitea_runner_token_host (inventory host with Gitea that mints the token;
it must be a host in the inventory), gitea_runner_instance_url and gitea_runner_name.
Set them in group_vars or host_vars.
tags: [gitea_runner, register]
# Nothing here may run under --check: the token is a live credential minted on the
# Gitea server. register.yml reports the intended registration instead.
- name: Mint the token on the token host
when: not ansible_check_mode
block:
# argv: no value passes through a command string.
- name: Generate runner token
delegate_to: "{{ gitea_runner_token_host }}"
become: true
no_log: true
ansible.builtin.command:
argv: >-
{{ ['sudo', '-u', gitea_runner_gitea_user, gitea_runner_gitea_install_dir ~ '/gitea',
'--config', gitea_runner_gitea_app_dir ~ '/app.ini', 'actions', 'generate-runner-token']
+ (['--scope', gitea_runner_registration_scope] if gitea_runner_registration_scope | length > 0 else []) }}
register: gitea_runner_token_cmd
failed_when: gitea_runner_token_cmd.rc != 0 or gitea_runner_token_cmd.stdout is not search('\S+')
changed_when: false
tags: [gitea_runner, register]
- name: Set runner token
no_log: true
ansible.builtin.set_fact:
gitea_runner_token: "{{ gitea_runner_token_cmd.stdout | regex_search('([a-zA-Z0-9]+)', '\\1') | first }}"
tags: [gitea_runner, register]
- name: Fail if runner token extraction failed
ansible.builtin.fail:
msg: "Failed to extract Gitea runner token"
when: gitea_runner_token is not defined or gitea_runner_token | length == 0
tags: [gitea_runner, register]
+86
View File
@@ -0,0 +1,86 @@
---
# Everything the molecule job needs is installed here, at provision time, so a CI
# run only executes tests: pinned tooling in a venv and the collections the roles use.
# The role builds no test image: the scenarios are expected to pull theirs from a registry.
# gitea_runner_collections_requirements_file is asserted non-empty in validate.yml.
- name: Install molecule venv prerequisites
become: true
ansible.builtin.apt:
name:
- python3-venv
- python3-pip
- git
# community.docker.docker_image runs on this host via the Docker SDK.
- python3-requests
- python3-docker
state: present
cache_valid_time: 3600
tags: [gitea_runner, molecule]
- name: Install pinned molecule tooling into its venv
become: true
ansible.builtin.pip:
name:
- "molecule=={{ gitea_runner_molecule_version }}"
- "molecule-plugins[docker]=={{ gitea_runner_molecule_plugins_version }}"
- "ansible-core=={{ gitea_runner_molecule_ansible_core_version }}"
- "docker=={{ gitea_runner_molecule_docker_sdk_version }}"
virtualenv: "{{ gitea_runner_molecule_venv }}"
virtualenv_command: python3 -m venv
tags: [gitea_runner, molecule]
# The collections come from gitea_runner_collections_requirements_file and are
# reinstalled when it changes. requirements.sha256 in the collections path records the
# checksum of the file the installed set came from; it is written only after a
# successful install, so a failed install is retried on the next run (a guard on the
# copied file changing would skip it forever). --force: without it ansible-galaxy skips
# a collection it finds on any other collections path of this host and installs
# nothing into -p, leaving the molecule job without the modules it needs.
- name: Copy the pinned collections file to the runner host
become: true
ansible.builtin.copy:
src: "{{ gitea_runner_collections_requirements_file }}"
dest: "{{ gitea_runner_home }}/molecule-requirements.yml"
owner: root
group: root
mode: "0644"
tags: [gitea_runner, molecule]
- name: Read the requirements checksum of the installed collections
become: true
ansible.builtin.slurp:
src: "{{ gitea_runner_molecule_collections_path }}/requirements.sha256"
register: gitea_runner_molecule_collections_stamp
failed_when: false
tags: [gitea_runner, molecule]
- name: Install the collections the tested roles use
when: gitea_runner_molecule_collections_stamp.content | default('') | b64decode | trim != gitea_runner_molecule_requirements_sha256
vars:
gitea_runner_molecule_requirements_sha256: "{{ lookup('ansible.builtin.file', gitea_runner_collections_requirements_file) | hash('sha256') }}"
tags: [gitea_runner, molecule]
block:
- name: Install the collections of the requirements file
become: true
ansible.builtin.command:
argv:
- "{{ gitea_runner_molecule_venv }}/bin/ansible-galaxy"
- collection
- install
- --force
- -r
- "{{ gitea_runner_home }}/molecule-requirements.yml"
- -p
- "{{ gitea_runner_molecule_collections_path }}"
changed_when: true
tags: [gitea_runner, molecule]
- name: Record the checksum of the installed collections
become: true
ansible.builtin.copy:
content: "{{ gitea_runner_molecule_requirements_sha256 }}\n"
dest: "{{ gitea_runner_molecule_collections_path }}/requirements.sha256"
owner: root
group: root
mode: "0644"
tags: [gitea_runner, molecule]
+40
View File
@@ -0,0 +1,40 @@
---
# The user module does not create a named primary group; on a fresh host it would fail with
# "Group <gitea_runner_group> does not exist".
- name: Ensure runner group exists
become: true
ansible.builtin.group:
name: "{{ gitea_runner_group }}"
system: true
tags: [gitea_runner, prereqs, always]
- name: Ensure runner user exists
become: true
ansible.builtin.user:
name: "{{ gitea_runner_user }}"
group: "{{ gitea_runner_group }}"
home: "{{ gitea_runner_home }}"
create_home: true
system: true
tags: [gitea_runner, prereqs, always]
- name: Check if runner is installed
ansible.builtin.stat:
path: "{{ gitea_runner_install_dir }}/gitea-runner"
register: gitea_runner_bin
tags: [gitea_runner, prereqs, always]
- name: Check if runner is registered
# become: the work dir is 0750 gitea_runner_user, unreadable when ansible_user is another
# account.
become: true
ansible.builtin.stat:
path: "{{ gitea_runner_work_dir }}/.runner"
register: gitea_runner_state
tags: [gitea_runner, prereqs, always]
- name: Set runner facts
ansible.builtin.set_fact:
gitea_runner_installed: "{{ gitea_runner_bin.stat.exists }}"
gitea_runner_registered: "{{ gitea_runner_state.stat.exists }}"
tags: [gitea_runner, prereqs, always]
+114
View File
@@ -0,0 +1,114 @@
---
# Weekly Docker cleanup. Every pinned image version stays on disk after a bump, so without
# this the disk of a busy runner fills and every job fails at container setup.
# The settings are validated in validate.yml.
# ExecCondition runs the gate script below: it skips the run (not a failure) while a container
# younger than gitea_runner_docker_prune_job_max_age runs, so a prune never removes an image
# or container a job needs. An older container is a leaked job container (a job cannot run
# past its timeout): it is logged and ignored, or one leak would block the prune for good.
# The window between that check and the prune is a few seconds; a job started inside it can
# fail once and is re-run. A skipped run is not retried before the next timer elapse: on a busy
# week set a shorter gitea_runner_docker_prune_schedule (e.g. daily).
# The ExecStart= lines start with '-' so a failing step does not skip the later ones.
# Named volumes are never pruned (docker volume prune without -a removes anonymous ones only).
- name: Install Docker prune gate script
become: true
ansible.builtin.copy:
dest: /usr/local/sbin/gitea-runner-docker-prune-gate
owner: root
group: root
mode: "0755"
# raw: the Go template braces are not Jinja. The tag shares the shebang line: Jinja keeps the
# newline after {% raw %}, and a file that does not start with "#!" cannot be exec'd by systemd.
content: |
{% raw %}#!/bin/sh
# Exit 0 when no container younger than $1 seconds runs (prune may proceed), 1 to skip.
# Every failure skips: the prune must not run when the state is unknown.
max_age="$1"
case "$max_age" in
'' | *[!0-9]*) echo "invalid max age '$max_age'"; exit 1 ;;
esac
now=$(date +%s)
ids=$(/usr/bin/docker ps -q) || { echo "docker ps failed"; exit 1; }
for id in $ids; do
started=$(/usr/bin/docker inspect --format '{{.State.StartedAt}}' "$id") || { echo "cannot inspect $id"; exit 1; }
started=$(date -d "$started" +%s) || { echo "cannot parse start time of $id"; exit 1; }
age=$((now - started))
if [ "$age" -lt "$max_age" ]; then
echo "container $id is $age s old: a job may be running, skipping the prune"
exit 1
fi
echo "ignoring container $id, running for $age s (leaked job container)"
done
exit 0
{% endraw %}
when: gitea_runner_docker_prune_enabled | bool
tags: [gitea_runner, prune]
- name: Install Docker prune service
become: true
ansible.builtin.copy:
dest: /etc/systemd/system/gitea-runner-docker-prune.service
owner: root
group: root
mode: "0644"
content: |
[Unit]
Description=Prune unused Docker data on the Gitea runner host
After=docker.service
Requires=docker.service
[Service]
Type=oneshot
ExecCondition=/usr/local/sbin/gitea-runner-docker-prune-gate {{ gitea_runner_docker_prune_job_max_age }}
ExecStart=-/usr/bin/docker container prune --force --filter until={{ gitea_runner_docker_prune_container_age }}
ExecStart=-/usr/bin/docker image prune --all --force --filter until={{ gitea_runner_docker_prune_image_age }}
ExecStart=-/usr/bin/docker builder prune --force --filter until={{ gitea_runner_docker_prune_image_age }}
ExecStart=-/usr/bin/docker volume prune --force
register: gitea_runner_prune_service
when: gitea_runner_docker_prune_enabled | bool
tags: [gitea_runner, prune]
- name: Install Docker prune timer
become: true
ansible.builtin.copy:
dest: /etc/systemd/system/gitea-runner-docker-prune.timer
owner: root
group: root
mode: "0644"
content: |
[Unit]
Description=Scheduled Docker prune on the Gitea runner host
[Timer]
OnCalendar={{ gitea_runner_docker_prune_schedule }}
Persistent=true
RandomizedDelaySec=10m
[Install]
WantedBy=timers.target
register: gitea_runner_prune_timer
when: gitea_runner_docker_prune_enabled | bool
tags: [gitea_runner, prune]
- name: Reload systemd for the prune units
become: true
ansible.builtin.systemd:
daemon_reload: true
when:
- gitea_runner_docker_prune_enabled | bool
- gitea_runner_prune_service is changed or gitea_runner_prune_timer is changed
tags: [gitea_runner, prune]
# Not in check mode: on the first run the unit files above are only simulated, so systemd
# would not find the timer. A changed timer is restarted to re-arm a new schedule.
- name: Enable the Docker prune timer
become: true
ansible.builtin.systemd:
name: gitea-runner-docker-prune.timer
enabled: true
state: "{{ 'restarted' if gitea_runner_prune_timer is changed else 'started' }}"
when:
- gitea_runner_docker_prune_enabled | bool
- not ansible_check_mode
tags: [gitea_runner, prune]
+47
View File
@@ -0,0 +1,47 @@
---
# A forced re-registration minted the token in main.yml before dropping .runner.
- name: Mint runner token
ansible.builtin.include_tasks: mint_token.yml
when: not gitea_runner_force_register | bool
tags: [gitea_runner, register]
# In check mode no token was minted and the register command can't be templated
# without one, so report the intended registration instead.
- name: Report runner registration (check mode)
ansible.builtin.debug:
msg: >-
Check mode: would generate a runner token on {{ gitea_runner_token_host }} and register
{{ gitea_runner_name }} against {{ gitea_runner_instance_url }}
with scope {{ gitea_runner_registration_scope if gitea_runner_registration_scope | length > 0 else '(instance-wide)' }}
changed_when: true
when: ansible_check_mode
tags: [gitea_runner, register]
- name: Register Gitea runner
when: not ansible_check_mode
become: true
tags: [gitea_runner, register]
block:
- name: Attempt runner registration
ansible.builtin.command:
argv:
- "{{ gitea_runner_install_dir }}/gitea-runner"
- register
- --no-interactive
- --instance
- "{{ gitea_runner_instance_url }}"
- --name
- "{{ gitea_runner_name }}"
chdir: "{{ gitea_runner_work_dir }}"
creates: "{{ gitea_runner_work_dir }}/.runner"
environment:
GITEA_RUNNER_REGISTRATION_TOKEN: "{{ gitea_runner_token }}"
register: gitea_runner_register_cmd
no_log: true
notify: Restart Gitea Runner
rescue:
- name: Fail with sanitized runner registration error
ansible.builtin.fail:
msg: >-
Gitea runner registration failed (rc={{ gitea_runner_register_cmd.rc | default('unknown') }}):
{{ gitea_runner_register_cmd.stderr | default('') | regex_replace(gitea_runner_token | regex_escape, '***REDACTED***') }}
+75
View File
@@ -0,0 +1,75 @@
---
# Run with -e gitea_runner_remove=true (and gitea_runner_remove_data=true to delete the
# registration and config too). The role ends after these tasks.
- name: Stop Gitea runner service
become: true
ansible.builtin.systemd:
name: gitea-runner
state: stopped
enabled: false
register: gitea_runner_stop
# The unit may already be gone (systemd: "Could not find the requested service <unit>").
# Any other stop failure must halt here, before the unit file and data are deleted.
failed_when:
- gitea_runner_stop.failed | default(false)
- "'Could not find the requested service' not in (gitea_runner_stop.msg | default(''))"
tags: [gitea_runner, remove]
- name: Stop the Docker prune timer
become: true
ansible.builtin.systemd:
name: gitea-runner-docker-prune.timer
state: stopped
enabled: false
register: gitea_runner_prune_stop
failed_when:
- gitea_runner_prune_stop.failed | default(false)
- "'Could not find the requested service' not in (gitea_runner_prune_stop.msg | default(''))"
tags: [gitea_runner, remove]
- name: Remove the Docker prune units
become: true
ansible.builtin.file:
path: "/etc/systemd/system/{{ gitea_runner_prune_unit }}"
state: absent
loop:
- gitea-runner-docker-prune.timer
- gitea-runner-docker-prune.service
loop_control:
loop_var: gitea_runner_prune_unit
tags: [gitea_runner, remove]
- name: Remove the Docker prune gate script
become: true
ansible.builtin.file:
path: /usr/local/sbin/gitea-runner-docker-prune-gate
state: absent
tags: [gitea_runner, remove]
- name: Remove systemd unit
become: true
ansible.builtin.file:
path: "{{ gitea_runner_service_unit }}"
state: absent
tags: [gitea_runner, remove]
- name: Reload systemd
become: true
ansible.builtin.systemd:
daemon_reload: true
tags: [gitea_runner, remove]
- name: Remove runner binary
become: true
ansible.builtin.file:
path: "{{ gitea_runner_install_dir }}/gitea-runner"
state: absent
tags: [gitea_runner, remove]
- name: Remove runner work directory
become: true
ansible.builtin.file:
path: "{{ gitea_runner_work_dir }}"
state: absent
when: gitea_runner_remove_data | default(false) | bool
tags: [gitea_runner, remove]
+79
View File
@@ -0,0 +1,79 @@
---
- name: Get current runner version
become: true
ansible.builtin.command:
argv: ["{{ gitea_runner_install_dir }}/gitea-runner", --version]
register: gitea_runner_version_cmd
changed_when: false
# Failure is expected when the binary is missing (rc 2): empty stdout falls through to 0.0.0
# below, which triggers the install path.
failed_when: false
# Read-only, so it also runs in the --check preview. Skipped there, stdout would be empty, the version
# would fall back to 0.0.0 and an up-to-date binary would look like it needs an install.
check_mode: false
tags: [gitea_runner, update]
- name: Extract installed version
ansible.builtin.set_fact:
gitea_runner_installed_version: >-
{{
(gitea_runner_version_cmd.stdout
| regex_findall('v?([0-9]+\.[0-9]+\.[0-9]+)')
| first)
| default('0.0.0')
}}
tags: [gitea_runner, update]
- name: Determine if update required
ansible.builtin.set_fact:
gitea_runner_update_required: "{{ gitea_runner_installed_version != gitea_runner_version }}"
# Next to the live binary, so the swap is a rename on one filesystem.
gitea_runner_staged_binary: "{{ gitea_runner_install_dir }}/gitea-runner.new"
tags: [gitea_runner, update]
# Download and verify before anything is stopped: a failed download or checksum leaves the
# running runner untouched. mortis.kamino._binary_update then stops, backs up, swaps, restarts,
# checks the version and rolls back on failure, and removes the staged binary.
- name: Stage and swap in the new runner binary
when: gitea_runner_update_required
block:
# Its own rescue, so that only a staging failure gets this message: a failure in the swap
# below keeps the rollback message of mortis.kamino._binary_update.
- name: Stage the new runner binary
block:
- name: Download and verify into the staging path
ansible.builtin.include_tasks: download.yml
vars:
gitea_runner_download_dest: "{{ gitea_runner_staged_binary }}"
tags: [gitea_runner, update]
rescue:
- name: Fail the staging
ansible.builtin.fail:
msg: >-
Staging gitea-runner {{ gitea_runner_version }} failed ({{ ansible_failed_result.msg | default('see the task above') }}).
The runner was not stopped and still runs {{ gitea_runner_installed_version }}.
tags: [gitea_runner, update]
# An include does not pass its tags on to the included tasks, hence apply.
- name: Swap in the staged runner binary
ansible.builtin.include_role:
name: mortis.kamino._binary_update
apply:
tags: [gitea_runner, update]
vars:
_binary_update_service: gitea-runner
_binary_update_binary_path: "{{ gitea_runner_install_dir }}/gitea-runner"
_binary_update_staged_path: "{{ gitea_runner_staged_binary }}"
_binary_update_version_command: ["{{ gitea_runner_install_dir }}/gitea-runner", --version]
_binary_update_expected_version: "{{ gitea_runner_version }}"
tags: [gitea_runner, update]
always:
# Left behind only when the run failed before the swap; get_url would reuse a matching
# file anyway, but a stale binary next to the live one is clutter.
- name: Remove the staged runner binary
become: true
ansible.builtin.file:
path: "{{ gitea_runner_staged_binary }}"
state: absent
tags: [gitea_runner, update]
+48
View File
@@ -0,0 +1,48 @@
---
# Input checks. Imported first in main.yml with tags: always, so a bad input fails before any
# change, whatever tags the run selects.
- name: Require a plain gitea_runner_version
ansible.builtin.assert:
that:
- gitea_runner_version is string
- gitea_runner_version is match('^[0-9]+\\.[0-9]+\\.[0-9]+$')
fail_msg: >-
gitea_runner_version must be a plain release number such as 6.0.1, with no leading v: it is
used in the download URL and compared with what the binary reports.
quiet: true
# Checks the format only. Together with minting the token first, a malformed scope or a
# failed mint stops the play before a forced re-registration drops .runner.
- name: Require a valid registration scope
ansible.builtin.assert:
that:
- gitea_runner_registration_scope is string
- gitea_runner_registration_scope | length == 0 or gitea_runner_registration_scope is match('^[A-Za-z0-9_.-]+(/[A-Za-z0-9_.-]+)?$')
fail_msg: >-
gitea_runner_registration_scope must be empty (instance-wide), an owner (user or organisation)
or owner/repo, got '{{ gitea_runner_registration_scope }}'.
quiet: true
# The values land in systemd unit files: a newline or % would inject or expand directives.
- name: Validate the Docker prune settings
ansible.builtin.assert:
that:
- gitea_runner_docker_prune_schedule is match('^[A-Za-z0-9 :*,./~-]+$')
- gitea_runner_docker_prune_container_age is match('^[0-9]+[smh]$')
- gitea_runner_docker_prune_image_age is match('^[0-9]+[smh]$')
fail_msg: >-
gitea_runner_docker_prune_schedule must be a plain OnCalendar value (no newline or %),
the two ages a number with s, m or h (e.g. 168h).
quiet: true
when: gitea_runner_docker_prune_enabled | bool
- name: Require the collections requirements file for the molecule tooling
ansible.builtin.assert:
that:
- gitea_runner_collections_requirements_file is string
- gitea_runner_collections_requirements_file | length > 0
fail_msg: >-
gitea_runner_molecule_enabled is true, so gitea_runner_collections_requirements_file must name
the collections requirements file on the control host that the molecule install reads.
quiet: true
when: gitea_runner_molecule_enabled | bool
@@ -0,0 +1,30 @@
log:
level: {{ gitea_runner_log_level | default('info') }}
runner:
# Number of jobs run concurrently
capacity: {{ gitea_runner_capacity }}
# Runner labels exposed to workflows
labels:
{% for label in gitea_runner_labels | default(['docker', 'ubuntu-lxc']) %}
- {{ label }}
{% endfor %}
{% if gitea_runner_molecule_enabled | default(false) | bool %}
- {{ gitea_runner_molecule_label }}:host
{% endif %}
container:
# Run job containers privileged
privileged: {{ gitea_runner_container_privileged | default(false) | lower }}
# Docker daemon the runner uses. "-" still finds the daemon but does not mount
# the socket into job containers. to_json keeps the value a quoted YAML string.
docker_host: {{ gitea_runner_container_docker_host | default('unix:///var/run/docker.sock') | to_json }}
{% if gitea_runner_container_volumes is defined %}
volumes:
{% for volume in gitea_runner_container_volumes %}
- "{{ volume }}"
{% endfor %}
{% endif %}