69 Commits
Author SHA1 Message Date
Defame1297 567c3d2f22 Merge pull request 'ci: refuse CLAUDE.md in any letter case and keep .apm-local out of the build' (#333) from ci/refuse-claude-md-any-case into main
Molecule / molecule (push) Canceled after 0s
Lint / lint (push) Canceled after 0s
Build / build (push) Successful in 14s
Images / image (Dockerfile, ubuntu:24.04@sha256:9c7f200c07e3d4a03e7249d2c16bf66a51120fb876aa2242cf31451412543289, molecule-ubuntu2404, images/molecule-ubuntu2404, 0.1.9) (push) Successful in 9s
Images / image (Dockerfile, ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db, molecule-ubuntu2604, images/molecule-ubuntu2604, 0.1.5) (push) Successful in 34s
Images / image (images/ci/Dockerfile, ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db, ci, , 0.2.38) (push) Successful in 4m36s
Reviewed-on: #333
Reviewed-by: Defame1297 <[email protected]>
2026-11-23 20:33:04 +00:00
Defame1297 5abf42c6c4 Merge branch 'main' into ci/refuse-claude-md-any-case
Build / build (pull_request) Successful in 14s
Molecule / molecule (pull_request) Successful in 14m37s
Lint / lint (pull_request) Successful in 1m46s
2026-11-23 20:15:15 +00:00
Dragonish 40b79ea985 Merge pull request 'feat(fail2ban): reload instead of restart when jail.local changes' (#332) from feat/fail2ban-reload into main
Build / build (push) Successful in 15s
Molecule / molecule (push) Canceled after 0s
Lint / lint (push) Canceled after 47s
Reviewed-on: #332
Reviewed-by: Defame1297 <[email protected]>
2026-11-23 20:15:08 +00:00
Defame1297 f21a535a87 Merge branch 'main' into ci/refuse-claude-md-any-case
Build / build (pull_request) Canceled after 0s
Molecule / molecule (pull_request) Canceled after 0s
Lint / lint (pull_request) Canceled after 1m28s
2026-11-23 20:08:31 +00:00
Defame1297 9d31fd9461 Merge branch 'main' into feat/fail2ban-reload
Build / build (pull_request) Successful in 15s
Molecule / molecule (pull_request) Successful in 3m48s
Lint / lint (pull_request) Successful in 1m20s
2026-11-23 20:08:26 +00:00
Dragonish e0e9fa1b17 feat(fail2ban): reload instead of restart when jail.local changes
Build / build (pull_request) Successful in 16s
Molecule / molecule (pull_request) Canceled after 0s
Lint / lint (pull_request) Canceled after 1m23s
The main entry point notified a restart. A restart stops every jail, which
flushes its bans out of the firewall until they are restored from Fail2Ban's
database when the jail starts again, and forgets failures counted toward
maxretry. A reload applies the new settings to the running jails. service_jail
already reloads.

The Restart Fail2Ban handler is removed: nothing notifies it any more, and a
handler name is not part of the role's interface (#257). A new side_effect.yml
bans an address, records the daemon's PID and rewrites jail.local; verify
asserts the new maxretry is active, the ban is in force and the PID is
unchanged (the PID is what separates a reload from a restart, since bans are
restored from the database).

Assisted-by: Claude Code
2026-11-23 20:01:07 +00:00
Defame1297 97f5328043 Merge pull request 'feat(system_baseline): add a per-host package blacklist for unattended-upgrades' (#325) from feat/322-unattended-blacklist into main
Molecule / molecule (push) Canceled after 0s
Lint / lint (push) Canceled after 0s
Build / build (push) Successful in 17s
Reviewed-on: #325
Reviewed-by: Defame1297 <[email protected]>
2026-11-23 20:00:03 +00:00
Defame1297 cca31f44a1 build(galaxy): keep .apm-local out of the Collection build
Lint / lint (pull_request) Canceled after 0s
Molecule / molecule (pull_request) Canceled after 0s
Build / build (pull_request) Canceled after 3s
.apm-local/ is apm's local state directory and ignores itself through its
own .gitignore, so a local ansible-galaxy collection build copied it into
the archive, where check_tarball.py rejects it as a disallowed top-level
entry.

Assisted-by: Claude Code
2026-11-23 19:58:57 +00:00
Defame1297 4f29901a80 ci(pre-commit): refuse CLAUDE.md in any letter case
The refuse-claude-md pattern was case-sensitive, so claude.md or CLAUDE.MD
passed it, yet a case-insensitive file system serves either as CLAUDE.md.
Match with the inline (?i) flag. The hook config is a ci image input, so
the ci image moves from 0.2.37 to 0.2.38.

Assisted-by: Claude Code
2026-11-23 19:58:50 +00:00
Defame1297 163bb21f40 Merge branch 'main' into feat/322-unattended-blacklist
Build / build (pull_request) Successful in 16s
Lint / lint (pull_request) Successful in 1m13s
Molecule / molecule (pull_request) Successful in 2m12s
2026-11-23 19:55:48 +00:00
Defame1297 ff000857a9 Merge pull request 'ci: refuse CLAUDE.md files by hook and keep every AGENTS.md out of the Collection tarball' (#330) from ci/244-refuse-claude-md into main
Build / build (push) Successful in 15s
Lint / lint (push) Canceled after 0s
Images / image (Dockerfile, ubuntu:24.04@sha256:9c7f200c07e3d4a03e7249d2c16bf66a51120fb876aa2242cf31451412543289, molecule-ubuntu2404, images/molecule-ubuntu2404, 0.1.9) (push) Successful in 15s
Images / image (Dockerfile, ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db, molecule-ubuntu2604, images/molecule-ubuntu2604, 0.1.5) (push) Successful in 28s
Images / image (images/ci/Dockerfile, ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db, ci, , 0.2.37) (push) Successful in 6m1s
Reviewed-on: #330
Reviewed-by: Defame1297 <[email protected]>
2026-11-23 19:55:35 +00:00
Defame1297 5d2f6ffad2 Merge branch 'main' into ci/244-refuse-claude-md
Build / build (pull_request) Successful in 16s
Molecule / molecule (pull_request) Successful in 2s
Lint / lint (pull_request) Successful in 1m23s
2026-11-23 19:53:12 +00:00
Defame1297 943cd96580 Merge pull request 'feat(docker): derive the apt architecture from the host' (#331) from feat/300-docker-apt-arch into main
Build / build (push) Successful in 17s
Molecule / molecule (push) Canceled after 0s
Lint / lint (push) Canceled after 13s
Reviewed-on: #331
2026-11-23 19:52:58 +00:00
Defame1297 161e5bff63 ci(images): bump the ci image past main's 0.2.36
Build / build (pull_request) Successful in 16s
Molecule / molecule (pull_request) Canceled after 0s
Lint / lint (pull_request) Canceled after 13s
main raised ci to 0.2.36 for its own .pre-commit-config.yaml change, so
the hook change here needs 0.2.37.

Refs: #244

Assisted-by: Claude Code
2026-11-23 19:48:12 +00:00
Defame1297 a9aa1f2e0e Merge branch 'main' into feat/300-docker-apt-arch
Build / build (pull_request) Successful in 16s
Molecule / molecule (pull_request) Successful in 3m3s
Lint / lint (pull_request) Successful in 1m18s
2026-11-23 19:47:02 +00:00
kamino-renovate Bot 597590c2f1 Merge pull request 'chore(deps): update git.rkdr.net/mortis/molecule-ubuntu2404 docker tag to v0.1.9' (#327) from renovate/git.rkdr.net-mortis-molecule-ubuntu2404-0.x into main
Build / build (push) Successful in 15s
Molecule / molecule (push) Canceled after 0s
Lint / lint (push) Canceled after 36s
2026-11-23 19:46:36 +00:00
Defame1297 0ee6e76037 Merge branch 'main' into renovate/git.rkdr.net-mortis-molecule-ubuntu2404-0.x
Build / build (pull_request) Successful in 14s
Lint / lint (pull_request) Successful in 1m30s
Molecule / molecule (pull_request) Successful in 14m11s
2026-11-23 19:30:36 +00:00
Dragonish ba96e98585 feat(docker): derive the apt architecture from the host
Build / build (pull_request) Successful in 19s
Molecule / molecule (pull_request) Canceled after 0s
Lint / lint (pull_request) Canceled after 25s
docker_apt_arch defaults to empty, which derives amd64 or arm64 from
the host architecture; another architecture fails the play, and a set
value is always used.

Assisted-by: Claude Code
2026-11-23 19:30:31 +00:00
Defame1297 d8f044740a Merge branch 'main' into ci/244-refuse-claude-md
Build / build (pull_request) Successful in 15s
Lint / lint (pull_request) Failing after 1m3s
Molecule / molecule (pull_request) Successful in 2s
2026-11-23 19:27:59 +00:00
kamino-renovate Bot b50ae9345a Merge pull request 'chore(deps): update git.rkdr.net/mortis/ci docker tag to v0.2.35' (#326) from renovate/git.rkdr.net-mortis-ci-0.x into main
Build / build (push) Successful in 15s
Lint / lint (push) Successful in 1m15s
2026-11-23 19:20:48 +00:00
Defame1297 573e5e49a6 Merge branch 'main' into renovate/git.rkdr.net-mortis-ci-0.x
Gitea release key / check (pull_request) Canceled after 0s
Build / build (pull_request) Successful in 15s
Molecule / molecule (pull_request) Successful in 3s
Lint / lint (pull_request) Successful in 1m17s
2026-11-23 19:18:31 +00:00
Defame1297 ff607879a1 Merge pull request 'chore(deps): update pre-commit hook zizmorcore/zizmor-pre-commit to v1.33.1' (#312) from renovate/zizmorcore-zizmor-pre-commit-1.x into main
Build / build (push) Successful in 20s
Images / image (Dockerfile, ubuntu:24.04@sha256:9c7f200c07e3d4a03e7249d2c16bf66a51120fb876aa2242cf31451412543289, molecule-ubuntu2404, images/molecule-ubuntu2404, 0.1.9) (push) Successful in 10s
Lint / lint (push) Canceled after 22s
Images / image (Dockerfile, ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db, molecule-ubuntu2604, images/molecule-ubuntu2604, 0.1.5) (push) Successful in 10s
Images / image (images/ci/Dockerfile, ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db, ci, , 0.2.36) (push) Successful in 4m53s
Reviewed-on: #312
Reviewed-by: Defame1297 <[email protected]>
2026-11-23 19:18:08 +00:00
Defame1297 35e780cf79 ci(check_tarball): refuse AGENTS.md at any depth
Build / build (pull_request) Successful in 18s
Lint / lint (pull_request) Successful in 1m21s
Molecule / molecule (pull_request) Successful in 1s
An AGENTS.md under roles/ holds contributor rules; shipped in the
Collection, a consumer's agent reading an installed role would load
them. galaxy.yml build_ignore lists the current ones, and the archive
check now refuses any AGENTS.md, compared case-insensitively, as the
allow list behind that deny list. A root AGENTS.md was already refused
by ALLOWED_TOP.

Refs: #244

Assisted-by: Claude Code
2026-11-23 19:16:17 +00:00
Defame1297 b232887153 ci(images): bump the ci image for the hook change
.pre-commit-config.yaml is an input of the ci image, so the new hook
needs a new image version (0.2.35 -> 0.2.36).

Refs: #244

Assisted-by: Claude Code
2026-11-23 19:14:07 +00:00
Defame1297 de16995f35 ci(pre-commit): refuse CLAUDE.md files by hook
Claude Code reads CLAUDE.md in place of AGENTS.md, so a stray CLAUDE.md,
CLAUDE.local.md or .claude/CLAUDE.md at any depth leaves an agent without
this repository's guidance, and nothing reports it. A language: fail hook
refuses such a file at commit time.

Refs: #244

Assisted-by: Claude Code
2026-11-23 19:14:00 +00:00
Defame1297 a46880bc8a Merge branch 'main' into renovate/zizmorcore-zizmor-pre-commit-1.x
Build / build (pull_request) Successful in 18s
Lint / lint (pull_request) Successful in 1m28s
Molecule / molecule (pull_request) Successful in 2s
2026-11-23 19:06:51 +00:00
Defame1297 bca13f4139 Merge pull request 'feat(gitea_runner): bound the Docker image cache by count and disk usage' (#328) from feat/319-docker-prune-count-threshold into main
Build / build (push) Successful in 17s
Lint / lint (push) Successful in 1m16s
Molecule / molecule (push) Canceled after 8m2s
Reviewed-on: #328
Reviewed-by: Defame1297 <[email protected]>
2026-11-23 19:06:42 +00:00
Defame1297 35f7e772a5 Merge branch 'main' into feat/319-docker-prune-count-threshold
Build / build (pull_request) Successful in 16s
Lint / lint (pull_request) Successful in 1m48s
Molecule / molecule (pull_request) Successful in 2m32s
2026-11-23 18:41:11 +00:00
Defame1297 ee4cb160ea test(gitea_runner): pin the disk check and refused-input messages
Build / build (pull_request) Canceled after 0s
Lint / lint (pull_request) Canceled after 0s
Molecule / molecule (pull_request) Canceled after 0s
The weekly schedule and image age cases matched text the disk check
schedule message also holds; match each assert's own message. Add a
case at exactly the root's use so the strict comparison is pinned, and
check the below message so a df failure cannot pass for it.

Refs #319

Assisted-by: Claude Code
2026-11-23 18:35:53 +00:00
renovate-bot 8d7e71c881 chore(deps): update pre-commit hook zizmorcore/zizmor-pre-commit to v1.33.1
renovate/stability-days Updates have met minimum release age requirement
Build / build (pull_request) Successful in 17s
Lint / lint (pull_request) Successful in 1m38s
Molecule / molecule (pull_request) Successful in 2s
2026-11-23 18:27:09 +00:00
renovate-bot d87b0e79cc chore(deps): update git.rkdr.net/mortis/molecule-ubuntu2404 docker tag to v0.1.9
renovate/stability-days Updates have met minimum release age requirement
Build / build (pull_request) Successful in 18s
Lint / lint (pull_request) Successful in 1m45s
Molecule / molecule (pull_request) Successful in 13m31s
2026-11-23 18:27:04 +00:00
renovate-bot 1d1fe06bf5 chore(deps): update git.rkdr.net/mortis/ci docker tag to v0.2.35
renovate/stability-days Updates have met minimum release age requirement
Build / build (pull_request) Successful in 46s
Gitea release key / check (pull_request) Successful in 9s
Lint / lint (pull_request) Successful in 59s
Molecule / molecule (pull_request) Successful in 3s
2026-11-23 18:26:59 +00:00
Dragonish 325c24a8d0 docs(system_baseline): add a Proxmox example for the package blacklist
Build / build (pull_request) Successful in 17s
Lint / lint (pull_request) Successful in 1m23s
Molecule / molecule (pull_request) Successful in 2m6s
Packages that should only change through a deliberate apt dist-upgrade.

Assisted-by: Claude Code
2026-11-23 18:24:34 +00:00
Dragonish e4c69dfdd8 feat(system_baseline): add a per-host package blacklist for unattended-upgrades
Build / build (pull_request) Successful in 19s
Lint / lint (pull_request) Successful in 1m21s
Molecule / molecule (pull_request) Successful in 2m8s
system_baseline_unattended_upgrade_package_blacklist (list of regular
expressions, default empty) is written to a drop-in as
Unattended-Upgrade::Package-Blacklist; an empty list removes it.

Assisted-by: Claude Code
2026-11-23 18:22:24 +00:00
Defame1297 e91c074373 fix(gitea_runner): address review of the prune count and threshold
Give each new input its own assert message so every refused-input case
matches only its own input, and cover a negative count and a bad disk
check schedule. Fire the pressure prune only above the threshold, as
the inputs describe it. Name the disk check script apart from the
pressure service, prefix the new registers as internal, and keep the
new comments short.

Refs #319

Assisted-by: Claude Code
2026-11-23 18:20:32 +00:00
Defame1297 9b968e1e71 Merge pull request 'fix(system_baseline): do not report a pending package upgrade as drift in check mode' (#323) from fix/321-system-baseline-check-mode into main
Build / build (push) Successful in 17s
Lint / lint (push) Successful in 1m29s
Molecule / molecule (push) Successful in 14m48s
Reviewed-on: #323
Reviewed-by: Defame1297 <[email protected]>
2026-11-23 18:09:58 +00:00
Defame1297 637a297e00 Merge branch 'main' into fix/321-system-baseline-check-mode
Build / build (pull_request) Successful in 18s
Lint / lint (pull_request) Successful in 2m50s
Molecule / molecule (pull_request) Successful in 1m38s
2026-11-23 18:05:02 +00:00
Defame1297 f50ecc2945 feat(gitea_runner): bound the Docker image cache by count and disk usage
An age-based prune does not cap disk use: the cache grows with how often
new image versions are published, and builds on the runner then fail for
lack of space. Keep the newest N image IDs per repository in the weekly
prune, and add an hourly pressure prune that runs the count prune and a
capped builder prune when the Docker root's filesystem passes a
threshold, behind the same job gate. Both are off by default.

Refs #319

Assisted-by: Claude Code
2026-11-23 18:04:50 +00:00
kamino-renovate Bot 8e512416e9 Merge pull request 'chore(deps): update git.rkdr.net/mortis/ci docker tag to v0.2.34' (#311) from renovate/git.rkdr.net-mortis-ci-0.x into main
Build / build (push) Successful in 1m7s
Lint / lint (push) Successful in 1m13s
2026-11-23 17:54:59 +00:00
Dragonish 55bd5d5231 fix(system_baseline): do not report a pending package upgrade as drift in check mode
Build / build (pull_request) Successful in 17s
Molecule / molecule (pull_request) Successful in 1m52s
Lint / lint (pull_request) Successful in 2m8s
The main flow skips the apt upgrade in check mode; autoremove and
autoclean are a task of their own and stay checked. The update entry
point is unchanged and still previews the upgrade.

Assisted-by: Claude Code
2026-11-23 17:54:58 +00:00
Defame1297 dab942afde Merge branch 'main' into renovate/git.rkdr.net-mortis-ci-0.x
Build / build (pull_request) Successful in 22s
Gitea release key / check (pull_request) Successful in 7s
Lint / lint (pull_request) Successful in 1m12s
Molecule / molecule (pull_request) Successful in 1s
2026-11-23 17:52:30 +00:00
Defame1297 344bf33ca1 Merge pull request 'chore(deps): update ubuntu:24.04 docker digest to 9c7f200' (#310) from renovate/job-container-ubuntu-24.04 into main
Build / build (push) Successful in 23s
Images / image (Dockerfile, ubuntu:24.04@sha256:9c7f200c07e3d4a03e7249d2c16bf66a51120fb876aa2242cf31451412543289, molecule-ubuntu2404, images/molecule-ubuntu2404, 0.1.9) (push) Successful in 18s
Lint / lint (push) Successful in 1m40s
Images / image (Dockerfile, ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db, molecule-ubuntu2604, images/molecule-ubuntu2604, 0.1.5) (push) Successful in 11s
Images / image (images/ci/Dockerfile, ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db, ci, , 0.2.35) (push) Successful in 11s
Reviewed-on: #310
2026-11-23 17:45:33 +00:00
Defame1297 3695d2dc6b Merge branch 'main' into renovate/job-container-ubuntu-24.04
Build / build (pull_request) Successful in 19s
Lint / lint (pull_request) Successful in 1m31s
Molecule / molecule (pull_request) Successful in 4s
2026-11-23 17:43:35 +00:00
Defame1297 3f2d184922 Merge pull request 'docs: follow-ups from #318 (bot-diff wording, glossary scope, standalone roadmap)' (#320) from docs/215-followups into main
Build / build (push) Successful in 21s
Lint / lint (push) Successful in 1m27s
Reviewed-on: #320
Reviewed-by: Defame1297 <[email protected]>
2026-11-23 17:30:08 +00:00
Defame1297 a0a871e3f9 docs(readme): drop the private-repository reference from the roadmap
Build / build (pull_request) Successful in 17s
Lint / lint (pull_request) Successful in 1m54s
Molecule / molecule (pull_request) Successful in 1s
The public-place rule bars naming another of the maintainer's
repositories, its issues or its decisions; the roadmap stands alone
without them.

Assisted-by: Claude Code
2026-11-23 17:12:24 +00:00
Defame1297 51f5be20a4 docs(glossary): widen the opening line to the role terms
The glossary now holds the role terms (Role interface, Internal role),
which the opening line left out.

Assisted-by: Claude Code
2026-11-23 17:12:15 +00:00
Defame1297 07fb8a6d21 chore: call the bot-diff check by its name outside the docs
The glossary avoids gate and guard; the check is
scripts/check_bot_pr_diff.py, so name it as the docs now do.

Assisted-by: Claude Code
2026-11-23 17:12:09 +00:00
Defame1297 9c7b7e6e9e Merge branch 'main' into renovate/job-container-ubuntu-24.04
Build / build (pull_request) Successful in 18s
Lint / lint (pull_request) Successful in 1m45s
Molecule / molecule (pull_request) Successful in 2s
2026-11-23 17:00:22 +00:00
Defame1297 c438d40bbe Merge pull request 'docs(glossary): widen control and define review, aspirational, scheduled merge and the role terms' (#318) from docs/215-glossary-control into main
Build / build (push) Successful in 20s
Lint / lint (push) Successful in 2m6s
Molecule / molecule (push) Failing after 14m38s
Reviewed-on: #318
Reviewed-by: Defame1297 <[email protected]>
2026-11-23 16:59:59 +00:00
Defame1297 10c14898f2 Merge branch 'main' into docs/215-glossary-control
Lint / lint (pull_request) Successful in 1m24s
Molecule / molecule (pull_request) Successful in 2s
Build / build (pull_request) Successful in 18s
2026-11-23 16:54:47 +00:00
kamino-renovate Bot 4c6dbf41bd Merge pull request 'chore(deps): update ubuntu:24.04 docker digest to 9c7f200' (#309) from renovate/ubuntu-24.04 into main
Build / build (push) Successful in 20s
Images / image (Dockerfile, ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8, molecule-ubuntu2404, images/molecule-ubuntu2404, 0.1.9) (push) Successful in 33s
Lint / lint (push) Successful in 1m34s
Images / image (Dockerfile, ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db, molecule-ubuntu2604, images/molecule-ubuntu2604, 0.1.5) (push) Successful in 10s
Images / image (images/ci/Dockerfile, ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db, ci, , 0.2.35) (push) Successful in 9s
2026-11-23 16:54:31 +00:00
Defame1297 a052713aa1 docs(glossary): widen control and define review, aspirational, scheduled merge and the role terms
Lint / lint (pull_request) Canceled after 0s
Molecule / molecule (pull_request) Canceled after 0s
Build / build (pull_request) Canceled after 21s
The held-by lines in AGENTS.md and the contributor docs hold rules by a control,
by review or aspirationally, and SECURITY.md's Accepted risks count repository
settings such as branch protection and code-owner approval, but the glossary
defined only control and limited it to hooks and CI jobs. Define all three, the
merge and role terms, and replace the avoided gate, guard and enforce wording.

Assisted-by: Claude Code
2026-11-23 16:40:54 +00:00
Defame1297 1edad97c0d Merge branch 'main' into renovate/ubuntu-24.04
Build / build (pull_request) Successful in 20s
Lint / lint (pull_request) Successful in 1m33s
Molecule / molecule (pull_request) Successful in 2s
2026-11-23 16:38:12 +00:00
Claude 50c881fa7c Merge pull request 'chore(release): 1.11.0' (#317) from chore/release-1.11.0 into main
Lint / lint (push) Successful in 2m1s
Molecule / molecule (push) Successful in 14m10s
Build / build (push) Successful in 22s
2026-11-23 16:35:37 +00:00
Defame1297 282c010167 chore(release): 1.11.0
Build / build (pull_request) Successful in 17s
Lint / lint (pull_request) Successful in 1m29s
Molecule / molecule (pull_request) Successful in 13m21s
Minor release that adds the cloudflared role (#316).

Assisted-by: Claude Code:claude-opus-5-5
2026-11-23 16:03:41 +00:00
Defame1297 db237569b2 Merge pull request 'feat(cloudflared): add the cloudflared role' (#316) from feat/cloudflared-role into main
Build / build (push) Successful in 17s
Lint / lint (push) Successful in 2m56s
Molecule / molecule (push) Successful in 14m34s
Reviewed-on: #316
Reviewed-by: Defame1297 <[email protected]>
2026-11-23 16:02:40 +00:00
Defame1297 42c391ccbe fix(cloudflared): quote the mint POST status assertion in verify.yml
Build / build (pull_request) Successful in 17s
Lint / lint (pull_request) Successful in 1m39s
Molecule / molecule (pull_request) Successful in 2m20s
The plain scalar `cloudflared_test_posts[0] is search('"status": 200')`
holds ': ', so YAML parsed it as a one-key mapping and ansible-core
refused it ("Conditional expressions must be strings"). A folded block
scalar keeps it a string.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-23 15:56:30 +00:00
Defame1297 701226f499 fix(cloudflared): escape the stub's shell variables in molecule.yml
Build / build (pull_request) Successful in 19s
Lint / lint (pull_request) Successful in 1m23s
Molecule / molecule (pull_request) Failing after 2m21s
molecule interpolates environment variables in molecule.yml, so `$1`
and `$*` in the embedded stub script failed the config parse ("Invalid
placeholder") before any step ran. `$$` renders as a literal `$`.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-23 15:11:21 +00:00
Defame1297 92534a486e test(cloudflared): stop the API stub only while its pid is still the stub
Build / build (pull_request) Successful in 17s
Lint / lint (pull_request) Successful in 2m11s
Molecule / molecule (pull_request) Failing after 1s
Cleanup now checks /proc/<pid>/cmdline before it signals the pid, so a
reused pid is never killed, and removes the pid file afterwards.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-23 14:57:34 +00:00
Defame1297 eaa5d2f4ee fix(cloudflared): query DNS per hostname and validate config.yml first
The overwrite guard listed the zone's first 100 records only, so a
record further on went unseen. It now queries each ingress hostname by
name and compares names case-insensitively, and the prune listing pages
through result_info.total_pages. Query values are urlencoded. The
template task validates config.yml with cloudflared before it replaces
the file; the rendered content is unchanged. The API stub filters by
name and pages to match.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-23 14:55:59 +00:00
Defame1297 fd1e9b67dd fix(cloudflared): refuse unsafe hostnames, names, paths and tunnel ids
Ingress hostnames must be lowercase, with an optional leading *. and no
whitespace: they land unquoted in config.yml. The service account names
and directories must hold no newline or %, which the unit would read as
directives, and the directories must be absolute. A set tunnel id must
be a lowercase UUID, the shape the stale-credentials search relies on.
Each refusal has a negative case in the scenario.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-23 14:51:13 +00:00
Defame1297 ee0fa0e89e test(cloudflared): cover a tunnel lookup that fails with another status
Assisted-by: Claude Code:claude-opus-5-5
2026-11-23 14:22:22 +00:00
Defame1297 fea99a8207 fix(cloudflared): reach the re-mint message after a 404 tunnel lookup
A lookup that still returned 404 after its retries failed the lookup
task itself, whose output no_log hides, so the message with the re-mint
steps never ran. The lookup now ignores its own failure; the next task
fails with the re-mint steps for a 404 or a deleted tunnel, and a new
one fails with the HTTP status for any other lookup error.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-23 14:22:22 +00:00
Defame1297 d73b5b03dd docs(readme): add cloudflared to the _binary_update callers
The role is in the Collection now, so it leaves the wave 2 Roadmap
line, and the status line names it as an unreleased caller of the
internal _binary_update role.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-23 14:22:22 +00:00
Defame1297 9a626962a5 test(cloudflared): add the default molecule scenario
Runs without Cloudflare and without a real cloudflared: a stub of the
Cloudflare API on the controller's loopback answers the tunnel, zone and
DNS record calls through cloudflared_api_base_url, a stub binary stands
in for the daemon, and the releases come from file:// URLs.

Covers the converge with an update through _binary_update and its
idempotence, the rendered files and the running unit, the input asserts,
the deleted-tunnel and DNS guards, a stale hash and a failed checksum,
the mint entry point (as child processes outside CI) and the remove
path. The cloudflare_dns calls cannot reach the stub and are not run.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-23 14:22:16 +00:00
Defame1297 e308683431 feat(cloudflared): add the cloudflared role
Installs cloudflared as a systemd service for a locally managed
Cloudflare Tunnel: checks that the tunnel exists, manages its proxied
CNAMEs, renders config.yml and the credentials file, and updates the
binary through the internal _binary_update role. The opt-in mint entry
point creates the tunnel and registers its id and credentials as no_log
facts for the calling play to persist.

Validation runs first under always and asserts the tunnel secrets with
the mint instructions; the secrets stay optional in the argument spec on
purpose. cloudflared_manage_dns lets the records be managed elsewhere.
A removal now ends the role.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-23 14:22:16 +00:00
renovate-bot 929506882e chore(deps): update git.rkdr.net/mortis/ci docker tag to v0.2.34
renovate/stability-days Updates have met minimum release age requirement
Build / build (pull_request) Successful in 44s
Gitea release key / check (pull_request) Successful in 9m17s
Lint / lint (pull_request) Successful in 55s
Molecule / molecule (pull_request) Successful in 2s
2026-11-23 10:27:13 +00:00
renovate-bot 29f66897f2 chore(deps): update ubuntu:24.04 docker digest to 9c7f200
renovate/stability-days Updates have met minimum release age requirement
Build / build (pull_request) Successful in 15s
Lint / lint (pull_request) Successful in 1m19s
Molecule / molecule (pull_request) Successful in 5s
2026-11-23 10:27:12 +00:00
renovate-bot f34769bca2 chore(deps): update ubuntu:24.04 docker digest to 9c7f200
renovate/stability-days Updates have met minimum release age requirement
Build / build (pull_request) Successful in 15s
Lint / lint (pull_request) Successful in 1m16s
Molecule / molecule (pull_request) Successful in 1s
2026-11-23 10:27:10 +00:00
93 changed files with 3247 additions and 77 deletions

No files matched your search

+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
timeout-minutes: 30
# The ci image (images/ci, built by image.yml): tag for the release, digest enforced.
container:
image: git.rkdr.net/mortis/ci:0.2.33@sha256:2020686a819c5bdac6f773237479083ccc291a00351a6647c26a2dec5341de43
image: git.rkdr.net/mortis/ci:0.2.35@sha256:307d51be744f3be5965af8783e88bd3fdda911dd53bb8a939d0710256e2e97d3
env:
PIP_DISABLE_PIP_VERSION_CHECK: "1"
steps:
+1 -1
View File
@@ -44,7 +44,7 @@ jobs:
# The ci image (images/ci, built by image.yml), at the pin of lint.yml: tag for the
# release, digest enforced. Only its /opt/venv Python (with PyYAML) is used here.
container:
image: git.rkdr.net/mortis/ci:0.2.33@sha256:2020686a819c5bdac6f773237479083ccc291a00351a6647c26a2dec5341de43
image: git.rkdr.net/mortis/ci:0.2.35@sha256:307d51be744f3be5965af8783e88bd3fdda911dd53bb8a939d0710256e2e97d3
steps:
# The container has no Node, so JavaScript actions such as actions/checkout
# cannot run; clone with git and the job token.
+3 -3
View File
@@ -77,17 +77,17 @@ jobs:
matrix:
include:
- name: molecule-ubuntu2404
version: 0.1.8
version: 0.1.9
subpath: images/molecule-ubuntu2404
dockerfile: Dockerfile
job_image: ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8
job_image: ubuntu:24.04@sha256:9c7f200c07e3d4a03e7249d2c16bf66a51120fb876aa2242cf31451412543289
- name: molecule-ubuntu2604
version: 0.1.5
subpath: images/molecule-ubuntu2604
dockerfile: Dockerfile
job_image: ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db
- name: ci
version: 0.2.35
version: 0.2.38
subpath: ""
dockerfile: images/ci/Dockerfile
job_image: ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db
+1 -1
View File
@@ -35,7 +35,7 @@ jobs:
# The tag says which release, the digest is what is enforced (bump both together
# when image.yml publishes a new version).
container:
image: git.rkdr.net/mortis/ci:0.2.33@sha256:2020686a819c5bdac6f773237479083ccc291a00351a6647c26a2dec5341de43
image: git.rkdr.net/mortis/ci:0.2.35@sha256:307d51be744f3be5965af8783e88bd3fdda911dd53bb8a939d0710256e2e97d3
env:
PIP_DISABLE_PIP_VERSION_CHECK: "1"
PRE_COMMIT_HOME: /opt/pre-commit
+1 -1
View File
@@ -70,7 +70,7 @@ jobs:
# Used by the scenarios as `image: ${MOLECULE_IMAGE}`; set it the same way to run
# one locally.
MOLECULE_IMAGE: >-
git.rkdr.net/mortis/molecule-ubuntu2404:0.1.8@sha256:e1ea7c6f953626c39d9f578d60a1ef668f09ed4e5d537d5c7601668b5c5e0eb3
git.rkdr.net/mortis/molecule-ubuntu2404:0.1.9@sha256:2687d921fdcadf49c36bd7a3b01eaf5f2a53fa0e8f9ed91b2c7ab0631022193b
# The same for Ubuntu 26.04, the release the hosts are moving to; used by
# `image: ${MOLECULE_IMAGE_2604}` in extensions/molecule/image-smoke-2604.
MOLECULE_IMAGE_2604: >-
+12 -1
View File
@@ -68,7 +68,7 @@ repos:
# --offline: no network audits, so a run needs no token and gives the same result everywhere.
# Overriding args drops the hook's default, so --no-progress is repeated here.
- repo: https://github.com/zizmorcore/zizmor-pre-commit
rev: 0eb9e4a60caf04df64b499ed1e8bef55f4440eae # frozen: v1.33.0
rev: c7d31dc612dffdd4d3b2f2b88b9660d3ab057ee8 # frozen: v1.33.1
hooks:
- id: zizmor
args: [--no-progress, --offline]
@@ -126,6 +126,17 @@ repos:
require_serial: true
fail_fast: true
# apm compile (target claude), a tool's project init or a skill can create a CLAUDE.md, and
# the failure is silent: the agent gets no guidance and no error.
- id: refuse-claude-md
name: Refuse CLAUDE.md files
description: refuse CLAUDE.md, CLAUDE.local.md and .claude/CLAUDE.md at any depth, in any case
entry: a CLAUDE.md file makes Claude Code ignore every AGENTS.md; delete it
language: fail
# Any letter case: a case-insensitive file system serves claude.md as CLAUDE.md.
files: (?i)(^|/)(\.claude/)?claude(\.local)?\.md$
stages: ['pre-commit']
- repo: meta
hooks:
- id: check-hooks-apply
+1 -1
View File
@@ -10,7 +10,7 @@ held: by a control (a named hook or check), by review, or aspirational (checked
1. **Accountability**: every change has a human author who understands it and answers for it; an agent is a tool.
2. **A human decides what is irreversible or shared**: settings, protection, tags, releases, credentials, merges to `main`; a merge is decided case by case or by a standing rule a human reviewed, such as Renovate's automerge policy in `renovate.json`.
3. **Secrets and supply chain**: no secret in the repository, a prompt or a log; dependencies and images are pinned and change through review.
4. **Enforced, not trusted**: a rule that matters gets a control; one without is labelled as such.
4. **Controlled, not trusted**: a rule that matters gets a control; one without is labelled as such.
5. **Honest reporting**: a pull request says what was verified and what was not.
6. **Simple enough to review**: see the code-style rules below.
7. **Openness and licence**: AI assistance is disclosed; contributions are GPL-compatible and REUSE-clean.
+8
View File
@@ -4,6 +4,14 @@ mortis.kamino Release Notes
.. contents:: Topics
v1.11.0
=======
Minor Changes
-------------
- cloudflared - New role. Installs cloudflared as a systemd service for a locally managed Cloudflare Tunnel, with a sha256-verified binary, checks that the tunnel still exists, renders ``config.yml`` from ``cloudflared_ingress``, writes the tunnel credentials, and with ``cloudflared_manage_dns`` (default true) points a proxied CNAME for every ingress hostname at the tunnel, refusing to overwrite a record that does not point at a tunnel and pruning CNAMEs of this tunnel that are no longer listed. With ``cloudflared_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. ``cloudflared_remove`` removes the daemon and ends the role; with ``cloudflared_remove_data`` it also deletes the tunnel and its records on Cloudflare. The opt-in ``mint`` entry point creates the tunnel with a secret generated in memory and registers its id and credentials as ``no_log`` facts for the calling play to persist; it is refused under CI and does nothing when a tunnel is already set.
v1.10.2
=======
+1 -1
View File
@@ -8,7 +8,7 @@
# Some patterns name paths that do not exist yet, so the file is in place before they do.
# Everything else is unowned, so role changes merge on green checks. requirements-dev.txt,
# requirements-dev.lock and requirements.yml stay unowned on purpose, so Renovate's pin
# bumps keep automerging behind the bot-diff gate.
# bumps keep automerging behind the bot-diff check.
CODEOWNERS @Defame1297
\\.gitea/.* @Defame1297
+28 -2
View File
@@ -1,11 +1,13 @@
# Kamino
The language of contributing to the `mortis.kamino` Ansible Collection: how its guidance for contributors and their agents is named.
The language of contributing to the `mortis.kamino` Ansible Collection: how the guidance for its contributors and their agents, and its role interface, are named.
## Language
### Guidance
A rule is held in exactly one of three ways: by a control (naming the check), by review, or aspirationally; an agent instruction is a place a rule lives, not a way it is held.
**Principle**:
A commitment that holds across the whole repository, stated with its reason.
_Avoid_: Value, guideline, philosophy
@@ -15,9 +17,17 @@ What a principle requires of a contributor, human or agent, in one area of the r
_Avoid_: Convention, policy, standard
**Control**:
A mechanical check, a hook or a CI job, that holds a rule without depending on anyone's attention.
A mechanical check (a hook, a CI job or a repository setting) that holds a rule without depending on anyone's attention. Something that only proposes a change, such as a Renovate pull request, is not one: a human or another control still decides.
_Avoid_: Gate, guard, guardrail, enforcement
**Review**:
A person other than the one acting sees the change before it takes effect, such as a pull request reviewer or a code-owner approval.
_Avoid_: Sign-off
**Aspirational**:
Written down and relied on, but checked by nothing and nobody, so a breach is found only by chance.
_Avoid_: Best effort, honour system
### People
There are two positions, each held per repository: a trusted contributor of another repository in the organisation is an outsider here unless given write access here.
@@ -43,3 +53,19 @@ _Avoid_: Bot, autonomous agent, AFK agent
**Agent account**:
A Gitea account used only by agents, with exactly one accountable person.
_Avoid_: Bot account, service account
### Merging
**Scheduled merge**:
A merge set to run once the required checks pass; it merges whatever head the branch has at that moment, as the person who set it. Renovate's automerge is one.
_Avoid_: Automerge (for the general case), merge when checks succeed
### Roles
**Role interface**:
What a consumer of a role may depend on: its inputs, supported entry points, documented output facts and documented tags.
_Avoid_: API, public surface
**Internal role**:
A role that only other roles of the Collection call; its interface is not part of the Collection's versioning promise.
_Avoid_: Private role, helper role
+5 -7
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.10.2 holds the `docker`, `fail2ban`, `gitea`, `gitea_runner`, `network_interfaces`, `sshd`, `system_baseline`, `systemd_hardening`, `traefik`, `ufw` and `user_management` roles (and the internal `_binary_update`, which `gitea`, `gitea_runner` and `traefik` call).
Status: roles arrive in waves. Release 1.11.0 holds the `cloudflared`, `docker`, `fail2ban`, `gitea`, `gitea_runner`, `network_interfaces`, `sshd`, `system_baseline`, `systemd_hardening`, `traefik`, `ufw` and `user_management` roles (and the internal `_binary_update`, which `cloudflared`, `gitea`, `gitea_runner` and `traefik` call).
## Consuming
@@ -16,7 +16,7 @@ name (FQCN) only, `mortis.kamino.<role>`:
collections:
- name: https://git.rkdr.net/mortis/kamino.git
type: git
version: v1.10.2
version: v1.11.0
```
Its dependencies (`community.general`, `ansible.posix`) are declared in `galaxy.yml`, so
@@ -33,14 +33,12 @@ input carries the role name as a prefix (`<role>_<name>`).
## Roadmap
Roles are extracted from the author's private environment repository in waves
(tracked in that repository's epic #486 and its ADR 0001). The order inside a wave is
not a promise, and a role arrives only when its own gates (tests, a safe cutover of
the environment that uses it) are met.
Roles arrive in waves. The order inside a wave is not a promise, and a role arrives only
when its own prerequisites (tests, a safe cutover wherever the role already runs) are met.
Still to come:
- Wave 2: `pve_vm`, `pve_lxc`, `tailscale`, `cloudflared`, `pihole`.
- Wave 2: `pve_vm`, `pve_lxc`, `tailscale`, `pihole`.
- Wave 3: `rke2`, `proxmox_host`.
- Later, wave not yet assigned: `opnsense`, `proxmox_firewall`.
+3 -3
View File
@@ -93,8 +93,8 @@ reduction. A later decision that accepts a risk adds an entry here.
- **Risk:** a writer can add a version-shaped change to such a pull request, and it merges as
the Renovate bot.
- **Why accepted:** bounded by the bot-diff gate (shape, not value) and by code-owner
approval, which a push dismisses; every account that can push there already reaches every
secret. There is no `renovate/*` push allowlist.
- **Why accepted:** bounded by the bot-diff check (`scripts/check_bot_pr_diff.py`: shape, not
value) and by code-owner approval, which a push dismisses; every account that can push there
already reaches every secret. There is no `renovate/*` push allowlist.
- **Trigger:** a token that can push here but cannot reach the secrets.
- **Planned reduction:** none for now.
+6 -1
View File
@@ -5,6 +5,11 @@ objects:
with rollback'
name: _binary_update
version_added: null
cloudflared:
description: Install and run cloudflared for a locally managed Cloudflare Tunnel,
with its DNS records
name: cloudflared
version_added: null
docker:
description: Install, update or remove Docker Engine
name: docker
@@ -66,4 +71,4 @@ plugins:
strategy: {}
test: {}
vars: {}
version: 1.10.2
version: 1.11.0
+20
View File
@@ -85,6 +85,26 @@ releases:
fragments:
- systemd-hardening-sockets.yml
release_date: '2026-11-23'
1.11.0:
changes:
minor_changes:
- cloudflared - New role. Installs cloudflared as a systemd service for a locally
managed Cloudflare Tunnel, with a sha256-verified binary, checks that the
tunnel still exists, renders ``config.yml`` from ``cloudflared_ingress``,
writes the tunnel credentials, and with ``cloudflared_manage_dns`` (default
true) points a proxied CNAME for every ingress hostname at the tunnel, refusing
to overwrite a record that does not point at a tunnel and pruning CNAMEs of
this tunnel that are no longer listed. With ``cloudflared_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. ``cloudflared_remove``
removes the daemon and ends the role; with ``cloudflared_remove_data`` it
also deletes the tunnel and its records on Cloudflare. The opt-in ``mint``
entry point creates the tunnel with a secret generated in memory and registers
its id and credentials as ``no_log`` facts for the calling play to persist;
it is refused under CI and does nothing when a tunnel is already set.
fragments:
- cloudflared-role.yml
release_date: '2026-11-23'
1.2.0:
changes:
minor_changes:
@@ -0,0 +1,7 @@
---
minor_changes:
- >-
docker - ``docker_apt_arch`` now defaults to an empty value that derives the apt architecture from the host (``x86_64`` gives ``amd64``,
``aarch64`` gives ``arm64``) instead of always writing ``amd64``, so an arm64 host no longer needs an override. A value set in the inventory
is used as before. A host with any other architecture fails the play with a message that names ``docker_apt_arch`` instead of getting an
``amd64`` source line that its apt cannot use; set ``docker_apt_arch`` for such a host.
+7
View File
@@ -0,0 +1,7 @@
---
minor_changes:
- >-
fail2ban - the main entry point now reloads Fail2Ban when ``jail.local`` changes instead of restarting it, as ``service_jail``
already did. A restart stops every jail, which flushes its bans out of the firewall until they are restored from Fail2Ban's
database, and forgets failures counted toward ``maxretry``; a reload applies the new settings to the running jails. The
``Restart Fail2Ban`` handler is removed: nothing in the role notifies it any more.
@@ -0,0 +1,9 @@
---
minor_changes:
- >-
gitea_runner - The Docker prune can bound the image cache by count and by disk use. With
``gitea_runner_docker_prune_keep_per_repository`` above 0 the weekly prune keeps the newest N image IDs of each
repository and removes every other image no container uses. With ``gitea_runner_docker_prune_disk_threshold_percent``
set, a timer (``gitea_runner_docker_prune_disk_check_schedule``, hourly by default) runs the count prune and a builder
prune capped at ``gitea_runner_docker_prune_builder_keep_storage`` when the filesystem holding the Docker root is
fuller than that, behind the same job gate as the weekly prune. Both are off by default.
@@ -0,0 +1,8 @@
---
bugfixes:
- >-
system_baseline - Do not run the apt upgrade in check mode in the main flow. A package that is only waiting for the next patch run, or a
package cache older than an hour, is not drift, but the package module reports both as changed, so a scheduled dry run flagged every
host. Autoremove and autoclean are now a task of their own and stay checked; as part of the upgrade call the module did not reach
autoclean, so ``apt-get autoclean`` now runs (and may report changed once on a host with stale archives), in the main flow and in the
``update`` entry point. The ``update`` entry point still previews the upgrade in check mode.
@@ -0,0 +1,6 @@
---
minor_changes:
- >-
system_baseline - Add ``system_baseline_unattended_upgrade_package_blacklist`` (list of regular expressions, default empty). A non-empty
list is written to ``/etc/apt/apt.conf.d/90unattended-upgrades-blacklist`` as ``Unattended-Upgrade::Package-Blacklist``, so unattended-upgrades
leaves those packages alone on a host whose kernel or drivers must not change. An empty list removes the file.
+2 -1
View File
@@ -45,7 +45,8 @@ contributor docs are held by review until an offline link check exists. Terms su
[SECURITY.md](../../SECURITY.md)).
*Held by:* aspirational.
- **No agent approves or merges a pull request, driven or unattended.**
*Reason:* approval by a code owner is the gate, and an agent that approves passes its own gate.
*Reason:* approval by a code owner is the review, and an agent's approval is not a review by a
person other than the one acting.
*Held by:* control for agent accounts (they are outside the merge and approvals allowlists of the
branch protection); review for an agent acting with a contributor's own token.
- **Every agent account has exactly one accountable person, named in its Gitea profile.**
+2 -1
View File
@@ -91,7 +91,8 @@ The rules for these live next to the files they govern: [scripts/AGENTS.md](../.
(scripts, their tests, tool pins and their lock, hook SHA pins),
[images/AGENTS.md](../../images/AGENTS.md) (image inputs, version bumps, pin pull requests, the layer
limit), [.gitea/workflows/AGENTS.md](../../.gitea/workflows/AGENTS.md) (workflows, secrets, the
bot-diff gate) and [docs/adr/AGENTS.md](../adr/AGENTS.md) (decision records).
bot-diff check `scripts/check_bot_pr_diff.py`) and [docs/adr/AGENTS.md](../adr/AGENTS.md) (decision
records).
- **Test a change to `renovate.json` before the merge with `renovate --platform=local`** (the version
in `.gitea/workflows/renovate.yml`), which reads your checkout.
+2 -2
View File
@@ -40,8 +40,8 @@ held by review until an offline link check exists.
*Reason:* it is the one visible sign that the agent loaded the guidance.
*Held by:* aspirational.
- **The tracked `.claude/settings.json` never holds `permissions.allow`; `deny` and `ask` rules are
allowed. Your own allowlist and personal guards go in `.claude/settings.local.json`, which is never
committed.**
allowed. Your own allowlist, hooks and any other rules you do not want shared go in
`.claude/settings.local.json`, which is never committed.**
*Reason:* a branch's settings take effect for whoever opens it with an agent, so an `allow` rule
pushed on an unmerged branch lets that branch's commands run without a prompt before anyone has
reviewed it, while a `deny` or `ask` rule can only add prompts.
+2 -2
View File
@@ -67,7 +67,7 @@ real consumers.
- `<version>` is semver, independent of the Collection's version. A published version is never moved or
rebuilt, so one digest belongs to exactly one version. `latest` is the newest version, for looking only.
- Pin `ci:<version>@sha256:<digest>`; the digest is what is enforced. Consumers: `lint.yml`, `build.yml` and
- Pin `ci:<version>@sha256:<digest>`; the digest decides what is pulled. Consumers: `lint.yml`, `build.yml` and
`gitea-release-key.yml`.
- Renovate is configured to move the pins to a new version after the image is built on `main` (the rule is in
`renovate.json`; the first pin of a brand-new image is made by hand).
@@ -78,7 +78,7 @@ real consumers.
files are copied in). The workflow runs on pushes to `main` that touch `images/**`, `requirements-dev.txt`, `requirements-dev.lock`, `requirements.yml`,
`.pre-commit-config.yaml` or the workflow itself, never on a pull request, and builds an image only when its
`version:` in the workflow's matrix is not yet published. A change to the image's inputs therefore needs a new
`version:` (Lint enforces it, and Renovate's bump step does it for dependency updates), and the merge builds
`version:` (Lint checks it, and Renovate's bump step does it for dependency updates), and the merge builds
the image. Each pushed layer stays below 100 MB (Cloudflare's request limit), which is why the Go toolchains
and the unused Go binaries are deleted from the hook cache, and why the build prints the compressed size of each layer
directory.
+2 -2
View File
@@ -58,7 +58,7 @@ systemd, packages, the `dbus` and `ssh` units, the Python bindings, `NET_ADMIN`)
- `<version>` is semver (`MAJOR.MINOR.PATCH`), independent of the Collection's version. A published
version is never moved or rebuilt, so one digest belongs to exactly one version. `latest` is the
newest version and is for looking, not for pinning.
- Pin `molecule-ubuntu2404:<version>@sha256:<digest>`; the digest is what is enforced. Consumers here:
- Pin `molecule-ubuntu2404:<version>@sha256:<digest>`; the digest decides what is pulled. Consumers here:
`.gitea/workflows/molecule.yml`.
- Renovate is configured to move the pin to a new version after the image is built on `main` (the rule is in
`renovate.json`; the first pin of a brand-new image is made by hand).
@@ -68,7 +68,7 @@ systemd, packages, the `dbus` and `ssh` units, the Python bindings, `NET_ADMIN`)
`.gitea/workflows/image.yml` builds it with kaniko. The workflow runs on pushes to `main` that touch `images/**`,
`requirements-dev.txt`, `requirements-dev.lock`, `requirements.yml`, `.pre-commit-config.yaml` or the workflow itself, never on a pull request, and builds an
image only when its `version:` in the workflow's matrix is not yet published. A change under
`images/molecule-ubuntu2404/` therefore needs a new `version:` (Lint enforces it) and the merge builds the image. The
`images/molecule-ubuntu2404/` therefore needs a new `version:` (Lint checks it) and the merge builds the image. The
Ubuntu release is fixed by the name: a new Ubuntu release is a new image (`molecule-ubuntuNNNN`), and the roles
are tested on every release the hosts run or are moving to.
+2 -2
View File
@@ -57,7 +57,7 @@ systemd, packages, the `dbus` and `ssh` units, the Python bindings, `NET_ADMIN`)
- `<version>` is semver (`MAJOR.MINOR.PATCH`), independent of the Collection's version. A published
version is never moved or rebuilt, so one digest belongs to exactly one version. `latest` is the
newest version and is for looking, not for pinning.
- Pin `molecule-ubuntu2604:<version>@sha256:<digest>`; the digest is what is enforced. Consumers here:
- Pin `molecule-ubuntu2604:<version>@sha256:<digest>`; the digest decides what is pulled. Consumers here:
`.gitea/workflows/molecule.yml`.
- Renovate is configured to move the pin to a new version after the image is built on `main` (the rule is in
`renovate.json`; the first pin of a brand-new image is made by hand).
@@ -67,7 +67,7 @@ systemd, packages, the `dbus` and `ssh` units, the Python bindings, `NET_ADMIN`)
`.gitea/workflows/image.yml` builds it with kaniko. The workflow runs on pushes to `main` that touch `images/**`,
`requirements-dev.txt`, `requirements-dev.lock`, `requirements.yml`, `.pre-commit-config.yaml` or the workflow itself, never on a pull request, and builds an
image only when its `version:` in the workflow's matrix is not yet published. A change under
`images/molecule-ubuntu2604/` therefore needs a new `version:` (Lint enforces it) and the merge builds the image. The
`images/molecule-ubuntu2604/` therefore needs a new `version:` (Lint checks it) and the merge builds the image. The
Ubuntu release is fixed by the name: a new Ubuntu release is a new image (`molecule-ubuntuNNNN`), and the roles
are tested on every release the hosts run or are moving to.
+2 -1
View File
@@ -1,7 +1,7 @@
---
namespace: mortis
name: kamino
version: 1.10.2
version: 1.11.0
readme: README.md
authors:
- Defame1297
@@ -31,6 +31,7 @@ build_ignore:
- apm.yml
- apm.lock.yaml
- apm_modules
- .apm-local
- .claude
- .gitea
- .gitignore
+1 -1
View File
@@ -25,7 +25,7 @@
# fails without host keys, so they cannot be removed; image scanners will flag them.
# They are throwaway keys of a test target that is never exposed.
# ubuntu:24.04 index digest as of 2026-10-24 (24.04.5).
FROM ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8
FROM ubuntu:24.04@sha256:9c7f200c07e3d4a03e7249d2c16bf66a51120fb876aa2242cf31451412543289
LABEL org.opencontainers.image.title="molecule-ubuntu2404" \
org.opencontainers.image.description="Disposable Ubuntu 24.04 test target for the molecule scenarios of the mortis.kamino Ansible Collection. systemd runs as PID 1 with D-Bus, sudo, python3 and the packages the roles manage (iptables, ufw, fail2ban, openssh-server) preinstalled, so a converge makes no network calls. Start it as a molecule platform (usage label); it carries throwaway SSH host keys and is a test target only, never to be exposed." \
+1 -1
View File
@@ -106,7 +106,7 @@
"automerge": true
},
{
"description": "The Renovate job container of renovate.yml runs with the job token: hand-bumped, never by the bot (the bot-diff gate would refuse a change to that file anyway).",
"description": "The Renovate job container of renovate.yml runs with the job token: hand-bumped, never by the bot (the bot-diff check would refuse a change to that file anyway).",
"matchFileNames": [
".gitea/workflows/renovate.yml"
],
+1 -1
View File
@@ -18,7 +18,7 @@ names a check that does not exist yet and its backlog issue.
*Why:* a consumer finds the same thing in the same place. *Held:* review.
- **Complexity.** A task file stays within ansible-lint's `complexity` limit, `max_tasks` 100
(40 once ansible-lint accepts the key). *Why:* a long task file is hard to review. *Held:*
review until the Lint job enables and gates `complexity` (#138).
review until the Lint job enables `complexity` and fails on it (#138).
- **Roadmap.** The pull request that adds a role removes it from the README "Roadmap" list, and
the section goes when the list is empty. *Why:* the list is useful only if true. *Held:* review.
+115
View File
@@ -0,0 +1,115 @@
# cloudflared
Installs cloudflared as a systemd service for a locally managed Cloudflare Tunnel. The role checks that the tunnel exists, manages its proxied DNS CNAMEs through the Cloudflare API, renders `config.yml` from a hostname-to-service list, and optionally updates or removes everything. A separate `mint` entry point creates the tunnel. 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 downloads the `cloudflared-linux-amd64` binary only, so other architectures are unsupported, and it needs `systemd`. The tasks that call the Cloudflare API run on the controller (`delegate_to: localhost`) and need the `community.general` collection (`cloudflare_dns`) there; the `mint` entry point also needs the `openssl` command on the controller. The target needs outbound access to github.com and to Cloudflare's edge; the role defines no firewall rules because the daemon only connects outbound.
## Requirements and run order
- Use it by its fully qualified name, `mortis.kamino.cloudflared`.
- Before the first run: set `cloudflared_account_id` and `cloudflared_tunnel_api_token` (vaulted), and, while `cloudflared_manage_dns` is true, `cloudflared_zone_name`; list the routed hostnames in `cloudflared_ingress`. The token needs Cloudflare Tunnel Edit, DNS Edit and Zone Read; do not reuse a token that serves another purpose (for example an ACME DNS-challenge token).
- First run versus later runs: `cloudflared_tunnel_id` and `cloudflared_credentials_json` have no role default and the main entry point never creates them. Validation asserts both are defined and non-empty before anything changes and fails with the mint instructions otherwise. On a new host run the `mint` entry point first, persist its output facts into inventory under these two names, then run the role (see Entry points).
- The secrets are not `required` in the argument spec, on purpose, as an exception to the rule that a secret is a required input: argument validation would stop a first run with a generic "missing required arguments" message, where the role's own assert names the mint entry point that creates the tunnel, and the `mint` entry point must run while `cloudflared_tunnel_id` is still undefined. All four (`cloudflared_tunnel_id`, `cloudflared_credentials_json`, `cloudflared_account_id`, `cloudflared_tunnel_api_token`) have no default and are asserted non-empty before any change.
- An origin behind the tunnel on the same host (for example a reverse proxy on `https://127.0.0.1:443`) must be serving before cloudflared can reach it; the role does not check it.
- Updates: the update path stages the verified binary and hands the swap to `mortis.kamino._binary_update`, an internal role of this Collection.
- `cloudflared_version` is asserted at role start to be a `YYYY.M.P` release tag, with no leading `v`, and `cloudflared_sha256_amd64` to be 64 hex digits. Pin both in inventory to move the daemon independently of Collection releases; the role defaults change only with a release.
## Role variables
| Variable | Default | Description |
|---|---|---|
| `cloudflared_ingress` | `[]` | List of `hostname`, `service` and optional `originRequest`. A catch-all `http_status:404` rule is appended. |
| `cloudflared_tunnel_id` | none (asserted) | Vaulted tunnel id, from the `mint` entry point. |
| `cloudflared_credentials_json` | none (asserted) | Vaulted tunnel credentials JSON, written to `<config_dir>/<tunnel id>.json`, mode 0600. |
| `cloudflared_account_id` | none (asserted) | Account id for the tunnel API. |
| `cloudflared_tunnel_api_token` | none (asserted) | API token, `no_log`. |
| `cloudflared_manage_dns` | `true` | Manage the proxied CNAMEs of the ingress hostnames; false makes no DNS call. |
| `cloudflared_zone_name` | `""` (asserted while `cloudflared_manage_dns`) | Zone of the ingress hostnames. |
| `cloudflared_allow_dns_overwrite` | `[]` | Hostnames whose existing non-tunnel DNS record may be overwritten. |
| `cloudflared_api_base_url` | `https://api.cloudflare.com/client/v4` | Cloudflare API base URL for the role's `uri` calls, no trailing slash. |
| `cloudflared_tunnel_name` | `{{ inventory_hostname }}-tunnel` | Tunnel name used by the `mint` entry point. |
| `cloudflared_version` | pinned in `defaults/main.yml` | Release tag, `YYYY.M.P`. |
| `cloudflared_sha256_amd64` | pinned | SHA-256 of the amd64 binary. Update with the version. |
| `cloudflared_download_url` | github.com release URL built from the version | Binary download URL. |
| `cloudflared_update` | `true` | Run the update tasks when the installed version differs: download and verify to a staging path, then `mortis.kamino._binary_update` swaps it in with rollback. |
| `cloudflared_remove` | `false` | Stop and disable the service, remove the unit and the binary. The role ends there. |
| `cloudflared_remove_data` | `false` | With `cloudflared_remove`, also remove the config directory and the user, and delete the tunnel (and, with `cloudflared_manage_dns`, its DNS records) on Cloudflare. |
| `cloudflared_user`, `cloudflared_group` | `cloudflared` | Service account. |
| `cloudflared_install_dir` | `/usr/local/bin` | Binary location. |
| `cloudflared_config_dir` | `/etc/cloudflared` | Configuration and credentials directory. |
| `cloudflared_service_unit` | `/etc/systemd/system/cloudflared.service` | Unit file path. |
| `cloudflared_mint_confirm` | `false` | Opt-in for the `mint` entry point. |
## Entry points
- `main`: install, configure, update or remove cloudflared, as above.
- `mint` (`tasks_from: mint`): creates the tunnel. Run it by hand from an operator play, never from CI:
```yaml
- name: Mint the Cloudflare Tunnel
hosts: tunnel_hosts
tasks:
- name: Mint
ansible.builtin.include_role:
name: mortis.kamino.cloudflared
tasks_from: mint
# Then vault-encrypt cloudflared_minted_tunnel_id and cloudflared_minted_credentials_json
# (when defined) into inventory as cloudflared_tunnel_id and cloudflared_credentials_json.
```
Run it with `-e cloudflared_mint_confirm=true`.
- Guards: `cloudflared_mint_confirm` must be true, and the entry point fails when `GITHUB_ACTIONS`, `GITEA_ACTIONS` or `CI` is set in the controller environment. This guards against accidents; it is not a security boundary.
- When `cloudflared_tunnel_id` is already defined and non-empty (undefined, null and `""` count as missing) it only reports that and creates nothing, so a re-run is safe. It creates nothing in check mode.
- Otherwise it asserts `cloudflared_account_id`, `cloudflared_tunnel_api_token` and `cloudflared_tunnel_name`, generates the tunnel secret in memory with `openssl rand -base64 32` on the controller, creates the tunnel through the API with `config_src: local` and registers `cloudflared_minted_tunnel_id` and `cloudflared_minted_credentials_json` as `no_log` facts. The secret and the API response are cleared from the host's variables afterwards.
- Persisting the facts is the calling play's job. The credentials are shown nowhere else, so a mint whose result is not persisted must be repeated, and leaves an orphan tunnel on Cloudflare to delete by hand.
## Variables set by the role
Only by the `mint` entry point, and only when a tunnel was created; `no_log`, not cacheable:
- `cloudflared_minted_tunnel_id` (string): the new tunnel's id.
- `cloudflared_minted_credentials_json` (string, JSON text): the tunnel credentials file content, including the tunnel secret.
## Tags
`cloudflared` (everything), `prereqs`, `install`, `configure`, `health`, `update`, `remove`, `mint` (carried by the mint entry point's tasks, but not selectable on its own: its guards are tagged `cloudflared, always`, so select a mint play with `--tags cloudflared`). The input asserts and the `prereqs` tasks are also tagged `always`. The download (`tasks/download.yml`, shared by install and update) is tagged `install` and `update`, so `--tags update` alone reaches it.
## Example play
```yaml
- name: Run a Cloudflare Tunnel
hosts: tunnel_hosts
roles:
- role: mortis.kamino.cloudflared
vars:
cloudflared_zone_name: example.com
cloudflared_ingress:
- hostname: git.example.com
service: https://127.0.0.1:443
originRequest:
originServerName: git.example.com
```
`cloudflared_account_id`, `cloudflared_tunnel_api_token`, `cloudflared_tunnel_id` and `cloudflared_credentials_json` come from vaulted inventory variables.
Remove with `-e "cloudflared_remove=true cloudflared_remove_data=true"`; only `cloudflared_remove_data` touches Cloudflare.
## Tests
The `default` molecule scenario runs without Cloudflare: a stub cloudflared binary stands in for the daemon, the downloads come from local `file://` URLs, and a stub of the Cloudflare API on the controller's loopback (`molecule/default/files/cloudflare_api_stub.py`, reached through `cloudflared_api_base_url`) answers the tunnel, zone and DNS record calls. It covers the converge with `cloudflared_manage_dns` false and an update through `_binary_update` (and its idempotence), the rendered `config.yml`, credentials file and unit, a stale credentials file, a failed checksum that leaves the daemon running, the input asserts, the deleted-tunnel and DNS guards, the `mint` entry point (confirm guard, CI refusal, no-op, check mode and a mint against the stub, run as child processes) and the remove path. The `community.general.cloudflare_dns` calls, which cannot be pointed at the stub, are not covered: creating, pruning and deleting records.
## Notes
- Idempotent: yes.
- The role is not a state selector. `main.yml` always runs validation, prerequisites and configure unless `cloudflared_remove` is true; the binary install only when it is absent; the update only when the installed version differs; remove only when `cloudflared_remove` is true, and then every later task is skipped.
- Secrets: the tasks that create the secrets, the `uri` calls that put the token in the Authorization header, the `cloudflare_dns` calls and the credentials file write use `no_log` (the credentials write also sets `diff: false`). A failure of those tasks therefore shows only as "censored": to debug a failed DNS change, check the Cloudflare audit log or set `no_log: false` on a throwaway run against a non-secret zone. The tunnel id itself is not masked: it shows in `config.yml` diffs, DNS record values and failure messages.
- Safety guards: the role fails if the tunnel no longer exists on Cloudflare (retrying a 404 three times first, then failing with the re-mint instructions), if the tunnel lookup fails otherwise (with its HTTP status), if the zone is not found, or if an existing record for an ingress hostname does not point at some `cfargotunnel.com` tunnel and the hostname is not in `cloudflared_allow_dns_overwrite`. A record that already points at a tunnel, including a deleted one, is repointed without an allowlist entry.
- Pruning: CNAMEs pointing at this tunnel whose name is not in `cloudflared_ingress` are deleted. The lookup is filtered by the tunnel's `cfargotunnel.com` target, so other records in the zone are not touched.
- Re-mint after a tunnel was deleted out of band: remove the stale `cloudflared_tunnel_id` and `cloudflared_credentials_json` from inventory, run the `mint` entry point and persist its output.
- Stale credentials: files named `<uuid>.json` in the config directory other than the current tunnel's are removed.
- The `Restart cloudflared` handler runs when `config.yml` or the credentials file changes. cloudflared's own ingress check (`ingress validate`) runs after `config.yml` is written.
- Update: the version is compared as `YYYY.M.P` against `cloudflared --version`. The new binary is downloaded and checksum-verified into `cloudflared.new` before the service is stopped, so a failed download leaves it running; a configured hash that equals the installed binary's is refused with a message, since it means the hash was not bumped with the version. A binary that reports no version is replaced too.
- The play fails when `cloudflared` is not `active` after start.
+48
View File
@@ -0,0 +1,48 @@
---
cloudflared_update: true
cloudflared_remove_data: false
cloudflared_remove: false
# cloudflared publishes no checksum file: the hash is the sha256 of the cloudflared-linux-amd64
# release asset, and it moves together with the version. Pin both in inventory to move the
# daemon independently of Collection releases.
cloudflared_version: "2026.11.1"
cloudflared_sha256_amd64: "97bb3b02d23a5980fc9c15a1a270e692da1923f103f920d5b16d4931d5ab55e7"
cloudflared_download_url: "https://github.com/cloudflare/cloudflared/releases/download/{{ cloudflared_version }}/cloudflared-linux-amd64"
cloudflared_user: "cloudflared"
cloudflared_group: "cloudflared"
cloudflared_install_dir: "/usr/local/bin"
cloudflared_config_dir: "/etc/cloudflared"
cloudflared_service_unit: "/etc/systemd/system/cloudflared.service"
cloudflared_api_base_url: "https://api.cloudflare.com/client/v4"
cloudflared_tunnel_name: "{{ inventory_hostname }}-tunnel"
# Set false when the tunnel's DNS records are managed elsewhere: the role then makes no DNS
# call and needs no zone.
cloudflared_manage_dns: true
# Every zone differs, so there is no useful default; asserted non-empty while
# cloudflared_manage_dns is true.
cloudflared_zone_name: ""
# Hostnames routed through the tunnel; each gets a proxied CNAME while cloudflared_manage_dns
# is true. A catch-all http_status:404 rule is always appended.
cloudflared_ingress: []
# The role owns no firewall rule: the daemon only connects outbound to Cloudflare's edge.
# No default for cloudflared_tunnel_id, cloudflared_credentials_json, cloudflared_account_id or
# cloudflared_tunnel_api_token: they are secrets. The main entry point asserts them and, for the
# tunnel, names the mint entry point that creates it; the mint entry point creates a tunnel only
# while cloudflared_tunnel_id is undefined, null or empty.
# Hostnames from cloudflared_ingress whose existing DNS record may be overwritten although it does
# not point at a cfargotunnel.com tunnel. Without an entry the play fails instead. Per hostname, so
# unblocking one does not authorise overwriting the others.
cloudflared_allow_dns_overwrite: []
# Opt-in for the mint entry point.
cloudflared_mint_confirm: false
+6
View File
@@ -0,0 +1,6 @@
---
- name: Restart cloudflared
become: true
ansible.builtin.systemd:
name: cloudflared
state: restarted
+227
View File
@@ -0,0 +1,227 @@
---
argument_specs:
main:
short_description: Install and run cloudflared for a locally managed Cloudflare Tunnel, with its DNS records
description:
- >-
Validates the inputs, then either removes cloudflared (C(cloudflared_remove), which ends the role) or creates
the C(cloudflared) system user, group and configuration directory, downloads and checksum-verifies the pinned
binary when it is missing and runs the configure tasks. Optionally updates the binary
(C(cloudflared_update)) with rollback through the internal C(mortis.kamino._binary_update) role.
- >-
This entry point never creates the tunnel (see the C(mint) entry point). Validation asserts that
C(cloudflared_tunnel_id) and C(cloudflared_credentials_json) are defined and non-empty, and fails with the
mint instructions otherwise. The configure tasks then check, from the controller, that the tunnel still
exists, and, with C(cloudflared_manage_dns), point a proxied CNAME for every C(cloudflared_ingress) hostname
at the tunnel and prune CNAMEs that point at this tunnel but are no longer listed. They write C(config.yml)
and the credentials file, remove stale credentials files, write the systemd unit and start the service.
- >-
The four secrets (C(cloudflared_tunnel_id), C(cloudflared_credentials_json), C(cloudflared_account_id),
C(cloudflared_tunnel_api_token)) are deliberately not C(required) in this spec: argument validation would
stop a first run with a generic message, where the role's own assert names the mint entry point that
creates the tunnel, and the mint entry point must run while the tunnel variables are still undefined.
They have no role default and are asserted non-empty before any change.
options:
cloudflared_remove:
type: bool
default: false
description:
- >-
When true the service is stopped and disabled and the unit file and the binary are removed. The role ends
there: nothing is installed or configured in the same run.
cloudflared_remove_data:
type: bool
default: false
description:
- >-
Only read while C(cloudflared_remove) is true. When true C(cloudflared_config_dir) and the
C(cloudflared) user are removed and, when C(cloudflared_tunnel_id) is non-empty, the tunnel is deleted on
Cloudflare, together with the DNS records of every C(cloudflared_ingress) hostname while
C(cloudflared_manage_dns) is true. Destructive on the Cloudflare side.
cloudflared_update:
type: bool
default: true
description:
- >-
When true the update tasks run after configuration. The installed version is compared with
C(cloudflared_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 daemon running.
cloudflared_version:
type: str
description:
- >-
cloudflared release tag, for example C(2026.11.1). The role default is a pinned tag, see
C(defaults/main.yml); pin it in inventory, together with C(cloudflared_sha256_amd64), to move the daemon
independently of Collection releases.
- Asserted at role start to be C(YYYY.M.P) digits only, with no leading C(v).
cloudflared_sha256_amd64:
type: str
description:
- >-
SHA-256 of the C(cloudflared-linux-amd64) binary of C(cloudflared_version). Upstream publishes no checksum
file, so it must be updated together with the version. The role default is the pinned value. Asserted at
role start to be 64 hex digits.
cloudflared_download_url:
type: raw
description:
- >-
Download URL of the binary. The role default is a Jinja expression built from C(cloudflared_version)
for C(cloudflared-linux-amd64) on github.com.
cloudflared_user:
type: str
default: cloudflared
description:
- System user that owns the configuration and runs the service.
cloudflared_group:
type: str
default: cloudflared
description:
- System group that owns the configuration and runs the service.
cloudflared_install_dir:
type: str
default: /usr/local/bin
description:
- Directory that receives the C(cloudflared) binary.
cloudflared_config_dir:
type: str
default: /etc/cloudflared
description:
- Directory for C(config.yml) and the tunnel credentials file C(<tunnel id>.json), mode 0750.
cloudflared_service_unit:
type: str
default: /etc/systemd/system/cloudflared.service
description:
- Path of the systemd unit file.
cloudflared_api_base_url:
type: str
default: https://api.cloudflare.com/client/v4
description:
- >-
Base URL of the Cloudflare API, without a trailing slash. Prefixed to every request the role makes with
C(ansible.builtin.uri) (tunnel lookup and delete, zone lookup and DNS record listing). The
C(community.general.cloudflare_dns) tasks always use the public endpoint.
cloudflared_tunnel_name:
type: raw
description:
- >-
Name given to the tunnel when it is created. The role default is the Jinja expression
C(<inventory_hostname>-tunnel). Only used by the C(mint) entry point.
cloudflared_tunnel_id:
type: raw
no_log: true
description:
- >-
Tunnel id, supplied as a vaulted variable from the output of the C(mint) entry point. No role default and
not C(required) in this spec, on purpose: the C(mint) entry point creates the tunnel only while this is
undefined, null or empty, and this entry point asserts it non-empty with the mint instructions.
cloudflared_credentials_json:
type: raw
no_log: true
description:
- >-
Tunnel credentials JSON as a vaulted string, written to C(<cloudflared_config_dir>/<tunnel id>.json) with
mode 0600. No role default and not C(required), for the same reason as C(cloudflared_tunnel_id);
asserted non-empty.
cloudflared_manage_dns:
type: bool
default: true
description:
- >-
When true the role looks up C(cloudflared_zone_name), points a proxied CNAME for every
C(cloudflared_ingress) hostname at the tunnel, prunes CNAMEs that point at this tunnel and are no longer
listed, and deletes the records on a removal with C(cloudflared_remove_data). When false it makes no DNS
call and C(cloudflared_zone_name) is not read: the records are managed elsewhere.
cloudflared_zone_name:
type: str
default: ""
description:
- >-
DNS zone of the C(cloudflared_ingress) hostnames. Asserted non-empty while C(cloudflared_manage_dns) is
true. The play fails when no zone of this name exists.
cloudflared_ingress:
type: list
elements: dict
default: []
description:
- >-
Routed hostnames. Each item is a mapping with C(hostname), C(service) and optionally C(originRequest)
(rendered as YAML). A catch-all C(http_status:404) rule is appended. With C(cloudflared_manage_dns) a
CNAME is created for every C(hostname), and CNAMEs that point at this tunnel and are not listed are
deleted.
cloudflared_allow_dns_overwrite:
type: list
elements: str
default: []
description:
- >-
Hostnames from C(cloudflared_ingress) whose existing DNS record may be overwritten although it does not
point at a C(cfargotunnel.com) tunnel. Without an entry the play fails instead of replacing the record.
Add a hostname only after confirming the record should be replaced.
cloudflared_account_id:
type: raw
description:
- >-
Cloudflare account id used in the tunnel API URLs. Read by the tunnel existence check and the removal.
No role default and not C(required) (see the secrets note above); asserted non-empty.
cloudflared_tunnel_api_token:
type: raw
no_log: true
description:
- >-
Cloudflare API token with Cloudflare Tunnel Edit, DNS Edit and Zone Read permissions, sent as a Bearer
header and as C(api_token) of C(community.general.cloudflare_dns). A secret: supply it from a vaulted
variable. No role default and not C(required) (see the secrets note above); asserted non-empty.
mint:
short_description: Create the Cloudflare Tunnel and register its secrets as facts (opt-in, operator only)
description:
- >-
Opt-in entry point (C(tasks_from=mint)), run by hand from an operator play, never from CI. Requires
C(cloudflared_mint_confirm=true) and refuses to run when C(GITHUB_ACTIONS), C(GITEA_ACTIONS) or C(CI) is set
on the controller. Does nothing but report when C(cloudflared_tunnel_id) is already defined and non-empty.
- >-
Otherwise, and never in check mode, it generates the tunnel secret in memory (C(openssl rand) on the
controller), creates the tunnel through the Cloudflare API from the controller and registers
C(cloudflared_minted_tunnel_id) and C(cloudflared_minted_credentials_json) (JSON text) as C(no_log) facts.
They are not cacheable, never printed and only defined when a tunnel was created. The role writes no file and
runs no vault command: persisting the facts, for example vault-encrypted into inventory as
C(cloudflared_tunnel_id) and C(cloudflared_credentials_json), is the calling play's job. Cloudflare shows the
credentials once.
- >-
C(cloudflared_account_id) and C(cloudflared_tunnel_api_token) are not C(required) in this spec, as in the
C(main) entry point; they are asserted non-empty before a tunnel is created.
options:
cloudflared_mint_confirm:
type: bool
default: false
description:
- Must be true, otherwise the entry point fails. Pass it as C(-e cloudflared_mint_confirm=true).
cloudflared_api_base_url:
type: str
default: https://api.cloudflare.com/client/v4
description:
- Base URL of the Cloudflare API, without a trailing slash.
cloudflared_tunnel_name:
type: raw
description:
- >-
Name given to the tunnel. The role default is the Jinja expression C(<inventory_hostname>-tunnel).
cloudflared_account_id:
type: raw
description:
- Cloudflare account id used in the tunnel API URL. No role default; asserted non-empty before a mint.
cloudflared_tunnel_api_token:
type: raw
no_log: true
description:
- >-
Cloudflare API token with Cloudflare Tunnel Edit permission, from a vaulted variable. No role default;
asserted non-empty before a mint.
cloudflared_tunnel_id:
type: raw
no_log: true
description:
- >-
Existing tunnel id. When defined and non-empty nothing is minted (undefined, null and the empty string
count as missing). No role default.
+18
View File
@@ -0,0 +1,18 @@
---
galaxy_info:
role_name: cloudflared
namespace: mortis
author: Defame1297
license: GPL-3.0-or-later
description: Install, update and remove cloudflared for a locally managed Cloudflare Tunnel, with its DNS records, and mint the tunnel on request.
min_ansible_version: "2.19"
platforms:
- name: Ubuntu
versions:
- noble
galaxy_tags:
- cloudflared
- cloudflare
- tunnel
- systemd
dependencies: []
@@ -0,0 +1,38 @@
---
# Stops the Cloudflare API stub that prepare.yml started on the controller. Also run before
# create, when there is nothing to stop yet. The pid is only signalled while it still belongs
# to the stub, so a reused pid is never killed.
- name: Cleanup
hosts: localhost
connection: local
gather_facts: false
vars:
cloudflared_test_stub_dir: "{{ lookup('ansible.builtin.env', 'MOLECULE_EPHEMERAL_DIRECTORY') }}/cloudflare-stub"
tasks:
- name: Read the pid of the stub
ansible.builtin.slurp:
src: "{{ cloudflared_test_stub_dir }}/pid"
register: cloudflared_test_stub_pid
failed_when: false
- name: Read the command line of that pid
ansible.builtin.slurp:
src: "/proc/{{ cloudflared_test_stub_pid.content | b64decode | trim }}/cmdline"
register: cloudflared_test_stub_cmdline
# It may have ended at its lifetime already.
failed_when: false
when: cloudflared_test_stub_pid.content is defined
- name: Stop the stub
ansible.builtin.command:
argv: [kill, "{{ cloudflared_test_stub_pid.content | b64decode | trim }}"]
failed_when: false
changed_when: true
when:
- cloudflared_test_stub_cmdline.content is defined
- "'cloudflare_api_stub.py' in (cloudflared_test_stub_cmdline.content | b64decode)"
- name: Remove the pid file
ansible.builtin.file:
path: "{{ cloudflared_test_stub_dir }}/pid"
state: absent
@@ -0,0 +1,9 @@
---
# Role variables come from the inventory group_vars in molecule.yml. The first run updates the
# stub binary from 2026.1.0 to 2026.2.0 through mortis.kamino._binary_update; the idempotence run
# finds 2026.2.0 and changes nothing.
- name: Converge
hosts: all
gather_facts: false
roles:
- role: mortis.kamino.cloudflared
@@ -0,0 +1,184 @@
"""Stub of the Cloudflare API calls of the cloudflared role, for its molecule scenario.
Listens on 127.0.0.1 on a free port, writes the port to <state-dir>/port and its pid to
<state-dir>/pid, and appends one JSON line per request (method, path, status; never a secret)
to <state-dir>/requests.log. Exits by itself after --lifetime seconds, so a cancelled run
leaves nothing running for long.
"""
import argparse
import base64
import binascii
import json
import os
import re
import threading
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit
PREFIX = "/client/v4"
TOKEN = "molecule-not-a-token"
ACCOUNT = "molecule-account"
ZONE_NAME = "example.test"
ZONE_ID = "molecule-zone"
# Tunnel id -> deleted_at (None while the tunnel exists).
TUNNELS = {
"6f1a6e2c-0000-4000-8000-000000000001": None,
"6f1a6e2c-0000-4000-8000-000000000002": "2026-01-01T00:00:00Z",
}
RECORDS = [
{"name": "taken.example.test", "type": "A", "content": "192.0.2.10"},
{
"name": "moved.example.test",
"type": "CNAME",
"content": "6f1a6e2c-0000-4000-8000-000000000009.cfargotunnel.com",
},
]
TUNNEL_PATH = re.compile(r"^/accounts/([^/]+)/cfd_tunnel(?:/([^/]+))?$")
RECORDS_PATH = re.compile(r"^/zones/([^/]+)/dns_records$")
LOCK = threading.Lock()
class Handler(BaseHTTPRequestHandler):
state_dir = "."
# Quiet: the requests go to requests.log instead of stderr.
def log_message(self, *args):
pass
def _send(self, status, result=None, result_info=None):
reply = {"success": status == 200, "errors": [], "result": result}
if result_info is not None:
reply["result_info"] = result_info
body = json.dumps(reply).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
with (
LOCK,
open(
os.path.join(self.state_dir, "requests.log"), "a", encoding="utf-8"
) as log,
):
log.write(
json.dumps(
{"method": self.command, "path": self.path, "status": status}
)
+ "\n"
)
def _route(self):
if self.headers.get("Authorization") != f"Bearer {TOKEN}":
return self._send(403)
url = urlsplit(self.path)
if not url.path.startswith(PREFIX):
return self._send(404)
path = url.path[len(PREFIX) :]
query = {key: values[0] for key, values in parse_qs(url.query).items()}
match = TUNNEL_PATH.match(path)
if match and match.group(1) == ACCOUNT:
return self._tunnel(match.group(2))
match = RECORDS_PATH.match(path)
if self.command == "GET" and match and match.group(1) == ZONE_ID:
return self._records(query)
if self.command == "GET" and path == "/zones":
zones = (
[{"id": ZONE_ID, "name": ZONE_NAME}]
if query.get("name") == ZONE_NAME
else []
)
return self._send(200, zones)
return self._send(404)
# Filters by name (case-insensitive, as DNS names are), type and content, and pages.
def _records(self, query):
records = [
r
for r in RECORDS
if ("name" not in query or r["name"].lower() == query["name"].lower())
and all(r[k] == query[k] for k in ("type", "content") if k in query)
]
per_page = int(query.get("per_page", "100"))
page = int(query.get("page", "1"))
total_pages = max(1, -(-len(records) // per_page))
chunk = records[(page - 1) * per_page : page * per_page]
info = {
"page": page,
"per_page": per_page,
"total_count": len(records),
"total_pages": total_pages,
}
return self._send(200, chunk, info)
def _tunnel(self, tunnel_id):
if tunnel_id is None and self.command == "POST":
return self._create()
if tunnel_id not in TUNNELS:
return self._send(404)
if self.command == "GET":
return self._send(200, {"id": tunnel_id, "deleted_at": TUNNELS[tunnel_id]})
if self.command == "DELETE":
TUNNELS[tunnel_id] = "2026-01-01T00:00:00Z"
return self._send(200, {"id": tunnel_id})
return self._send(405)
# Accepts only what the real API needs for a locally managed tunnel: a name, config_src
# local and a base64 secret of at least 32 bytes.
def _create(self):
try:
body = json.loads(
self.rfile.read(int(self.headers.get("Content-Length", "0")))
)
secret = base64.b64decode(body["tunnel_secret"], validate=True)
except (ValueError, KeyError, TypeError, binascii.Error):
return self._send(400)
if (
not body.get("name")
or body.get("config_src") != "local"
or len(secret) < 32
):
return self._send(400)
tunnel_id = str(uuid.uuid4())
TUNNELS[tunnel_id] = None
credentials = {
"AccountTag": ACCOUNT,
"TunnelID": tunnel_id,
"TunnelName": body["name"],
"TunnelSecret": body["tunnel_secret"],
}
return self._send(
200,
{"id": tunnel_id, "name": body["name"], "credentials_file": credentials},
)
do_GET = _route
do_POST = _route
do_DELETE = _route
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--state-dir", required=True)
parser.add_argument("--lifetime", type=int, default=1500)
args = parser.parse_args()
os.makedirs(args.state_dir, exist_ok=True)
Handler.state_dir = args.state_dir
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
for name, value in (("pid", os.getpid()), ("port", server.server_address[1])):
tmp = os.path.join(args.state_dir, name + ".tmp")
with open(tmp, "w", encoding="utf-8") as handle:
handle.write(f"{value}\n")
os.replace(tmp, os.path.join(args.state_dir, name))
timer = threading.Timer(args.lifetime, server.shutdown)
timer.daemon = True
timer.start()
server.serve_forever()
if __name__ == "__main__":
main()
@@ -0,0 +1,48 @@
---
# Run by verify.yml in a child ansible-playbook process, because the mint 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. The child uses `-i localhost,` and so does not see the molecule group_vars: verify.yml
# passes the inputs with -e, and cloudflared_test_expect_minted says what to assert afterwards.
- name: Mint with a controlled environment
hosts: localhost
connection: local
gather_facts: false
tasks:
- name: Run the mint entry point
ansible.builtin.include_role:
name: mortis.kamino.cloudflared
tasks_from: mint
vars:
cloudflared_mint_confirm: true
- name: No tunnel fact was registered
ansible.builtin.assert:
that:
- cloudflared_minted_tunnel_id is not defined
- cloudflared_minted_credentials_json is not defined
quiet: true
when: not (cloudflared_test_expect_minted | default(false) | bool)
- name: Parse the minted credentials
ansible.builtin.set_fact:
cloudflared_test_minted: "{{ cloudflared_minted_credentials_json | from_json }}"
no_log: true
when: cloudflared_test_expect_minted | default(false) | bool
# The stub accepted the secret only as base64 of at least 32 bytes; 32 bytes are 44
# characters. The secret and the API response must not stay in the host's variables.
- name: The tunnel facts were registered and the intermediates cleared
ansible.builtin.assert:
that:
- cloudflared_minted_tunnel_id is match('^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')
- cloudflared_test_minted.TunnelID == cloudflared_minted_tunnel_id
- cloudflared_test_minted.AccountTag == cloudflared_account_id
- cloudflared_test_minted.TunnelName == cloudflared_tunnel_name
- cloudflared_test_minted.TunnelSecret | length == 44
- __cloudflared_tunnel_secret == ""
- __cloudflared_tunnel_create == ""
fail_msg: The minted tunnel facts are missing or wrong, or an intermediate was kept
quiet: true
no_log: true
when: cloudflared_test_expect_minted | default(false) | bool
@@ -0,0 +1,87 @@
---
# 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 Cloudflare and no real
# cloudflared: prepare.yml starts a stub of the Cloudflare API on the controller's loopback
# (files/cloudflare_api_stub.py, reached through cloudflared_api_base_url; cleanup.yml stops it)
# and seeds a stub cloudflared binary that reports an older version, so the update downloads its
# new stub from local file:// URLs. The scenario downloads nothing. cloudflared_manage_dns is
# false here because community.general.cloudflare_dns cannot be pointed at the stub; the DNS
# guards in front of it are run with it true in verify.yml.
# The container runs systemd as PID 1 with a writable cgroup; no privileged mode.
driver:
name: docker
platforms:
- name: cloudflared-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:
# The stub binary; @VERSION@ is replaced per release file. Its hash is the configured
# sha256, so the release files need no checksum file.
cloudflared_test_stub: |
#!/bin/sh
case "$$1" in
--version) echo "cloudflared version @VERSION@ (built 2026-01-01-0000 UTC)" ;;
tunnel)
[ "$$2" = --config ] || { echo "stub cloudflared: expected --config" >&2; exit 2; }
case "$$4" in
ingress) grep -q 'service: http_status:404' "$$3" && { echo "Validating rules from $$3"; exit 0; } ;;
run) [ -r "$$3" ] && exec sleep infinity ;;
esac
echo "stub cloudflared: cannot handle: $$*" >&2; exit 1 ;;
*) echo "stub cloudflared: unexpected arguments: $$*" >&2; exit 2 ;;
esac
cloudflared_test_stub_dir: "{{ lookup('ansible.builtin.env', 'MOLECULE_EPHEMERAL_DIRECTORY') }}/cloudflare-stub"
cloudflared_test_tunnel_id: 6f1a6e2c-0000-4000-8000-000000000001
cloudflared_test_credentials_json: >-
{"AccountTag": "molecule-account", "TunnelID": "6f1a6e2c-0000-4000-8000-000000000001", "TunnelSecret": "bW9sZWN1bGU="}
cloudflared_version: "2026.2.0"
cloudflared_sha256_amd64: "{{ cloudflared_test_stub | replace('@VERSION@', cloudflared_version) | hash('sha256') }}"
cloudflared_download_url: "file:///opt/molecule-download/cloudflared-{{ cloudflared_version }}"
cloudflared_api_base_url: >-
http://127.0.0.1:{{ lookup('ansible.builtin.file', cloudflared_test_stub_dir ~ '/port') }}/client/v4
cloudflared_account_id: molecule-account
cloudflared_tunnel_api_token: molecule-not-a-token
cloudflared_tunnel_id: "{{ cloudflared_test_tunnel_id }}"
cloudflared_credentials_json: "{{ cloudflared_test_credentials_json }}"
cloudflared_manage_dns: false
cloudflared_ingress: "{{ cloudflared_test_ingress }}"
cloudflared_test_ingress:
- hostname: app.example.test
service: https://127.0.0.1:443
originRequest:
originServerName: app.example.test
- hostname: other.example.test
service: http://127.0.0.1:8080
verifier:
name: ansible
scenario:
# molecule's default sequence minus both destroys: the workflow removes the container before the
# run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait.
# After a local run, run `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
@@ -0,0 +1,75 @@
---
# Stand-ins for what the scenario cannot have: the Cloudflare API (a stub on the controller's
# loopback), an installed cloudflared (a stub binary reporting 2026.1.0, so the converge updates
# it), and the release files of two newer versions behind file:// URLs. The configured sha256 is
# the hash of the stub of the requested version, so 2026.2.0 verifies and 2026.3.0 does only when
# a case passes its hash. A stale tunnel credentials file and an unrelated JSON file are seeded
# in the config directory: configure must remove the first and keep the second.
- name: Prepare
hosts: all
gather_facts: false
tasks:
- name: Remove the state of an earlier stub run
delegate_to: localhost
run_once: true
ansible.builtin.file:
path: "{{ cloudflared_test_stub_dir }}"
state: absent
# Runs in the background until cleanup.yml stops it, or until its lifetime, kept below the
# workflow's 30-minute job timeout, runs out.
- name: Start the Cloudflare API stub on the controller
delegate_to: localhost
run_once: true
ansible.builtin.command:
argv:
- "{{ ansible_playbook_python }}"
- -I
- "{{ playbook_dir }}/files/cloudflare_api_stub.py"
- --state-dir
- "{{ cloudflared_test_stub_dir }}"
- --lifetime
- "1500"
async: 1500
poll: 0
changed_when: true
- name: Wait for the stub to listen
delegate_to: localhost
run_once: true
ansible.builtin.wait_for:
path: "{{ cloudflared_test_stub_dir }}/port"
timeout: 30
- name: Create the download and config directories
ansible.builtin.file:
path: "{{ cloudflared_test_dir }}"
state: directory
mode: "0755"
loop: [/opt/molecule-download, /etc/cloudflared]
loop_control:
loop_var: cloudflared_test_dir
- name: Write the installed stub binary and the release files
ansible.builtin.copy:
dest: "{{ cloudflared_test_release.dest }}"
mode: "0755"
content: "{{ cloudflared_test_stub | replace('@VERSION@', cloudflared_test_release.version) }}"
loop:
- {dest: /usr/local/bin/cloudflared, version: 2026.1.0}
- {dest: /opt/molecule-download/cloudflared-2026.2.0, version: 2026.2.0}
- {dest: /opt/molecule-download/cloudflared-2026.3.0, version: 2026.3.0}
loop_control:
loop_var: cloudflared_test_release
label: "{{ cloudflared_test_release.dest }}"
- name: Seed a stale credentials file and an unrelated JSON file
ansible.builtin.copy:
dest: "/etc/cloudflared/{{ cloudflared_test_seed }}"
mode: "0600"
content: "{}\n"
loop:
- 6f1a6e2c-0000-4000-8000-000000000000.json
- notes.json
loop_control:
loop_var: cloudflared_test_seed
@@ -0,0 +1,42 @@
---
# One failing run: runs the main entry point with the inputs of the case and asserts that the
# expected message, not something else, stopped it. Input: cloudflared_test_case (name, vars,
# expect). Task vars cannot come from a template as a whole, so each input a case may change is
# passed with its scenario value as the default.
- name: "Run the role, case {{ cloudflared_test_case.name }}"
block:
- name: "Include the role, case {{ cloudflared_test_case.name }}"
ansible.builtin.include_role:
name: mortis.kamino.cloudflared
vars:
cloudflared_version: "{{ cloudflared_test_case.vars.cloudflared_version | default('2026.2.0') }}"
cloudflared_sha256_amd64: >-
{{ cloudflared_test_case.vars.cloudflared_sha256_amd64
| default(cloudflared_test_stub | replace('@VERSION@', '2026.2.0') | hash('sha256')) }}
cloudflared_tunnel_id: "{{ cloudflared_test_case.vars.cloudflared_tunnel_id | default(cloudflared_test_tunnel_id) }}"
cloudflared_credentials_json: "{{ cloudflared_test_case.vars.cloudflared_credentials_json | default(cloudflared_test_credentials_json) }}"
cloudflared_account_id: "{{ cloudflared_test_case.vars.cloudflared_account_id | default('molecule-account') }}"
cloudflared_tunnel_api_token: "{{ cloudflared_test_case.vars.cloudflared_tunnel_api_token | default('molecule-not-a-token') }}"
cloudflared_manage_dns: "{{ cloudflared_test_case.vars.cloudflared_manage_dns | default(false) }}"
cloudflared_zone_name: "{{ cloudflared_test_case.vars.cloudflared_zone_name | default('') }}"
cloudflared_ingress: "{{ cloudflared_test_case.vars.cloudflared_ingress | default(cloudflared_test_ingress) }}"
cloudflared_user: "{{ cloudflared_test_case.vars.cloudflared_user | default('cloudflared') }}"
cloudflared_install_dir: "{{ cloudflared_test_case.vars.cloudflared_install_dir | default('/usr/local/bin') }}"
cloudflared_config_dir: "{{ cloudflared_test_case.vars.cloudflared_config_dir | default('/etc/cloudflared') }}"
# Only reached when the include returned. The message must not contain the expected
# text, so the rescue below cannot mistake it for the failure under test.
- name: "Fail because the include returned, case {{ cloudflared_test_case.name }}"
ansible.builtin.fail:
msg: The role accepted the input
rescue:
# A failed loop task reports its message per item.
- name: "The expected failure stopped the run, case {{ cloudflared_test_case.name }}"
vars:
cloudflared_test_messages: >-
{{ (ansible_failed_result.msg | default('')) ~ ' '
~ (ansible_failed_result.results | default([]) | map(attribute='msg', default='') | join(' ')) }}
ansible.builtin.assert:
that: cloudflared_test_case.expect in cloudflared_test_messages
fail_msg: "Expected '{{ cloudflared_test_case.expect }}', got: {{ cloudflared_test_messages }}"
quiet: true
@@ -0,0 +1,407 @@
---
- name: Verify the converged daemon
hosts: all
gather_facts: false
tasks:
- name: Read config.yml
ansible.builtin.slurp:
src: /etc/cloudflared/config.yml
register: cloudflared_test_config_raw
- name: Parse config.yml
ansible.builtin.set_fact:
cloudflared_test_config: "{{ cloudflared_test_config_raw.content | b64decode | from_yaml }}"
- name: Config.yml routes the ingress hostnames and ends with the catch-all
ansible.builtin.assert:
that:
- cloudflared_test_config.tunnel == cloudflared_test_tunnel_id
- cloudflared_test_config['credentials-file'] == '/etc/cloudflared/' ~ cloudflared_test_tunnel_id ~ '.json'
- cloudflared_test_config.ingress | length == 3
- cloudflared_test_config.ingress[0].hostname == 'app.example.test'
- cloudflared_test_config.ingress[0].service == 'https://127.0.0.1:443'
- "cloudflared_test_config.ingress[0].originRequest == {'originServerName': 'app.example.test'}"
- cloudflared_test_config.ingress[1].hostname == 'other.example.test'
- cloudflared_test_config.ingress[1].originRequest is not defined
- "cloudflared_test_config.ingress[2] == {'service': 'http_status:404'}"
quiet: true
- name: Read the credentials file
ansible.builtin.slurp:
src: "/etc/cloudflared/{{ cloudflared_test_tunnel_id }}.json"
register: cloudflared_test_credentials
no_log: true
- name: Stat the configuration, the seeded files and what an update leaves behind
ansible.builtin.stat:
path: "{{ cloudflared_test_path }}"
loop:
- /etc/cloudflared/config.yml
- "/etc/cloudflared/{{ cloudflared_test_tunnel_id }}.json"
- /etc/cloudflared/6f1a6e2c-0000-4000-8000-000000000000.json
- /etc/cloudflared/notes.json
- /usr/local/bin/cloudflared.new
- /usr/local/bin/cloudflared.bak
loop_control:
loop_var: cloudflared_test_path
register: cloudflared_test_files
- name: The files are private to the daemon, the stale credentials are gone and the update left nothing behind
ansible.builtin.assert:
that:
- cloudflared_test_files.results[0].stat.mode == '0640'
- cloudflared_test_files.results[0].stat.pw_name == 'cloudflared'
- cloudflared_test_files.results[1].stat.mode == '0600'
- cloudflared_test_files.results[1].stat.pw_name == 'cloudflared'
- (cloudflared_test_credentials.content | b64decode | from_json) == (cloudflared_test_credentials_json | from_json)
- not cloudflared_test_files.results[2].stat.exists
- cloudflared_test_files.results[3].stat.exists
- not cloudflared_test_files.results[4].stat.exists
- not cloudflared_test_files.results[5].stat.exists
quiet: true
- name: Ask the installed binary for its version
ansible.builtin.command:
argv: [/usr/local/bin/cloudflared, --version]
register: cloudflared_test_version
changed_when: false
- name: Ask systemd about the daemon
ansible.builtin.systemd:
name: cloudflared
register: cloudflared_test_unit
# The stub's `run` only keeps running when it can read the config it was given, so an active
# unit shows the service user reads config.yml.
- name: Stat the daemon's process
ansible.builtin.stat:
path: "/proc/{{ cloudflared_test_unit.status.MainPID }}"
register: cloudflared_test_process
- name: The updated daemon runs as the service user with the rendered config
ansible.builtin.assert:
that:
- "'2026.2.0' in cloudflared_test_version.stdout"
- cloudflared_test_unit.status.ActiveState == 'active'
- cloudflared_test_unit.status.UnitFileState == 'enabled'
- cloudflared_test_unit.status.ExecStart is search('--config /etc/cloudflared/config.yml run')
- cloudflared_test_process.stat.exists
- cloudflared_test_process.stat.pw_name == 'cloudflared'
quiet: true
# cloudflared_manage_dns is false in the converge: the tunnel was checked, no DNS call made.
- name: Read the requests the API stub received
delegate_to: localhost
ansible.builtin.slurp:
src: "{{ cloudflared_test_stub_dir }}/requests.log"
register: cloudflared_test_requests
- name: The converge checked the tunnel and made no DNS call
vars:
cloudflared_test_log: "{{ cloudflared_test_requests.content | b64decode }}"
ansible.builtin.assert:
that:
- >-
cloudflared_test_log is search('"GET", "path": "/client/v4/accounts/molecule-account/cfd_tunnel/'
~ cloudflared_test_tunnel_id ~ '"')
- cloudflared_test_log is not search('/zones')
quiet: true
# Every case fails, before any change or at a guard ahead of the first change; the last play
# checks that the daemon was left as the converge set it up.
- name: Verify the failure paths
hosts: all
gather_facts: false
tasks:
- name: Checksum config.yml and the binary before the failure cases
ansible.builtin.stat:
path: "{{ cloudflared_test_path }}"
checksum_algorithm: sha256
loop: [/etc/cloudflared/config.yml, /usr/local/bin/cloudflared]
loop_control:
loop_var: cloudflared_test_path
register: cloudflared_test_before
- name: Ask systemd about the daemon before the failure cases
ansible.builtin.systemd:
name: cloudflared
register: cloudflared_test_unit_before
- name: Run each case
ansible.builtin.include_tasks: tasks/failed_run.yml
loop:
- name: version-with-v
vars: {cloudflared_version: v2026.2.0}
expect: must be a release tag
- name: sha256-not-hex
vars: {cloudflared_sha256_amd64: not-a-hash}
expect: must be the 64-digit hex sha256
- name: ingress-without-service
vars: {cloudflared_ingress: [{hostname: app.example.test}]}
expect: each with hostname and service
- name: hostname-uppercase
vars: {cloudflared_ingress: [{hostname: App.example.test, service: "http://127.0.0.1:8080"}]}
expect: must be lowercase letters
- name: hostname-whitespace
vars: {cloudflared_ingress: [{hostname: "app.example.test\n - service: x", service: "http://127.0.0.1:8080"}]}
expect: must be lowercase letters
- name: user-with-percent
vars: {cloudflared_user: "cloud%flared"}
expect: must not contain a newline or %
- name: config-dir-with-newline
vars: {cloudflared_config_dir: "/etc/cloudflared\nExecStartPre=/bin/false"}
expect: must not contain a newline or %
- name: install-dir-relative
vars: {cloudflared_install_dir: usr/local/bin}
expect: the two directories must be absolute paths
- name: tunnel-id-not-uuid
vars: {cloudflared_tunnel_id: not-a-uuid}
expect: must be a lowercase UUID
- name: tunnel-not-minted
vars: {cloudflared_tunnel_id: ""}
expect: run the mint entry point first
- name: credentials-not-minted
vars: {cloudflared_credentials_json: ""}
expect: run the mint entry point first
- name: account-missing
vars: {cloudflared_account_id: ""}
expect: cloudflared_account_id and cloudflared_tunnel_api_token (vaulted) have no role default
- name: zone-missing
vars: {cloudflared_manage_dns: true}
expect: cloudflared_manage_dns is true, so cloudflared_zone_name
- name: tunnel-deleted
vars: {cloudflared_tunnel_id: 6f1a6e2c-0000-4000-8000-000000000002}
expect: no longer exists on Cloudflare
# Retried three times, 5 s apart, before the 404 is trusted.
- name: tunnel-unknown
vars: {cloudflared_tunnel_id: 6f1a6e2c-0000-4000-8000-00000000000f}
expect: (HTTP 404)
# The stub answers 403 to any other token.
- name: token-refused
vars: {cloudflared_tunnel_api_token: molecule-wrong-token}
expect: The Cloudflare tunnel lookup failed (HTTP 403)
- name: zone-unknown
vars: {cloudflared_manage_dns: true, cloudflared_zone_name: missing.example.test}
expect: No Cloudflare zone found named missing.example.test
- name: record-owned-by-something-else
vars:
cloudflared_manage_dns: true
cloudflared_zone_name: example.test
cloudflared_ingress: [{hostname: taken.example.test, service: "http://127.0.0.1:8080"}]
expect: do not point at a Cloudflare Tunnel
# The configured hash is the installed binary's, so the version was bumped without it.
- name: stale-sha256
vars:
cloudflared_version: 2026.3.0
cloudflared_sha256_amd64: "{{ cloudflared_test_stub | replace('@VERSION@', '2026.2.0') | hash('sha256') }}"
expect: The hash is stale
- name: checksum-mismatch
vars: {cloudflared_version: 2026.3.0, cloudflared_sha256_amd64: "{{ 'f' * 64 }}"}
expect: cloudflared was not stopped and still runs 2026.2.0
loop_control:
loop_var: cloudflared_test_case
label: "{{ cloudflared_test_case.name }}"
- name: Checksum config.yml and the binary after the failure cases
ansible.builtin.stat:
path: "{{ cloudflared_test_path }}"
checksum_algorithm: sha256
loop: [/etc/cloudflared/config.yml, /usr/local/bin/cloudflared]
loop_control:
loop_var: cloudflared_test_path
register: cloudflared_test_after
- name: Stat the staged binary
ansible.builtin.stat:
path: /usr/local/bin/cloudflared.new
register: cloudflared_test_staged
- name: Ask systemd about the daemon after the failure cases
ansible.builtin.systemd:
name: cloudflared
register: cloudflared_test_unit_after
- name: The failures changed nothing and the daemon still runs
ansible.builtin.assert:
that:
- cloudflared_test_after.results | map(attribute='stat.checksum') | list == cloudflared_test_before.results | map(attribute='stat.checksum') | list
- not cloudflared_test_staged.stat.exists
- cloudflared_test_unit_after.status.ActiveState == 'active'
# not restarted, not even by the failed update
- cloudflared_test_unit_after.status.MainPID == cloudflared_test_unit_before.status.MainPID
quiet: true
# The mint entry point. The molecule job runs with CI variables set, so every mint that should
# get past the CI guard runs as a child process with them blanked (mint.yml).
- name: Verify the mint entry point
hosts: all
gather_facts: false
vars:
cloudflared_test_mint_inputs:
cloudflared_api_base_url: "{{ cloudflared_api_base_url }}"
cloudflared_account_id: molecule-account
cloudflared_tunnel_api_token: molecule-not-a-token
cloudflared_tunnel_name: molecule-tunnel
cloudflared_test_no_ci: {GITHUB_ACTIONS: "", GITEA_ACTIONS: "", CI: "", ANSIBLE_NOCOLOR: "1"}
tasks:
- name: Mint without confirmation
block:
- name: Include the mint entry point with cloudflared_mint_confirm unset
ansible.builtin.include_role:
name: mortis.kamino.cloudflared
tasks_from: mint
# Only reached when the include returned, so the guard did not fire. The message
# must not contain the guard's text, so the rescue below cannot mistake it for it.
- name: Fail because the include returned
ansible.builtin.fail:
msg: The include returned without the confirm guard firing
rescue:
- name: The confirm guard fired, and nothing else failed first
ansible.builtin.assert:
that:
- "'mint is opt-in' in ansible_failed_result.msg"
- "'cloudflared_mint_confirm=true' in ansible_failed_result.msg"
quiet: true
- name: Mint under each CI variable, run as a child process with only that one set
delegate_to: localhost
run_once: true
ansible.builtin.command:
argv:
- ansible-playbook
- -i
- localhost,
- "{{ playbook_dir }}/mint.yml"
- -e
- "{{ cloudflared_test_mint_inputs | to_json }}"
environment: "{{ cloudflared_test_no_ci | combine({item: 'true'}) }}"
loop: [GITHUB_ACTIONS, GITEA_ACTIONS, CI]
register: cloudflared_test_mint_ci
# The child is expected to fail (the CI guard fires). Its rc and output are asserted next.
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)"
- "'mint is opt-in' not in (item.stdout ~ item.stderr)"
quiet: true
loop: "{{ cloudflared_test_mint_ci.results }}"
loop_control:
label: "{{ item.item }}"
- name: Run the mint cases outside CI, each as a child process
delegate_to: localhost
run_once: true
ansible.builtin.command:
argv: >-
{{ ['ansible-playbook', '-i', 'localhost,', playbook_dir ~ '/mint.yml',
'-e', cloudflared_test_mint_inputs | combine(item.vars) | to_json]
+ item.args | default([]) }}
environment: "{{ cloudflared_test_no_ci }}"
loop:
# A tunnel that is already set is never replaced.
- {name: already-set, vars: {cloudflared_tunnel_id: "{{ cloudflared_test_tunnel_id }}"}}
- {name: account-missing, vars: {cloudflared_account_id: ""}}
# An empty id counts as missing; in check mode the inputs are asserted and nothing is created.
- {name: check-mode, vars: {cloudflared_tunnel_id: ""}, args: [--check]}
- {name: minted, vars: {cloudflared_test_expect_minted: true}}
loop_control:
label: "{{ item.name }}"
register: cloudflared_test_mint_cases
# Some children are expected to fail. Their rc and output are asserted next.
failed_when: false
changed_when: false
- name: Read the requests the API stub received
delegate_to: localhost
ansible.builtin.slurp:
src: "{{ cloudflared_test_stub_dir }}/requests.log"
register: cloudflared_test_requests
- name: Each mint case ended as expected, and only the last one created a tunnel
vars:
cloudflared_test_out: >-
{{ cloudflared_test_mint_cases.results | map(attribute='stdout')
| zip(cloudflared_test_mint_cases.results | map(attribute='stderr')) | map('join', ' ') | list }}
cloudflared_test_rc: "{{ cloudflared_test_mint_cases.results | map(attribute='rc') | list }}"
cloudflared_test_posts: >-
{{ cloudflared_test_requests.content | b64decode | split('\n')
| select('search', '"POST", "path": "/client/v4/accounts/molecule-account/cfd_tunnel"') | list }}
ansible.builtin.assert:
that:
- cloudflared_test_rc[0] == 0
- "'nothing to mint' in cloudflared_test_out[0]"
- cloudflared_test_rc[1] != 0
- "'must be set and non-empty to mint' in cloudflared_test_out[1]"
- cloudflared_test_rc[2] == 0
- "'nothing to mint' not in cloudflared_test_out[2]"
- cloudflared_test_rc[3] == 0
- cloudflared_test_posts | length == 1
# Block scalar: the ': ' in the pattern would make a plain scalar a YAML mapping.
- >-
cloudflared_test_posts[0] is search('"status": 200')
fail_msg: "Return codes {{ cloudflared_test_rc }}, outputs: {{ cloudflared_test_out }}"
quiet: true
# The remove path. Last on purpose: it runs once, outside the idempotence step, and nothing runs
# after verify except molecule's cleanup. cloudflared_manage_dns stays false, so the removal
# deletes the tunnel through the API stub and makes no DNS call.
- 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.cloudflared
vars:
cloudflared_remove: true
cloudflared_remove_data: true
- name: Stat what the removal deletes
ansible.builtin.stat:
path: "{{ cloudflared_test_path }}"
loop:
- /etc/systemd/system/cloudflared.service
- /usr/local/bin/cloudflared
- /etc/cloudflared
- /etc/systemd/system/multi-user.target.wants/cloudflared.service
loop_control:
loop_var: cloudflared_test_path
register: cloudflared_test_removed
- name: Look up the cloudflared user
ansible.builtin.getent:
database: passwd
key: cloudflared
fail_key: false
register: cloudflared_test_user
- name: Ask systemd whether the service is still active
ansible.builtin.systemd:
name: cloudflared
register: cloudflared_test_active
failed_when: false
- name: Read the requests the API stub received
delegate_to: localhost
ansible.builtin.slurp:
src: "{{ cloudflared_test_stub_dir }}/requests.log"
register: cloudflared_test_requests
- name: Everything is gone, nothing was recreated, and the tunnel was deleted on Cloudflare
ansible.builtin.assert:
that:
- cloudflared_test_removed.results | map(attribute='stat') | map(attribute='exists') | select | list | length == 0
# prereqs, which create the account, do not run after a removal
- cloudflared_test_user.ansible_facts.getent_passwd.cloudflared is none
# the module errors for a unit that no longer exists, which is also a pass
- (cloudflared_test_active.status | default({})).ActiveState | default('inactive') != 'active'
- >-
cloudflared_test_requests.content | b64decode is search('"DELETE", "path": "/client/v4/accounts/molecule-account/cfd_tunnel/'
~ cloudflared_test_tunnel_id ~ '", "status": 200')
quiet: true
+305
View File
@@ -0,0 +1,305 @@
---
# validate.yml has asserted the minted tunnel secrets and the API credentials. The tunnel can
# still be gone on Cloudflare's side: cloudflared then loops on "Tunnel not found" while systemd
# reports the unit active, so check it first.
- name: Install and start cloudflared
become: true
tags: [cloudflared, configure]
block:
- name: Verify the tunnel still exists on Cloudflare
delegate_to: localhost
become: false
ansible.builtin.uri:
url: "{{ cloudflared_api_base_url }}/accounts/{{ cloudflared_account_id }}/cfd_tunnel/{{ cloudflared_tunnel_id }}"
method: GET
headers:
Authorization: "Bearer {{ cloudflared_tunnel_api_token }}"
status_code: [200, 404]
register: __cloudflared_tunnel_lookup
# Right after a mint a 404 can be read-after-write lag rather than a deletion: retry
# briefly before trusting it.
until: __cloudflared_tunnel_lookup.status | default(0) == 200
retries: 3
delay: 5
# Running out of retries fails the task whatever its status, and no_log would hide why: the
# two tasks below fail instead, with the re-mint instructions for a 404.
ignore_errors: true # noqa: ignore-errors
# Read-only GET: runs in --check too, so a deleted tunnel is caught in the preview.
check_mode: false
# The Authorization header carries the API token.
no_log: true
tags: [cloudflared, configure, health]
- name: Fail if the tunnel was deleted on Cloudflare's side
ansible.builtin.fail:
msg: >-
Tunnel {{ cloudflared_tunnel_id }} no longer exists on Cloudflare
(HTTP {{ __cloudflared_tunnel_lookup.status }}). Re-mint it: remove the stale
cloudflared_tunnel_id and cloudflared_credentials_json from your inventory, run the mint
entry point with -e cloudflared_mint_confirm=true, persist the minted values and run the
role again. A hostname whose record still points at a cfargotunnel.com tunnel is repointed
without a cloudflared_allow_dns_overwrite entry.
when: >-
__cloudflared_tunnel_lookup.status | default(0) == 404 or
((__cloudflared_tunnel_lookup.json | default({})).result | default({})).deleted_at | default(None) is not none
tags: [cloudflared, configure, health]
- name: Fail if the tunnel lookup failed
ansible.builtin.fail:
msg: >-
The Cloudflare tunnel lookup failed (HTTP {{ __cloudflared_tunnel_lookup.status | default('none') }}).
Check cloudflared_api_base_url, cloudflared_account_id and that cloudflared_tunnel_api_token has the
Cloudflare Tunnel permission.
when: __cloudflared_tunnel_lookup is failed
tags: [cloudflared, configure, health]
- name: Manage the tunnel's DNS records
when: cloudflared_manage_dns | bool
vars:
__cloudflared_prune_url: >-
{{ cloudflared_api_base_url }}/zones/{{ __cloudflared_zone_lookup.json.result[0].id }}/dns_records?type=CNAME&content={{
(cloudflared_tunnel_id ~ '.cfargotunnel.com') | urlencode }}&per_page=100
block:
- name: Look up Cloudflare zone ID for DNS pruning
delegate_to: localhost
become: false
ansible.builtin.uri:
url: "{{ cloudflared_api_base_url }}/zones?name={{ cloudflared_zone_name | urlencode }}"
method: GET
headers:
Authorization: "Bearer {{ cloudflared_tunnel_api_token }}"
status_code: [200]
register: __cloudflared_zone_lookup
# Read-only GET: runs in --check too, so the guards below can report.
check_mode: false
# The Authorization header carries the API token.
no_log: true
- name: Fail if Cloudflare zone lookup returned no results
ansible.builtin.fail:
msg: "No Cloudflare zone found named {{ cloudflared_zone_name }}"
when: __cloudflared_zone_lookup.json.result | length == 0
# One query per hostname, filtered by name and not by type, so an existing A or AAAA
# record at a hostname is caught too, however many records the zone holds.
- name: Look up the existing DNS records of each ingress hostname
delegate_to: localhost
become: false
loop: "{{ cloudflared_ingress }}"
loop_control:
loop_var: __cloudflared_ingress_item
label: "{{ __cloudflared_ingress_item.hostname }}"
ansible.builtin.uri:
url: >-
{{ cloudflared_api_base_url }}/zones/{{ __cloudflared_zone_lookup.json.result[0].id }}/dns_records?name={{
__cloudflared_ingress_item.hostname | lower | urlencode }}&per_page=100
method: GET
headers:
Authorization: "Bearer {{ cloudflared_tunnel_api_token }}"
status_code: [200]
register: __cloudflared_hostname_records
# Read-only GET: runs in --check too, so the guard below fails before anything is written.
check_mode: false
# The Authorization header carries the API token.
no_log: true
# Fail closed: a record that does not point at a Cloudflare Tunnel belongs to something
# else and is replaced only with an explicit cloudflared_allow_dns_overwrite entry. A record
# that points at some cfargotunnel.com tunnel (this one, or one replaced by a re-mint) is
# this role's own and is repointed. Names compare case-insensitively.
- name: Fail if an existing record doesn't already point at a tunnel
ansible.builtin.fail:
msg: >-
Existing DNS record(s) for {{ __cloudflared_hostname }}
({{ __cloudflared_existing_targets }}) do not point at a Cloudflare
Tunnel. Verify manually and add
{{ __cloudflared_hostname }} to
cloudflared_allow_dns_overwrite to proceed if this is expected.
loop: "{{ cloudflared_ingress }}"
loop_control:
loop_var: __cloudflared_ingress_item
index_var: __cloudflared_ingress_index
label: "{{ __cloudflared_ingress_item.hostname }}"
vars:
__cloudflared_hostname: "{{ __cloudflared_ingress_item.hostname | lower }}"
__cloudflared_existing_targets: >-
{{ __cloudflared_hostname_records.results[__cloudflared_ingress_index].json.result
| selectattr('name', 'match', '(?i)^' ~ (__cloudflared_hostname | regex_escape) ~ '$')
| map(attribute='content') | map('lower') | map('trim', '.') | list }}
when: >-
__cloudflared_hostname not in (cloudflared_allow_dns_overwrite | map('lower') | list) and
__cloudflared_existing_targets | length > 0 and
__cloudflared_existing_targets | select('match', '^.*\.cfargotunnel\.com$') | list | length == 0
- name: Point public DNS at the tunnel
delegate_to: localhost
become: false
loop: "{{ cloudflared_ingress }}"
loop_control:
loop_var: __cloudflared_ingress_item
label: "{{ __cloudflared_ingress_item.hostname }}"
community.general.cloudflare_dns:
zone: "{{ cloudflared_zone_name }}"
record: "{{ __cloudflared_ingress_item.hostname }}"
type: CNAME
value: "{{ cloudflared_tunnel_id }}.cfargotunnel.com"
proxied: true
api_token: "{{ cloudflared_tunnel_api_token }}"
state: present
# api_token is a module parameter and would show in the task's output.
no_log: true
# Filtered by content=<tunnel id>.cfargotunnel.com, so the prune below only ever sees
# CNAMEs of this tunnel, never records of other services or tunnels in the zone. Paged:
# the first page says how many there are, the rest are fetched below.
- name: List existing DNS records pointing at this tunnel
delegate_to: localhost
become: false
ansible.builtin.uri:
url: "{{ __cloudflared_prune_url }}&page=1"
method: GET
headers:
Authorization: "Bearer {{ cloudflared_tunnel_api_token }}"
status_code: [200]
register: __cloudflared_tunnel_records_first
# Read-only GET: runs in --check too, so the prune can report.
check_mode: false
# The Authorization header carries the API token.
no_log: true
- name: List the further pages of DNS records pointing at this tunnel
delegate_to: localhost
become: false
loop: "{{ range(2, (__cloudflared_tunnel_records_first.json.result_info.total_pages | default(1) | int) + 1) | list }}"
loop_control:
loop_var: __cloudflared_page
ansible.builtin.uri:
url: "{{ __cloudflared_prune_url }}&page={{ __cloudflared_page }}"
method: GET
headers:
Authorization: "Bearer {{ cloudflared_tunnel_api_token }}"
status_code: [200]
register: __cloudflared_tunnel_records_more
check_mode: false
no_log: true
- name: Prune DNS records for hostnames no longer in cloudflared_ingress
delegate_to: localhost
become: false
loop: >-
{{ __cloudflared_tunnel_records_first.json.result
+ (__cloudflared_tunnel_records_more.results | default([]) | map(attribute='json.result') | flatten(levels=1)) }}
loop_control:
loop_var: __cloudflared_dns_record_item
label: "{{ __cloudflared_dns_record_item.name }}"
community.general.cloudflare_dns:
zone: "{{ cloudflared_zone_name }}"
record: "{{ __cloudflared_dns_record_item.name }}"
type: CNAME
api_token: "{{ cloudflared_tunnel_api_token }}"
state: absent
when: __cloudflared_dns_record_item.name | lower not in (cloudflared_ingress | map(attribute='hostname') | map('lower') | list)
# api_token is a module parameter and would show in the task's output.
no_log: true
- name: Create cloudflared config file
ansible.builtin.template:
src: config.yml.j2
dest: "{{ cloudflared_config_dir }}/config.yml"
owner: "{{ cloudflared_user }}"
group: "{{ cloudflared_group }}"
mode: "0640"
# A config cloudflared rejects is never written.
validate: "{{ cloudflared_install_dir }}/cloudflared tunnel --config %s ingress validate"
notify: Restart cloudflared
# Also the only check of the existing config under --tags health, where the template above
# does not run.
- name: Validate cloudflared ingress config
ansible.builtin.command:
argv:
- "{{ cloudflared_install_dir }}/cloudflared"
- tunnel
- --config
- "{{ cloudflared_config_dir }}/config.yml"
- ingress
- validate
register: __cloudflared_ingress_validate
changed_when: false
failed_when: __cloudflared_ingress_validate.rc != 0
tags: [cloudflared, configure, health]
- name: Write tunnel credentials file
ansible.builtin.copy:
content: "{{ cloudflared_credentials_json }}"
dest: "{{ cloudflared_config_dir }}/{{ cloudflared_tunnel_id }}.json"
owner: "{{ cloudflared_user }}"
group: "{{ cloudflared_group }}"
mode: "0600"
notify: Restart cloudflared
# The content is the tunnel credentials JSON.
no_log: true
diff: false
# A prior tunnel's credentials file would otherwise stay on disk after a re-mint.
- name: Find stale tunnel credentials files
ansible.builtin.find:
paths: "{{ cloudflared_config_dir }}"
# Tunnel ids are UUIDs, so credentials files are <uuid>.json; an unrelated JSON file in
# the directory is left alone.
patterns: "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\.json$"
use_regex: true
excludes: "{{ cloudflared_tunnel_id }}.json"
register: __cloudflared_stale_credentials
- name: Remove stale tunnel credentials left by a prior tunnel
ansible.builtin.file:
path: "{{ __cloudflared_stale_credential_item.path }}"
state: absent
loop: "{{ __cloudflared_stale_credentials.files }}"
loop_control:
loop_var: __cloudflared_stale_credential_item
label: "{{ __cloudflared_stale_credential_item.path }}"
- name: Create systemd service file for cloudflared
ansible.builtin.copy:
dest: "{{ cloudflared_service_unit }}"
content: |
[Unit]
Description=Cloudflare Tunnel
After=network.target
[Service]
User={{ cloudflared_user }}
Group={{ cloudflared_group }}
ExecStart={{ cloudflared_install_dir }}/cloudflared tunnel \
--config {{ cloudflared_config_dir }}/config.yml run
Restart=always
[Install]
WantedBy=multi-user.target
owner: root
group: root
mode: "0644"
- name: Reload systemd daemon
ansible.builtin.systemd:
daemon_reload: true
- name: Enable and start cloudflared
ansible.builtin.systemd:
name: cloudflared
enabled: true
state: started
- name: Check cloudflared service status
ansible.builtin.systemd:
name: cloudflared
register: __cloudflared_service_status
tags: [cloudflared, configure, health]
- name: Fail if cloudflared service is not running
ansible.builtin.fail:
msg: "cloudflared service is not running"
when: __cloudflared_service_status.status.ActiveState != "active"
tags: [cloudflared, configure, health]
+18
View File
@@ -0,0 +1,18 @@
---
# The one download of the cloudflared 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
# cloudflared_sha256_amd64 before it moves the file to __cloudflared_download_dest, so a failed or
# mismatching 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 cloudflared binary
become: true
ansible.builtin.get_url:
url: "{{ cloudflared_download_url }}"
dest: "{{ __cloudflared_download_dest }}"
checksum: "sha256:{{ cloudflared_sha256_amd64 }}"
owner: root
group: root
mode: "0755"
tags: [cloudflared, install, update]
+21
View File
@@ -0,0 +1,21 @@
---
- name: Download and install cloudflared binary
ansible.builtin.include_tasks: download.yml
vars:
__cloudflared_download_dest: "{{ cloudflared_install_dir }}/cloudflared"
tags: [cloudflared, install]
- name: Ensure cloudflared binary exists
ansible.builtin.stat:
path: "{{ cloudflared_install_dir }}/cloudflared"
register: __cloudflared_binary
tags: [cloudflared, install, health]
- name: Fail if cloudflared binary missing
ansible.builtin.assert:
that:
- __cloudflared_binary.stat.exists
fail_msg: "cloudflared binary not found after download"
# Nothing is downloaded under --check.
when: not ansible_check_mode
tags: [cloudflared, install, health]
+32
View File
@@ -0,0 +1,32 @@
---
- name: Validate the role inputs
ansible.builtin.import_tasks: validate.yml
tags: [cloudflared, always]
# The removal ends the role: none of the tasks below runs, so a removed daemon is not
# installed and configured again in the same run.
- name: Remove cloudflared (explicit only)
ansible.builtin.include_tasks: remove.yml
when: cloudflared_remove | bool
tags: [cloudflared, remove]
- name: Install, configure and update cloudflared
when: not (cloudflared_remove | bool)
block:
- name: Include prerequisites
ansible.builtin.include_tasks: prereqs.yml
tags: [cloudflared, prereqs, always]
- name: Install cloudflared if missing
ansible.builtin.include_tasks: install.yml
when: not __cloudflared_installed
tags: [cloudflared, install]
- name: Configure cloudflared
ansible.builtin.include_tasks: configure.yml
tags: [cloudflared, configure, health]
- name: Ensure cloudflared is up-to-date
ansible.builtin.include_tasks: update.yml
when: cloudflared_update | bool
tags: [cloudflared, update]
+95
View File
@@ -0,0 +1,95 @@
---
# Opt-in entry point (tasks_from: mint): creates the Cloudflare Tunnel through the Cloudflare
# API from the controller (no `cloudflared tunnel login`, no browser) and registers its id and
# credentials as the no_log facts cloudflared_minted_tunnel_id and
# cloudflared_minted_credentials_json. The tunnel secret exists only in memory. Persisting the
# facts (for example vault-encrypted into inventory as cloudflared_tunnel_id and
# cloudflared_credentials_json) is the calling play's job; this role writes no file.
- name: Require explicit opt-in for the cloudflared mint
ansible.builtin.assert:
that:
- cloudflared_mint_confirm | bool
fail_msg: "cloudflared mint is opt-in: pass -e cloudflared_mint_confirm=true"
quiet: true
tags: [cloudflared, always]
- name: Refuse to mint 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: "cloudflared mint refuses to run under CI: run the mint play by hand"
quiet: true
tags: [cloudflared, always]
# Defined and empty (or null) counts as missing: the main entry point asserts a non-empty id, so
# skipping the mint on an empty one would deadlock. A tunnel that is already set is never
# replaced, so a re-run is safe.
- name: Skip the cloudflared mint when the tunnel is already set
ansible.builtin.debug:
msg: "cloudflared_tunnel_id is already set for {{ inventory_hostname }}; nothing to mint."
when: (cloudflared_tunnel_id | default('', true) | string | length) > 0
tags: [cloudflared, mint]
# Before anything is created, and in --check too.
- name: Require the mint inputs
ansible.builtin.assert:
that:
- cloudflared_account_id | default('', true) | string | length > 0
- cloudflared_tunnel_api_token | default('', true) | string | length > 0
- cloudflared_tunnel_name | default('', true) | string | length > 0
fail_msg: >-
cloudflared_account_id, cloudflared_tunnel_api_token (vaulted) and cloudflared_tunnel_name must be set
and non-empty to mint a tunnel.
quiet: true
when: (cloudflared_tunnel_id | default('', true) | string | length) == 0
tags: [cloudflared, always]
# uri makes its request even under --check, so the block is skipped there: a preview must never
# create a tunnel.
- name: Mint Cloudflare Tunnel via API
when: (cloudflared_tunnel_id | default('', true) | string | length) == 0 and not ansible_check_mode
delegate_to: localhost
become: false
tags: [cloudflared, mint]
block:
- name: Generate tunnel secret
ansible.builtin.command:
argv: [openssl, rand, -base64, "32"]
register: __cloudflared_tunnel_secret
changed_when: false
no_log: true
- name: Create Cloudflare Tunnel via API
ansible.builtin.uri:
url: "{{ cloudflared_api_base_url }}/accounts/{{ cloudflared_account_id }}/cfd_tunnel"
method: POST
headers:
Authorization: "Bearer {{ cloudflared_tunnel_api_token }}"
Content-Type: "application/json"
body_format: json
body:
name: "{{ cloudflared_tunnel_name }}"
tunnel_secret: "{{ __cloudflared_tunnel_secret.stdout | trim }}"
config_src: "local"
status_code: [200]
register: __cloudflared_tunnel_create
changed_when: true
no_log: true
# Not cloudflared_tunnel_id itself: the block's `when` is re-evaluated per task and reads it,
# so setting it here would skip every task after this one. Not cacheable and never printed.
- name: Register the minted tunnel facts
ansible.builtin.set_fact:
cloudflared_minted_tunnel_id: "{{ __cloudflared_tunnel_create.json.result.id }}"
cloudflared_minted_credentials_json: "{{ __cloudflared_tunnel_create.json.result.credentials_file | to_json }}"
no_log: true
# The raw secret and the API response (its credentials_file holds the TunnelSecret) would
# otherwise stay in the host's vars for the rest of the play; only the minted facts are kept.
- name: Clear the tunnel secret intermediates
ansible.builtin.set_fact:
__cloudflared_tunnel_secret: ""
__cloudflared_tunnel_create: ""
no_log: true
+39
View File
@@ -0,0 +1,39 @@
---
- name: Create cloudflared group
become: true
ansible.builtin.group:
name: "{{ cloudflared_group }}"
system: true
tags: [cloudflared, prereqs, always]
- name: Create cloudflared user
become: true
ansible.builtin.user:
name: "{{ cloudflared_user }}"
group: "{{ cloudflared_group }}"
shell: /usr/sbin/nologin
comment: "Cloudflare Tunnel daemon"
system: true
create_home: false
tags: [cloudflared, prereqs, always]
- name: Create cloudflared config directory
become: true
ansible.builtin.file:
path: "{{ cloudflared_config_dir }}"
state: directory
owner: "{{ cloudflared_user }}"
group: "{{ cloudflared_group }}"
mode: "0750"
tags: [cloudflared, prereqs, always]
- name: Check if cloudflared binary exists
ansible.builtin.stat:
path: "{{ cloudflared_install_dir }}/cloudflared"
register: __cloudflared_binary
tags: [cloudflared, prereqs, always]
- name: Set cloudflared facts
ansible.builtin.set_fact:
__cloudflared_installed: "{{ __cloudflared_binary.stat.exists }}"
tags: [cloudflared, prereqs, always]
+88
View File
@@ -0,0 +1,88 @@
---
# Run with -e cloudflared_remove=true (and cloudflared_remove_data=true to delete the
# configuration, the user, and the tunnel and its DNS records on Cloudflare too). The role ends
# after these tasks.
- name: Stop cloudflared service
become: true
ansible.builtin.systemd:
name: cloudflared
state: stopped
enabled: false
register: __cloudflared_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:
- __cloudflared_stop.failed | default(false)
- "'Could not find the requested service' not in (__cloudflared_stop.msg | default(''))"
tags: [cloudflared, remove]
- name: Remove systemd service
become: true
ansible.builtin.file:
path: "{{ cloudflared_service_unit }}"
state: absent
tags: [cloudflared, remove]
- name: Reload systemd
become: true
ansible.builtin.systemd:
daemon_reload: true
tags: [cloudflared, remove]
- name: Remove cloudflared binary
become: true
ansible.builtin.file:
path: "{{ cloudflared_install_dir }}/cloudflared"
state: absent
tags: [cloudflared, remove]
- name: Remove cloudflared configuration
become: true
ansible.builtin.file:
path: "{{ cloudflared_config_dir }}"
state: absent
when: cloudflared_remove_data | bool
tags: [cloudflared, remove]
- name: Remove cloudflared user
become: true
ansible.builtin.user:
name: "{{ cloudflared_user }}"
state: absent
remove: true
when: cloudflared_remove_data | bool
tags: [cloudflared, remove]
# Permanently deletes the tunnel and its DNS records on Cloudflare, so it needs
# cloudflared_remove_data: a plain cloudflared_remove only touches the host.
- name: Remove Cloudflare-side tunnel resources
when:
- cloudflared_remove_data | bool
- (cloudflared_tunnel_id | default('', true) | string | length) > 0
delegate_to: localhost
become: false
no_log: true
block:
- name: Remove public DNS record(s) for the tunnel
loop: "{{ cloudflared_ingress }}"
loop_control:
loop_var: __cloudflared_ingress_item
label: "{{ __cloudflared_ingress_item.hostname }}"
community.general.cloudflare_dns:
zone: "{{ cloudflared_zone_name }}"
record: "{{ __cloudflared_ingress_item.hostname }}"
type: CNAME
value: "{{ cloudflared_tunnel_id }}.cfargotunnel.com"
api_token: "{{ cloudflared_tunnel_api_token }}"
state: absent
when: cloudflared_manage_dns | bool
tags: [cloudflared, remove]
- name: Delete the Cloudflare Tunnel via API
ansible.builtin.uri:
url: "{{ cloudflared_api_base_url }}/accounts/{{ cloudflared_account_id }}/cfd_tunnel/{{ cloudflared_tunnel_id }}"
method: DELETE
headers:
Authorization: "Bearer {{ cloudflared_tunnel_api_token }}"
status_code: [200]
tags: [cloudflared, remove]
+106
View File
@@ -0,0 +1,106 @@
---
- name: Check installed cloudflared version
ansible.builtin.command:
argv: ["{{ cloudflared_install_dir }}/cloudflared", --version]
register: __cloudflared_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 the sha256 guard below would fail against an up-to-date
# binary.
check_mode: false
tags: [cloudflared, update]
- name: Extract installed cloudflared version
ansible.builtin.set_fact:
__cloudflared_installed_version: >-
{{
(__cloudflared_version_cmd.stdout
| regex_findall('([0-9]{4}\.[0-9]+\.[0-9]+)')
| first)
| default('0.0.0')
}}
tags: [cloudflared, update]
- name: Determine if cloudflared update required
ansible.builtin.set_fact:
__cloudflared_update_required: "{{ __cloudflared_installed_version != cloudflared_version }}"
# Next to the live binary, so the swap is a rename on one filesystem.
__cloudflared_staged_binary: "{{ cloudflared_install_dir }}/cloudflared.new"
tags: [cloudflared, update]
# A hash left over from an older release (a version bumped without its hash) would fail the
# staged download below with a bare checksum mismatch. Say what is wrong instead. Read-only, so
# it also runs in the --check preview.
- name: Check the installed binary against the configured sha256
ansible.builtin.stat:
path: "{{ cloudflared_install_dir }}/cloudflared"
checksum_algorithm: sha256
get_checksum: true
register: __cloudflared_installed_stat
when: __cloudflared_update_required
tags: [cloudflared, update]
- name: Fail when cloudflared_sha256_amd64 is the hash of the installed binary
ansible.builtin.assert:
that:
- (__cloudflared_installed_stat.stat.checksum | default('')) | lower != cloudflared_sha256_amd64 | lower
fail_msg: >-
cloudflared_sha256_amd64 equals the sha256 of the binary installed on {{ inventory_hostname }}
(version {{ __cloudflared_installed_version }}), but cloudflared_version is {{ cloudflared_version }}.
The hash is stale: set it to the sha256 of the cloudflared-linux-amd64 asset of release
{{ cloudflared_version }}.
quiet: true
when: __cloudflared_update_required
tags: [cloudflared, update]
# Download and verify before anything is stopped: a failed download or checksum leaves the
# running daemon untouched. mortis.kamino._binary_update then stops, backs up, swaps, restarts,
# checks the version and rolls back on failure, and removes the staged binary. A binary that
# reports no version (0.0.0 above) is replaced too; _binary_update backs it up when it exists.
- name: Stage and swap in the new cloudflared binary
when: __cloudflared_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 cloudflared binary
block:
- name: Download and verify into the staging path
ansible.builtin.include_tasks: download.yml
vars:
__cloudflared_download_dest: "{{ __cloudflared_staged_binary }}"
tags: [cloudflared, update]
rescue:
- name: Fail the staging
ansible.builtin.fail:
msg: >-
Staging cloudflared {{ cloudflared_version }} failed ({{ ansible_failed_result.msg | default('see the task above') }}).
cloudflared was not stopped and still runs {{ __cloudflared_installed_version }}.
tags: [cloudflared, update]
# An include does not pass its tags on to the included tasks, hence apply.
- name: Swap in the staged cloudflared binary
ansible.builtin.include_role:
name: mortis.kamino._binary_update
apply:
tags: [cloudflared, update]
vars:
_binary_update_service: cloudflared
_binary_update_binary_path: "{{ cloudflared_install_dir }}/cloudflared"
_binary_update_staged_path: "{{ __cloudflared_staged_binary }}"
_binary_update_version_command: ["{{ cloudflared_install_dir }}/cloudflared", --version]
_binary_update_expected_version: "{{ cloudflared_version }}"
_binary_update_version_regex: '([0-9]{4}\.[0-9]+\.[0-9]+)'
tags: [cloudflared, 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 cloudflared binary
become: true
ansible.builtin.file:
path: "{{ __cloudflared_staged_binary }}"
state: absent
tags: [cloudflared, update]
+119
View File
@@ -0,0 +1,119 @@
---
# 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 cloudflared_version
ansible.builtin.assert:
that:
- cloudflared_version is string
- cloudflared_version is match('^[0-9]{4}\\.[0-9]+\\.[0-9]+$')
fail_msg: >-
cloudflared_version must be a release tag such as 2026.11.1 (YYYY.M.P), with no leading v: it is
used in the download URL and compared with what the binary reports.
quiet: true
- name: Require a sha256 for the binary
ansible.builtin.assert:
that:
- cloudflared_sha256_amd64 is string
- cloudflared_sha256_amd64 is match('^[0-9a-fA-F]{64}$')
fail_msg: >-
cloudflared_sha256_amd64 must be the 64-digit hex sha256 of the cloudflared-linux-amd64 asset of
release {{ cloudflared_version }}.
quiet: true
# The items land in config.yml and, with cloudflared_manage_dns, become DNS records.
- name: Require a hostname and a service for every ingress rule
ansible.builtin.assert:
that:
- cloudflared_ingress is sequence
- cloudflared_ingress is not string
- cloudflared_ingress is not mapping
- cloudflared_ingress | reject('mapping') | list | length == 0
- cloudflared_ingress | selectattr('hostname', 'defined') | selectattr('service', 'defined') | list | length == cloudflared_ingress | length
fail_msg: >-
cloudflared_ingress must be a list of mappings, each with hostname and service (and optionally
originRequest).
quiet: true
# A hostname lands unquoted in config.yml and is compared with DNS record names.
- name: Require plain lowercase ingress hostnames
ansible.builtin.assert:
that:
- cloudflared_ingress | map(attribute='hostname') | reject('string') | list | length == 0
- cloudflared_ingress | map(attribute='hostname') | reject('match', '^(\\*\\.)?[a-z0-9_.-]+\\Z') | list | length == 0
fail_msg: >-
Every cloudflared_ingress hostname must be lowercase letters, digits, dots, hyphens or underscores,
with an optional leading *. and no whitespace or newline.
quiet: true
# The values land in the systemd unit and in file paths: a newline or % would inject or expand
# unit directives.
- name: Require plain service account names and absolute directories
ansible.builtin.assert:
that:
- cloudflared_user is string
- cloudflared_group is string
- cloudflared_install_dir is string
- cloudflared_config_dir is string
- (cloudflared_user ~ cloudflared_group ~ cloudflared_install_dir ~ cloudflared_config_dir) is not search('[\\r\\n%]')
- cloudflared_install_dir is match('/')
- cloudflared_config_dir is match('/')
fail_msg: >-
cloudflared_user, cloudflared_group, cloudflared_install_dir and cloudflared_config_dir must not contain a
newline or %, and the two directories must be absolute paths.
quiet: true
# The role never creates the tunnel on its main entry point. Defined and empty (or null) counts
# as missing, as in the mint entry point, so the two cannot disagree.
- name: Require the minted tunnel secrets
ansible.builtin.assert:
that:
- cloudflared_tunnel_id | default('', true) | string | length > 0
- cloudflared_credentials_json | default('', true) | string | length > 0
fail_msg: >-
cloudflared_tunnel_id and cloudflared_credentials_json are not defined or empty: run the mint entry
point first (include_role with tasks_from: mint and -e cloudflared_mint_confirm=true), persist
cloudflared_minted_tunnel_id and cloudflared_minted_credentials_json into your inventory as these two
variables, and run the role again.
quiet: true
when: not (cloudflared_remove | bool)
# The id names the credentials file, and stale credentials are found by the UUID shape.
- name: Require a UUID tunnel id
ansible.builtin.assert:
that:
- >-
cloudflared_tunnel_id | default('', true) | string | length == 0 or
cloudflared_tunnel_id | string is match('^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\Z')
fail_msg: cloudflared_tunnel_id must be a lowercase UUID, as the mint entry point returns it.
quiet: true
# Every Cloudflare call below needs them: the tunnel check on every run, the tunnel deletion
# of a removal with cloudflared_remove_data.
- name: Require the Cloudflare API credentials
ansible.builtin.assert:
that:
- cloudflared_account_id | default('', true) | string | length > 0
- cloudflared_tunnel_api_token | default('', true) | string | length > 0
fail_msg: >-
cloudflared_account_id and cloudflared_tunnel_api_token (vaulted) have no role default and must be set
and non-empty.
quiet: true
when: >-
not (cloudflared_remove | bool) or
((cloudflared_remove_data | bool) and (cloudflared_tunnel_id | default('', true) | string | length) > 0)
- name: Require the zone while the role manages DNS
ansible.builtin.assert:
that:
- cloudflared_zone_name is string
- cloudflared_zone_name | length > 0
fail_msg: >-
cloudflared_manage_dns is true, so cloudflared_zone_name must name the DNS zone of the
cloudflared_ingress hostnames.
quiet: true
when:
- cloudflared_manage_dns | bool
- >-
not (cloudflared_remove | bool) or
((cloudflared_remove_data | bool) and (cloudflared_tunnel_id | default('', true) | string | length) > 0)
+13
View File
@@ -0,0 +1,13 @@
tunnel: {{ cloudflared_tunnel_id }}
credentials-file: {{ cloudflared_config_dir }}/{{ cloudflared_tunnel_id }}.json
ingress:
{% for rule in cloudflared_ingress %}
- hostname: {{ rule.hostname }}
service: {{ rule.service }}
{% if rule.originRequest is defined %}
originRequest:
{{ rule.originRequest | to_nice_yaml | indent(6, first=true) }}
{% endif %}
{% endfor %}
- service: http_status:404
+2 -2
View File
@@ -4,7 +4,7 @@ Installs Docker Engine from the upstream Docker APT repository, optionally updat
## Supported platforms
Ubuntu. The key and repository URLs point at `download.docker.com/linux/ubuntu`, and the source line uses `ansible_distribution_release`. The default architecture is `amd64`. A limited molecule scenario covers the role's own logic (see [Tests](#tests)); the real Docker Engine is not tested.
Ubuntu. The key and repository URLs point at `download.docker.com/linux/ubuntu`, and the source line uses `ansible_distribution_release`. The apt architecture is derived from the host (`x86_64` gives `amd64`, `aarch64` gives `arm64`); any other architecture fails the play until `docker_apt_arch` is set. A limited molecule scenario covers the role's own logic (see [Tests](#tests)); the real Docker Engine is not tested.
## Requirements and run order
@@ -25,7 +25,7 @@ Ubuntu. The key and repository URLs point at `download.docker.com/linux/ubuntu`,
| `docker_apt_list_path` | `/etc/apt/sources.list.d/docker.list` | no | APT source file. |
| `docker_gpg_url` | `https://download.docker.com/linux/ubuntu/gpg` | no | Key URL. |
| `docker_repo_base_url` | `https://download.docker.com/linux/ubuntu` | no | Repository base URL. |
| `docker_apt_arch` | `amd64` | no | Architecture in the APT source. |
| `docker_apt_arch` | derived from the host | no | Architecture in the APT source. Empty derives it (`x86_64` gives `amd64`, `aarch64` gives `arm64`); another architecture fails until this is set. A value set here is always used; lowercase letters and digits only. |
| `docker_service` | `docker` | no | systemd unit name. |
| `docker_group` | `docker` | no | Group for `docker_users`. |
| `docker_users` | `[]` | no | Users added to the group. |
+3 -2
View File
@@ -13,8 +13,9 @@ docker_apt_list_path: /etc/apt/sources.list.d/docker.list
docker_gpg_url: https://download.docker.com/linux/ubuntu/gpg
docker_repo_base_url: https://download.docker.com/linux/ubuntu
# Override per host if a host is not amd64.
docker_apt_arch: amd64
# Architecture written into the APT source. Empty (the default) derives it from the host: x86_64 gives amd64, aarch64 gives arm64, any
# other architecture fails the play, so set it here (for example armhf) when Docker publishes one for it.
docker_apt_arch: ""
docker_service: docker
docker_group: docker
+5 -2
View File
@@ -56,9 +56,12 @@ argument_specs:
- Base URL of the repository. The source line uses C(ansible_distribution_release) and the C(stable) component.
docker_apt_arch:
type: str
default: amd64
default: ""
description:
- Architecture written into the APT source. Override per host if a host is not amd64.
- >-
Architecture written into the APT source. Empty (the default) derives it from the host: C(x86_64) gives C(amd64), C(aarch64)
gives C(arm64). Any other host architecture fails the play, so set this to the name Docker publishes for it. Lowercase letters
and digits only. A value set here is always used.
docker_service:
type: str
default: docker
@@ -59,3 +59,27 @@
- "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')"
- "'docker_remove' in ansible_failed_result.msg | default('')"
quiet: true
# The architecture is written into the one-line apt source, so a value with a space or a bracket is refused before anything
# changes. The derived default is covered by the converge above and verify.yml (the container is x86_64, so the source says amd64).
- name: A docker_apt_arch value that would corrupt the apt source is refused
hosts: all
gather_facts: false
vars:
docker_apt_arch: "bad arch"
tasks:
- name: Apply the role with a bad architecture
block:
- name: Include the role
ansible.builtin.include_role:
name: mortis.kamino.docker
- name: Fail when the bad architecture was accepted
ansible.builtin.fail:
msg: MOLECULE-ACCEPTED
rescue:
- name: The validation stopped the play
ansible.builtin.assert:
that:
- "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')"
- "'docker_apt_arch' in ansible_failed_result.msg | default('')"
quiet: true
+1
View File
@@ -17,6 +17,7 @@
- /srv/docker-stub-repo/docker.asc
register: docker_verify_files
# amd64 because the Molecule container is x86_64: the role derives the architecture from the host now.
- name: The source line carries the arch, the keyring and the release
ansible.builtin.assert:
that:
+1 -1
View File
@@ -30,7 +30,7 @@
ansible.builtin.copy:
dest: "{{ docker_apt_list_path }}"
content: |
deb [arch={{ docker_apt_arch }} signed-by={{ docker_keyring_path }}] {{ docker_repo_base_url }} {{ ansible_distribution_release }} stable
deb [arch={{ __docker_apt_arch }} signed-by={{ docker_keyring_path }}] {{ docker_repo_base_url }} {{ ansible_distribution_release }} stable
mode: "0644"
tags: [docker, install]
+5
View File
@@ -1,4 +1,9 @@
---
- name: Validate inputs
ansible.builtin.import_tasks: validate.yml
when: not (docker_remove | default(false) | bool)
tags: always
- name: Remove Docker (explicit only)
ansible.builtin.include_tasks: remove.yml
when: docker_remove | default(false) | bool
+23
View File
@@ -0,0 +1,23 @@
---
# Fact-computing and assertion only, before any task changes the host. A removal does not write the apt source, so it does not need the architecture.
- name: Work out the apt architecture
ansible.builtin.set_fact:
__docker_apt_arch: >-
{{ docker_apt_arch | default('', true) or __docker_arch_by_fact[ansible_facts['architecture'] | default('')] | default('', true) }}
tags: always
# The value is written into the one-line apt source (deb [arch=... signed-by=...]): a space or a bracket would corrupt it.
- name: Check the apt architecture
ansible.builtin.assert:
that:
- __docker_apt_arch is match('^[a-z0-9]+\Z')
fail_msg: >-
{% if docker_apt_arch | default('', true) | length > 0 %}
docker_apt_arch '{{ docker_apt_arch }}' is not a valid apt architecture name: use the name Docker publishes (for example amd64 or arm64),
lowercase letters and digits only.
{% else %}
The host architecture '{{ ansible_facts['architecture'] | default('unknown') }}' has no known Docker apt architecture (x86_64 and aarch64 do).
Set docker_apt_arch to the name Docker publishes for it, for example armhf.
{% endif %}
quiet: true
tags: always
+6
View File
@@ -0,0 +1,6 @@
---
# Constants, not inputs: the Docker apt architecture for each ansible_facts['architecture'] the role derives it for. docker_apt_arch
# overrides it for any other architecture.
__docker_arch_by_fact:
x86_64: amd64
aarch64: arm64
+4 -2
View File
@@ -68,10 +68,12 @@ Main entry point: `fail2ban` (everything), `fail2ban_install`, `fail2ban_validat
## Notes
- Each service owns `jail.d/<name>.local`, so one play cannot overwrite another service's jail. `jail.local` only holds `fail2ban_jails`.
- `fail2ban_ignoreip` lives in the `[DEFAULT]` section of `jail.local`, so it also applies to the jails that `service_jail` writes to `jail.d`. The exemption only exists once the main entry point has written `jail.local` on that host: `service_jail` does not read `fail2ban_ignoreip`, so a host that uses only `service_jail` has none. The first run after upgrading to a release with it adds the `[DEFAULT]` section and restarts Fail2Ban once.
- `fail2ban_ignoreip` lives in the `[DEFAULT]` section of `jail.local`, so it also applies to the jails that `service_jail` writes to `jail.d`. The exemption only exists once the main entry point has written `jail.local` on that host: `service_jail` does not read `fail2ban_ignoreip`, so a host that uses only `service_jail` has none.
- `fail2ban_ignoreip` replaces an `ignoreip` set in `jail.conf` or `jail.d/*.conf`, which Fail2Ban reads before `jail.local`; a `jail.d/*.local` file is read after it and can still override it for one jail. Entries must not contain whitespace, `;` or `%` (a `;` after whitespace starts a comment in Fail2Ban's config files and a `%` is interpolation syntax).
- Prefer IP addresses and CIDR networks in `fail2ban_ignoreip`. Fail2Ban resolves a hostname when the jail starts, and a failed lookup leaves that entry ineffective with only a log warning. The validation of `fail2ban_ignoreip` runs under the `fail2ban_validate` tag, so `--tags fail2ban_configure` skips it.
- Changing `jail.local` restarts Fail2Ban, which drops the in-memory ban list. Service jails only trigger a reload.
- Changing `jail.local` or a service jail reloads Fail2Ban instead of restarting it. A restart stops every jail, which flushes its bans out of the firewall until they are restored from the database, and forgets failures counted toward `maxretry`; a reload applies the new settings to the running jails. When the whole role runs, the reload comes after `fail2ban-client -t`.
- What a reload does not do, compared with the restart it replaces (read from the Fail2Ban 1.1.0 source, not run here): it does not unban an address that a widened `fail2ban_ignoreip` now covers (only a restart skips ignored addresses when it restores bans, so run `fail2ban-client unban <address>` to release one at once, or wait for the ban to expire); it does not change bans that already exist when `bantime` changes; and it does not apply server-level settings (`loglevel`, `dbfile`, `socket`, `pidfile`), which this role does not write. A changed `backend` restarts that jail by itself.
- With `--tags fail2ban_configure` only, `fail2ban-client -t` does not run before the reload; the reload (`fail2ban-client reload` in the upstream unit) still rejects a bad configuration and leaves the running daemon alone.
- `fail2ban-client -t` runs on every invocation of both entry points, not only when a file changed, so a broken file fails every run until fixed. It also runs in check mode.
- `fail2ban_service_jail` and `fail2ban_service_filter` must be passed as a single templated expression so they stay mappings, not strings or lists.
- `no_log` is not used: the role handles no secrets.
+7 -11
View File
@@ -1,15 +1,11 @@
---
- name: Restart Fail2Ban
become: true
ansible.builtin.service:
name: fail2ban
state: restarted
# Service jails only add a jail.d file, so reload instead of restarting the
# daemon (a restart drops the in-memory ban list). state=reloaded starts the
# service if it is not running. The config test runs as a task in
# service_jail.yml, so a broken file fails every run instead of only the one
# that wrote it.
# The main entry point and service_jail both reload instead of restarting the daemon. A restart stops every jail, which flushes
# its bans out of the firewall (they stay in Fail2Ban's database and are restored when the jail starts again), so for a moment
# banned addresses are not blocked, and failures counted toward maxretry are forgotten. A reload applies the new settings to the
# running jails and does neither. state=reloaded starts the service if it is not running. The configuration test
# (`fail2ban-client -t`) runs as a task in service.yml and service_jail.yml, so a broken file fails every run of the full role
# instead of only the one that wrote it, and when the whole role runs it comes before this handler (with only the configure tag it
# does not, and the reload itself rejects a bad configuration).
- name: Reload Fail2Ban
become: true
ansible.builtin.systemd:
+1 -1
View File
@@ -41,7 +41,7 @@ argument_specs:
An empty list exempts nothing, loopback included. It must be a list of non-empty strings without whitespace,
semicolons or percent signs (entries are joined with spaces, a semicolon starts a comment and a percent sign is
interpolation syntax in Fail2Ban's config files); a plain string, a number or null is refused.
- Changing it rewrites jail.local, which restarts Fail2Ban.
- Changing it rewrites jail.local, which reloads Fail2Ban.
fail2ban_service:
type: dict
description:
@@ -0,0 +1,42 @@
---
# Runs after the idempotence check and before verify. Record the daemon's PID, ban an address, change a jail setting so jail.local
# is rewritten and the handler fires, and let verify prove the daemon was reloaded, not restarted. The PID is the discriminator:
# a restart starts a new process, a reload does not. The ban alone would not tell them apart, because Fail2Ban restores unexpired
# bans from its database when a jail starts. The PID goes to a file because verify is a separate play.
- name: Change a jail setting while an address is banned
hosts: all
gather_facts: false
tasks:
- name: Read the unit state of the Fail2Ban daemon
ansible.builtin.systemd:
name: fail2ban
register: fail2ban_side_effect_unit
- name: Keep the main PID for the verify step
ansible.builtin.copy:
content: "{{ fail2ban_side_effect_unit.status.MainPID }}\n"
dest: /run/fail2ban-molecule-mainpid
mode: "0644"
# 198.51.100.0/24 is TEST-NET-2 (RFC 5737), outside the 192.0.2.0/24 the converge step ignores.
- name: Ban a documentation address on the sshd jail
ansible.builtin.command: fail2ban-client set sshd banip 198.51.100.77
changed_when: true
- name: Rewrite jail.local with a different maxretry
ansible.builtin.include_role:
name: mortis.kamino.fail2ban
vars:
fail2ban_ignoreip:
- 127.0.0.1/8
- "::1"
- 192.0.2.0/24
fail2ban_jails:
- name: sshd
enabled: true
port: ssh
filter: sshd
backend: systemd
maxretry: 4
bantime: "1h"
findtime: "10m"
@@ -83,3 +83,33 @@
loop: "{{ fail2ban_verify_ignoreip.results }}"
loop_control:
label: "{{ item.item }}"
# side_effect.yml recorded the daemon's PID, banned an address and rewrote jail.local with maxretry 4. The new maxretry must be
# active and the ban still in force. The PID must be unchanged: that is what tells a reload from a restart (a restart would
# have restored the ban from the database too, so the ban alone proves nothing about it).
- name: Ask the daemon for the sshd maxretry and its banned addresses
ansible.builtin.command: "fail2ban-client get sshd {{ item }}"
loop:
- maxretry
- banip
register: fail2ban_verify_reload
changed_when: false
- name: Read the PID recorded before the rewrite
ansible.builtin.slurp:
src: /run/fail2ban-molecule-mainpid
register: fail2ban_verify_pid_before
- name: Read the unit state of the Fail2Ban daemon now
ansible.builtin.systemd:
name: fail2ban
register: fail2ban_verify_unit
- name: The new maxretry is active, the ban is in force and the daemon was not restarted
ansible.builtin.assert:
that:
- "fail2ban_verify_reload.results[0].stdout | trim == '4'"
- "'198.51.100.77' in fail2ban_verify_reload.results[1].stdout"
- "(fail2ban_verify_pid_before.content | b64decode | trim) != '0'"
- "(fail2ban_verify_pid_before.content | b64decode | trim) == (fail2ban_verify_unit.status.MainPID | string)"
quiet: true
+1 -1
View File
@@ -7,4 +7,4 @@
owner: root
group: root
mode: "0600"
notify: Restart Fail2Ban
notify: Reload Fail2Ban
+2 -2
View File
@@ -16,8 +16,8 @@
enabled: "{{ fail2ban_service.enabled | default(true) }}"
state: "{{ fail2ban_service.state | default('started') }}"
# Handlers run at the end of the play; flush so the restart happens before the
# jail check below.
# Handlers run at the end of the play; flush so the reload happens after the
# configuration test above and before the jail check below.
- name: Apply pending Fail2Ban handlers
ansible.builtin.meta: flush_handlers
+7 -2
View File
@@ -53,6 +53,10 @@ Ubuntu 24.04 (noble), the image the molecule scenario runs on. The role uses `an
| `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_docker_prune_keep_per_repository` | `0` (off) | Newest image IDs kept per repository by the weekly and pressure prunes; every other image no container uses is removed. A multi-tag image counts once. |
| `gitea_runner_docker_prune_disk_threshold_percent` | `0` (off) | Use % of the Docker root's filesystem above which the pressure prune runs the count prune and a capped builder prune, behind the job gate. 1 to 99; needs the count above 0. |
| `gitea_runner_docker_prune_disk_check_schedule` | `hourly` | `OnCalendar` of the pressure prune timer. |
| `gitea_runner_docker_prune_builder_keep_storage` | `10GB` | `--keep-storage` of the builder prune under pressure. |
| `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. |
@@ -86,7 +90,7 @@ Change the registration scope of a registered runner: set `gitea_runner_registra
## 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.
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, the count prune and the disk check against a stub `docker` CLI, turning the pressure prune off, 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
@@ -95,6 +99,7 @@ The `default` molecule scenario runs without a Gitea server and without Docker:
- 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 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, the pressure units and the prune scripts. 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 pressure prune (`gitea-runner-docker-prune-pressure.{service,timer}`) runs once per check while usage is above the threshold; it has no low watermark, so usage that stays high needs a smaller count or a larger disk. A threshold set back to `0` stops its timer and removes its units and the disk check script. The age prunes and the count prune both apply: an image either one removes is gone.
- The play fails when `gitea-runner` is not `active` after start.
- `no_log` covers the token mint, the token fact and the registration command.
+6
View File
@@ -35,6 +35,12 @@ 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
# Newest image IDs kept per repository by the weekly and pressure prunes; 0 = off.
gitea_runner_docker_prune_keep_per_repository: 0
# Use % of the Docker root's filesystem above which the pressure prune runs; 0 = off. Needs the count.
gitea_runner_docker_prune_disk_threshold_percent: 0
gitea_runner_docker_prune_disk_check_schedule: hourly
gitea_runner_docker_prune_builder_keep_storage: 10GB
# Optional extra mounts
# gitea_runner_container_volumes:
@@ -0,0 +1,18 @@
#!/bin/sh
# Exit 0 when the filesystem holding the Docker root is more than $1 percent full (the pressure
# prune may run), 1 to skip. Every failure skips: the prune must not run when the state is unknown.
threshold="$1"
case "$threshold" in
'' | *[!0-9]*) echo "invalid threshold '$threshold'"; exit 1 ;;
esac
root=$(/usr/bin/docker info --format '{{.DockerRootDir}}') || { echo "docker info failed"; exit 1; }
use=$(df -P "$root" | awk 'NR == 2 { sub(/%$/, "", $5); print $5 }')
case "$use" in
'' | *[!0-9]*) echo "cannot read the use of '$root'"; exit 1 ;;
esac
if [ "$use" -gt "$threshold" ]; then
echo "$root is $use% full, above $threshold%: pruning"
exit 0
fi
echo "$root is $use% full, not above $threshold%: skipping the prune"
exit 1
+58
View File
@@ -0,0 +1,58 @@
#!/bin/sh
# Keep the newest $1 image IDs of each repository, by creation time, and remove every other image
# no container uses, dangling ones included. An image ID counts once however many tags it has, and
# one kept by any of its repositories stays. A failed listing exits non-zero and removes nothing.
keep="$1"
case "$keep" in
'' | *[!0-9]* | 0*) echo "invalid count '$keep'"; exit 2 ;;
esac
images=$(/usr/bin/docker image ls --no-trunc --format '{{.ID}} {{.Repository}} {{.CreatedAt}}') ||
{ echo "docker image ls failed"; exit 1; }
containers=$(/usr/bin/docker ps --all --quiet --no-trunc) || { echo "docker ps failed"; exit 1; }
used=""
if [ -n "$containers" ]; then
# shellcheck disable=SC2086 # one argument per container ID
used=$(/usr/bin/docker container inspect --format '{{.Image}}' $containers) ||
{ echo "cannot read the images of the containers"; exit 1; }
fi
# CreatedAt is local time with an offset ("2026-01-05 10:00:00 +0100 CET"): compare it as epoch
# seconds, or a change of offset would misorder the images.
table=$(printf '%s\n' "$images" | while read -r id repo day time offset _; do
[ -n "$id" ] || continue
created=$(date -d "$day $time $offset" +%s) || exit 1
echo "$created $id $repo"
done) || { echo "cannot parse the creation time of an image"; exit 1; }
# Lines in: "used <id>", then "image <created> <id> <repo>", newest first within a repository.
# Lines out: "<number of references> <id>" for each image to remove.
remove=$({
printf '%s\n' "$used" | sed -n 's/^./used &/p'
printf '%s\n' "$table" | LC_ALL=C sort -k3,3 -k1,1nr -k2,2 | sed -n 's/^./image &/p'
} | awk -v keep="$keep" '
$1 == "used" { used[$2] = 1; next }
{
id = $3; repo = $4; refs[id]++
if (!(id in seen)) { seen[id] = 1; order[++n] = id }
if (repo != "<none>" && !((repo, id) in counted)) {
counted[repo, id] = 1
if (++slots[repo] <= keep) kept[id] = 1
}
}
END { for (i = 1; i <= n; i++) if (!(order[i] in kept) && !(order[i] in used)) print refs[order[i]], order[i] }
')
# An image with several references is refused by a plain rmi of its ID, so it needs --force.
printf '%s\n' "$remove" | {
rc=0
while read -r refs id; do
[ -n "$id" ] || continue
force=""
[ "$refs" -gt 1 ] && force="--force"
echo "removing image $id"
# shellcheck disable=SC2086 # $force is empty or one word
/usr/bin/docker rmi $force "$id" || rc=1
done
exit "$rc"
}
@@ -231,6 +231,38 @@ argument_specs:
- >-
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_docker_prune_keep_per_repository:
type: int
default: 0
description:
- >-
Newest image IDs kept per repository, by creation time; C(0) turns the count prune off. Above C(0) the weekly
prune and the pressure prune remove every other image no container uses, dangling images included. An image
with several tags counts once, and one kept by any of its repositories stays. Only read when
C(gitea_runner_docker_prune_enabled) is true.
gitea_runner_docker_prune_disk_threshold_percent:
type: int
default: 0
description:
- >-
Use, in percent, of the filesystem holding the Docker root above which
C(gitea-runner-docker-prune-pressure.service) runs the count prune and a builder prune capped at
C(gitea_runner_docker_prune_builder_keep_storage), behind the same job gate as the weekly prune. C(0) turns it
off, and setting it back to C(0) stops the timer and removes its units. C(1) to C(99), and above C(0) only with
C(gitea_runner_docker_prune_keep_per_repository) above C(0), asserted at role start when the prune is enabled.
gitea_runner_docker_prune_disk_check_schedule:
type: str
default: hourly
description:
- >-
C(OnCalendar) value of the pressure prune timer. Same check as C(gitea_runner_docker_prune_schedule).
gitea_runner_docker_prune_builder_keep_storage:
type: str
default: 10GB
description:
- >-
C(--keep-storage) of the builder prune under disk pressure: the build cache kept. A number with an optional
C(B), C(KB), C(MB), C(GB) or C(TB), asserted at role start when the prune is enabled.
gitea_runner_container_volumes:
type: list
elements: str
@@ -41,6 +41,8 @@ provisioner:
- /cache:/cache
gitea_runner_docker_prune_enabled: true
gitea_runner_docker_prune_job_max_age: 3600
gitea_runner_docker_prune_keep_per_repository: 2
gitea_runner_docker_prune_disk_threshold_percent: 90
verifier:
name: ansible
scenario:
@@ -13,6 +13,10 @@
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_docker_prune_keep_per_repository: "{{ gitea_runner_test_refused.vars.gitea_runner_docker_prune_keep_per_repository | default(2) }}"
gitea_runner_docker_prune_disk_threshold_percent: "{{ gitea_runner_test_refused.vars.gitea_runner_docker_prune_disk_threshold_percent | default(90) }}"
gitea_runner_docker_prune_disk_check_schedule: "{{ gitea_runner_test_refused.vars.gitea_runner_docker_prune_disk_check_schedule | default('hourly') }}"
gitea_runner_docker_prune_builder_keep_storage: "{{ gitea_runner_test_refused.vars.gitea_runner_docker_prune_builder_keep_storage | default('10GB') }}"
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
+261 -4
View File
@@ -85,7 +85,7 @@
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
- name: The prune timer is armed and the service carries the gate, the ages and the count
vars:
gitea_runner_test_prune_text: "{{ gitea_runner_test_prune_service.content | b64decode }}"
ansible.builtin.assert:
@@ -95,6 +95,30 @@
- "'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"
- "'ExecStart=-/usr/local/sbin/gitea-runner-docker-prune-keep 2' in gitea_runner_test_prune_text"
quiet: true
- name: Ask systemd about the pressure prune timer
ansible.builtin.systemd:
name: gitea-runner-docker-prune-pressure.timer
register: gitea_runner_test_pressure_timer
- name: Read the pressure prune service
ansible.builtin.slurp:
src: /etc/systemd/system/gitea-runner-docker-prune-pressure.service
register: gitea_runner_test_pressure_service
- name: The pressure timer is armed and its service runs behind the gate and the disk check
vars:
gitea_runner_test_pressure_text: "{{ gitea_runner_test_pressure_service.content | b64decode }}"
ansible.builtin.assert:
that:
- gitea_runner_test_pressure_timer.status.ActiveState == 'active'
- gitea_runner_test_pressure_timer.status.UnitFileState == 'enabled'
- "'ExecCondition=/usr/local/sbin/gitea-runner-docker-prune-gate 3600' in gitea_runner_test_pressure_text"
- "'ExecCondition=/usr/local/sbin/gitea-runner-docker-prune-disk-check 90' in gitea_runner_test_pressure_text"
- "'ExecStart=-/usr/local/sbin/gitea-runner-docker-prune-keep 2' in gitea_runner_test_pressure_text"
- "'ExecStart=-/usr/bin/docker builder prune --force --keep-storage 10GB' in gitea_runner_test_pressure_text"
quiet: true
# The prune gate script against a stub docker CLI: no container, a young one (a job may be
@@ -171,6 +195,169 @@
loop_control:
loop_var: gitea_runner_test_path
# The count prune and the disk check against a stub docker CLI: it answers from the files below,
# records `rmi` calls, and a fail-<command> file makes that command fail. With N = 2, app keeps
# a1 (two tags: counted twice it would push a2 out), a2 and a4 (used by c1); lib keeps m1 though
# it is third in old; s3 (two tags) goes with --force; d1 goes, d2 (used by c2) stays.
- name: Verify the count prune and the disk check
hosts: all
gather_facts: false
vars:
gitea_runner_test_dir: /tmp/molecule-docker
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: Create the stub's directory
ansible.builtin.file:
path: "{{ gitea_runner_test_dir }}"
state: directory
mode: "0755"
- name: Write the stub docker CLI
ansible.builtin.copy:
dest: /usr/bin/docker
mode: "0755"
content: |
#!/bin/sh
d={{ gitea_runner_test_dir }}
[ -e "$d/fail-$1" ] && exit 1
case "$1" in
image) cat "$d/images" ;;
ps) cat "$d/containers" ;;
container)
shift 4
for c in "$@"; do grep "^$c " "$d/container-images" | cut -d' ' -f2; done ;;
info) cat "$d/root" ;;
rmi) echo "$*" >> "$d/rmi" ;;
*) exit 1 ;;
esac
- name: Write the stub's images and containers
ansible.builtin.copy:
dest: "{{ gitea_runner_test_dir }}/{{ gitea_runner_test_fixture.name }}"
mode: "0644"
content: "{{ gitea_runner_test_fixture.content }}"
loop:
- name: images
content: |
sha256:a1 app 2026-01-05 10:00:00 +0000 UTC
sha256:a1 app 2026-01-05 10:00:00 +0000 UTC
sha256:a2 app 2026-01-04 10:00:00 +0000 UTC
sha256:a3 app 2026-01-03 10:00:00 +0000 UTC
sha256:a4 app 2026-01-02 10:00:00 +0000 UTC
sha256:a5 app 2026-01-01 10:00:00 +0000 UTC
sha256:m1 lib 2026-01-01 10:00:00 +0000 UTC
sha256:o1 old 2026-01-03 10:00:00 +0000 UTC
sha256:o2 old 2026-01-02 10:00:00 +0000 UTC
sha256:m1 old 2026-01-01 10:00:00 +0000 UTC
sha256:s1 stale 2026-01-03 10:00:00 +0000 UTC
sha256:s2 stale 2026-01-02 10:00:00 +0000 UTC
sha256:s3 stale 2026-01-01 10:00:00 +0000 UTC
sha256:s3 stale 2026-01-01 10:00:00 +0000 UTC
sha256:d1 <none> 2026-01-01 10:00:00 +0000 UTC
sha256:d2 <none> 2026-01-01 10:00:00 +0000 UTC
- name: containers
content: |
c1
c2
- name: container-images
content: |
c1 sha256:a4
c2 sha256:d2
loop_control:
loop_var: gitea_runner_test_fixture
label: "{{ gitea_runner_test_fixture.name }}"
- name: Run each count prune case
ansible.builtin.shell:
cmd: |
cd {{ gitea_runner_test_dir }} && rm -f rmi fail-*
{{ ('touch fail-' ~ gitea_runner_test_case.fail) if gitea_runner_test_case.fail else ':' }}
/usr/local/sbin/gitea-runner-docker-prune-keep {{ gitea_runner_test_case.keep }} >&2
rc=$?
[ -e rmi ] && LC_ALL=C sort rmi
exit "$rc"
loop:
- {name: keep-two, keep: 2, fail: "", rc: 0, rmi: [rmi --force sha256:s3, rmi sha256:a3, rmi sha256:a5, rmi sha256:d1]}
- {name: image-ls-fails, keep: 2, fail: image, rc: 1, rmi: []}
- {name: ps-fails, keep: 2, fail: ps, rc: 1, rmi: []}
- {name: inspect-fails, keep: 2, fail: container, rc: 1, rmi: []}
- {name: zero-count, keep: 0, fail: "", rc: 2, rmi: []}
loop_control:
loop_var: gitea_runner_test_case
label: "{{ gitea_runner_test_case.name }}"
register: gitea_runner_test_keep
# The rc and the rmi calls are the result under test; the next task asserts them.
failed_when: false
changed_when: false
- name: The count prune removed exactly the expected images, and nothing when a listing failed
ansible.builtin.assert:
that:
- item.rc == item.gitea_runner_test_case.rc
- item.stdout_lines == item.gitea_runner_test_case.rmi
fail_msg: "case {{ item.gitea_runner_test_case.name }}: rc {{ item.rc }}, rmi {{ item.stdout_lines }}, output {{ item.stderr }}"
quiet: true
loop: "{{ gitea_runner_test_keep.results }}"
loop_control:
label: "{{ item.gitea_runner_test_case.name }}"
# The above and at-use cases set the threshold one below and equal to the root's use, read
# just before (df rounds up, so a used root is at least 1%); /run/lock is never above 50%.
- name: Run each disk check case
ansible.builtin.shell:
cmd: |
cd {{ gitea_runner_test_dir }} && rm -f fail-*
{{ ('touch fail-' ~ gitea_runner_test_case.fail) if gitea_runner_test_case.fail else ':' }}
echo '{{ gitea_runner_test_case.root }}' > root
threshold={{ gitea_runner_test_case.threshold }}
{% if gitea_runner_test_case.threshold in ['below-use', 'use'] %}
df -P / > df-root && use=$(awk 'NR == 2 { sub(/%$/, "", $5); print $5 }' df-root)
threshold=$((use - {{ 1 if gitea_runner_test_case.threshold == 'below-use' else 0 }}))
{% endif %}
/usr/local/sbin/gitea-runner-docker-prune-disk-check "$threshold"
loop:
- {name: above, root: /, threshold: below-use, fail: "", rc: 0}
- {name: below, root: /run/lock, threshold: 50, fail: "", rc: 1, out: "% full, not above 50%: skipping the prune"}
- {name: at-use, root: /, threshold: use, fail: "", rc: 1, out: "not above"}
- {name: info-fails, root: /, threshold: below-use, fail: info, rc: 1}
- {name: root-missing, root: /nonexistent, threshold: 1, fail: "", rc: 1}
loop_control:
loop_var: gitea_runner_test_case
label: "{{ gitea_runner_test_case.name }}"
register: gitea_runner_test_pressure
# The rc is the result under test; the next task asserts it.
failed_when: false
changed_when: false
- name: The disk check let the pressure prune run only above the threshold
ansible.builtin.assert:
that:
- item.rc == item.gitea_runner_test_case.rc
- item.gitea_runner_test_case.out | default('') in item.stdout
fail_msg: "case {{ item.gitea_runner_test_case.name }}: rc {{ item.rc }}, output {{ item.stdout }} {{ item.stderr }}"
quiet: true
loop: "{{ gitea_runner_test_pressure.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, "{{ gitea_runner_test_dir }}"]
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
@@ -237,10 +424,25 @@
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
expect: gitea_runner_docker_prune_schedule must be a plain OnCalendar value
- name: prune age without a unit
vars: {gitea_runner_docker_prune_image_age: "168"}
expect: plain OnCalendar value
expect: the two ages a number with s, m or h
- name: negative prune count
vars: {gitea_runner_docker_prune_keep_per_repository: -1}
expect: gitea_runner_docker_prune_keep_per_repository must be 0 (off) or more
- name: disk threshold of 100
vars: {gitea_runner_docker_prune_disk_threshold_percent: 100}
expect: gitea_runner_docker_prune_disk_threshold_percent must be 0 (off) or 1 to 99
- name: disk check schedule with a newline
vars: {gitea_runner_docker_prune_disk_check_schedule: "hourly\nExecStartPre=/bin/false"}
expect: gitea_runner_docker_prune_disk_check_schedule must be a plain OnCalendar value
- name: builder keep-storage with an extra argument
vars: {gitea_runner_docker_prune_builder_keep_storage: "10GB --all"}
expect: gitea_runner_docker_prune_builder_keep_storage must be a number
- name: disk threshold without a count
vars: {gitea_runner_docker_prune_keep_per_repository: 0}
expect: needs gitea_runner_docker_prune_keep_per_repository above 0
- name: molecule tooling without a requirements file
vars: {gitea_runner_molecule_enabled: true}
expect: gitea_runner_collections_requirements_file must name
@@ -351,6 +553,57 @@
- gitea_runner_test_unit.status.ActiveState == 'active'
quiet: true
# A threshold of 0 removes the pressure units; the run after it, with the scenario's inputs,
# puts them back, so the remove path below still has them to remove.
- name: Verify turning the pressure prune off
hosts: all
gather_facts: false
tasks:
- name: Run the role with the disk threshold at 0
ansible.builtin.include_role:
name: mortis.kamino.gitea_runner
vars:
gitea_runner_docker_prune_disk_threshold_percent: 0
- name: Stat the pressure units and script
ansible.builtin.stat:
path: "{{ gitea_runner_test_path }}"
loop:
- /etc/systemd/system/gitea-runner-docker-prune-pressure.service
- /etc/systemd/system/gitea-runner-docker-prune-pressure.timer
- /usr/local/sbin/gitea-runner-docker-prune-disk-check
loop_control:
loop_var: gitea_runner_test_path
register: gitea_runner_test_pressure_off
- name: Ask systemd about the pressure timer after turning it off
ansible.builtin.systemd:
name: gitea-runner-docker-prune-pressure.timer
register: gitea_runner_test_pressure_timer_off
# The module errors for a unit that no longer exists, which is also a pass.
failed_when: false
- name: The pressure units are gone and the timer is not active
ansible.builtin.assert:
that:
- gitea_runner_test_pressure_off.results | map(attribute='stat') | map(attribute='exists') | select | list | length == 0
- gitea_runner_test_pressure_timer_off.status.ActiveState | default('inactive') != 'active'
quiet: true
- name: Run the role again with the scenario's inputs
ansible.builtin.include_role:
name: mortis.kamino.gitea_runner
- name: Ask systemd about the pressure timer after turning it on again
ansible.builtin.systemd:
name: gitea-runner-docker-prune-pressure.timer
register: gitea_runner_test_pressure_timer_on
- name: The pressure timer is armed again
ansible.builtin.assert:
that: gitea_runner_test_pressure_timer_on.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
@@ -376,6 +629,10 @@
- /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/gitea-runner-docker-prune-pressure.service
- /etc/systemd/system/gitea-runner-docker-prune-pressure.timer
- /usr/local/sbin/gitea-runner-docker-prune-keep
- /usr/local/sbin/gitea-runner-docker-prune-disk-check
- /etc/systemd/system/multi-user.target.wants/gitea-runner.service
loop_control:
loop_var: gitea_runner_test_path
@@ -384,7 +641,7 @@
- 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: [gitea-runner, gitea-runner-docker-prune.timer, gitea-runner-docker-prune-pressure.timer]
loop_control:
loop_var: gitea_runner_test_unit_name
register: gitea_runner_test_after
+123 -1
View File
@@ -45,6 +45,18 @@
when: gitea_runner_docker_prune_enabled | bool
tags: [gitea_runner, prune]
# Used by the weekly and pressure services when gitea_runner_docker_prune_keep_per_repository > 0.
- name: Install Docker prune count script
become: true
ansible.builtin.copy:
src: gitea-runner-docker-prune-keep
dest: /usr/local/sbin/gitea-runner-docker-prune-keep
owner: root
group: root
mode: "0755"
when: gitea_runner_docker_prune_enabled | bool
tags: [gitea_runner, prune]
- name: Install Docker prune service
become: true
ansible.builtin.copy:
@@ -65,6 +77,9 @@
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
{% if gitea_runner_docker_prune_keep_per_repository | int > 0 %}
ExecStart=-/usr/local/sbin/gitea-runner-docker-prune-keep {{ gitea_runner_docker_prune_keep_per_repository }}
{% endif %}
register: gitea_runner_prune_service
when: gitea_runner_docker_prune_enabled | bool
tags: [gitea_runner, prune]
@@ -91,13 +106,108 @@
when: gitea_runner_docker_prune_enabled | bool
tags: [gitea_runner, prune]
# Pressure path: above the disk threshold, the count prune and a capped builder prune run behind
# the same gate. There is no low watermark: if usage stays high, the count or the disk needs a human.
# The builder cache is capped because job containers share the host's docker.sock by default.
- name: Install the pressure prune when a disk threshold is set
when:
- gitea_runner_docker_prune_enabled | bool
- gitea_runner_docker_prune_disk_threshold_percent | int > 0
tags: [gitea_runner, prune]
block:
- name: Install Docker disk check script
become: true
ansible.builtin.copy:
src: gitea-runner-docker-prune-disk-check
dest: /usr/local/sbin/gitea-runner-docker-prune-disk-check
owner: root
group: root
mode: "0755"
- name: Install Docker pressure prune service
become: true
ansible.builtin.copy:
dest: /etc/systemd/system/gitea-runner-docker-prune-pressure.service
owner: root
group: root
mode: "0644"
content: |
[Unit]
Description=Prune Docker images when the disk of the Gitea runner host is filling up
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 }}
ExecCondition=/usr/local/sbin/gitea-runner-docker-prune-disk-check {{ gitea_runner_docker_prune_disk_threshold_percent }}
ExecStart=-/usr/local/sbin/gitea-runner-docker-prune-keep {{ gitea_runner_docker_prune_keep_per_repository }}
ExecStart=-/usr/bin/docker builder prune --force --keep-storage {{ gitea_runner_docker_prune_builder_keep_storage }}
register: __gitea_runner_prune_pressure_service
- name: Install Docker pressure prune timer
become: true
ansible.builtin.copy:
dest: /etc/systemd/system/gitea-runner-docker-prune-pressure.timer
owner: root
group: root
mode: "0644"
content: |
[Unit]
Description=Disk check for the Docker pressure prune on the Gitea runner host
[Timer]
OnCalendar={{ gitea_runner_docker_prune_disk_check_schedule }}
Persistent=true
RandomizedDelaySec=2m
[Install]
WantedBy=timers.target
register: __gitea_runner_prune_pressure_timer
# A threshold set back to 0 turns the pressure path off: the units go, so nothing is left armed.
- name: Stop the Docker pressure prune timer when the disk threshold is 0
become: true
ansible.builtin.systemd:
name: gitea-runner-docker-prune-pressure.timer
state: stopped
enabled: false
register: __gitea_runner_prune_pressure_stop
failed_when:
- __gitea_runner_prune_pressure_stop.failed | default(false)
- "'Could not find the requested service' not in (__gitea_runner_prune_pressure_stop.msg | default(''))"
when:
- gitea_runner_docker_prune_enabled | bool
- gitea_runner_docker_prune_disk_threshold_percent | int == 0
tags: [gitea_runner, prune]
- name: Remove the Docker pressure prune units when the disk threshold is 0
become: true
ansible.builtin.file:
path: "{{ gitea_runner_prune_pressure_file }}"
state: absent
loop:
- /etc/systemd/system/gitea-runner-docker-prune-pressure.timer
- /etc/systemd/system/gitea-runner-docker-prune-pressure.service
- /usr/local/sbin/gitea-runner-docker-prune-disk-check
loop_control:
loop_var: gitea_runner_prune_pressure_file
register: __gitea_runner_prune_pressure_removed
when:
- gitea_runner_docker_prune_enabled | bool
- gitea_runner_docker_prune_disk_threshold_percent | int == 0
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
- >-
gitea_runner_prune_service is changed or gitea_runner_prune_timer is changed
or __gitea_runner_prune_pressure_service is changed or __gitea_runner_prune_pressure_timer is changed
or __gitea_runner_prune_pressure_removed is changed
tags: [gitea_runner, prune]
# Not in check mode: on the first run the unit files above are only simulated, so systemd
@@ -112,3 +222,15 @@
- gitea_runner_docker_prune_enabled | bool
- not ansible_check_mode
tags: [gitea_runner, prune]
- name: Enable the Docker pressure prune timer
become: true
ansible.builtin.systemd:
name: gitea-runner-docker-prune-pressure.timer
enabled: true
state: "{{ 'restarted' if __gitea_runner_prune_pressure_timer is changed else 'started' }}"
when:
- gitea_runner_docker_prune_enabled | bool
- gitea_runner_docker_prune_disk_threshold_percent | int > 0
- not ansible_check_mode
tags: [gitea_runner, prune]
+17 -4
View File
@@ -15,12 +15,17 @@
- "'Could not find the requested service' not in (gitea_runner_stop.msg | default(''))"
tags: [gitea_runner, remove]
- name: Stop the Docker prune timer
- name: Stop the Docker prune timers
become: true
ansible.builtin.systemd:
name: gitea-runner-docker-prune.timer
name: "{{ gitea_runner_prune_timer_name }}"
state: stopped
enabled: false
loop:
- gitea-runner-docker-prune.timer
- gitea-runner-docker-prune-pressure.timer
loop_control:
loop_var: gitea_runner_prune_timer_name
register: gitea_runner_prune_stop
failed_when:
- gitea_runner_prune_stop.failed | default(false)
@@ -35,15 +40,23 @@
loop:
- gitea-runner-docker-prune.timer
- gitea-runner-docker-prune.service
- gitea-runner-docker-prune-pressure.timer
- gitea-runner-docker-prune-pressure.service
loop_control:
loop_var: gitea_runner_prune_unit
tags: [gitea_runner, remove]
- name: Remove the Docker prune gate script
- name: Remove the Docker prune scripts
become: true
ansible.builtin.file:
path: /usr/local/sbin/gitea-runner-docker-prune-gate
path: "/usr/local/sbin/{{ gitea_runner_prune_script }}"
state: absent
loop:
- gitea-runner-docker-prune-gate
- gitea-runner-docker-prune-keep
- gitea-runner-docker-prune-disk-check
loop_control:
loop_var: gitea_runner_prune_script
tags: [gitea_runner, remove]
- name: Remove systemd unit
+44
View File
@@ -36,6 +36,50 @@
quiet: true
when: gitea_runner_docker_prune_enabled | bool
- name: Validate the Docker prune count
ansible.builtin.assert:
that: gitea_runner_docker_prune_keep_per_repository | int >= 0
fail_msg: gitea_runner_docker_prune_keep_per_repository must be 0 (off) or more.
quiet: true
when: gitea_runner_docker_prune_enabled | bool
- name: Validate the Docker prune disk threshold
ansible.builtin.assert:
that:
- gitea_runner_docker_prune_disk_threshold_percent | int >= 0
- gitea_runner_docker_prune_disk_threshold_percent | int <= 99
fail_msg: gitea_runner_docker_prune_disk_threshold_percent must be 0 (off) or 1 to 99.
quiet: true
when: gitea_runner_docker_prune_enabled | bool
# Same character set as the weekly schedule.
- name: Validate the Docker prune disk check schedule
ansible.builtin.assert:
that: gitea_runner_docker_prune_disk_check_schedule is match('^[A-Za-z0-9 :*,./~-]+$')
fail_msg: gitea_runner_docker_prune_disk_check_schedule must be a plain OnCalendar value (no newline or %).
quiet: true
when: gitea_runner_docker_prune_enabled | bool
# A subset of the units Docker accepts for --keep-storage.
- name: Validate the Docker builder keep-storage size
ansible.builtin.assert:
that: gitea_runner_docker_prune_builder_keep_storage is match('^[0-9]+(B|KB|MB|GB|TB)?$')
fail_msg: >-
gitea_runner_docker_prune_builder_keep_storage must be a number with an optional B, KB, MB, GB or TB (e.g. 10GB).
quiet: true
when: gitea_runner_docker_prune_enabled | bool
- name: Require a count for the pressure prune
ansible.builtin.assert:
that: >-
gitea_runner_docker_prune_disk_threshold_percent | int == 0
or gitea_runner_docker_prune_keep_per_repository | int > 0
fail_msg: >-
gitea_runner_docker_prune_disk_threshold_percent needs gitea_runner_docker_prune_keep_per_repository above 0:
the pressure prune removes images by that count.
quiet: true
when: gitea_runner_docker_prune_enabled | bool
- name: Require the collections requirements file for the molecule tooling
ansible.builtin.assert:
that:
+26 -1
View File
@@ -34,6 +34,7 @@ templating error instead of the role's own message.
| `system_baseline_apt_periodic_settings` | from profile | no | Keys for `20auto-upgrades` |
| `system_baseline_unattended_upgrade_settings` | from profile | no | Keys for `50unattended-upgrades` |
| `system_baseline_unattended_upgrade_origins` | from profile | no | Pinned `Origins-Pattern` entries; `[]` keeps the distribution default (see below) |
| `system_baseline_unattended_upgrade_package_blacklist` | `[]` | no | Packages unattended-upgrades must not touch, as regular expressions (see below) |
| `system_baseline_sysctl_hardening` | from profile | no | List of `name` and `value` sysctl pairs |
| `system_baseline_secure_tmp_mounts` | from profile | no | Paths remounted as tmpfs with `noexec,nosuid,nodev` |
| `system_baseline_journal_max_use` | `200M` | no | Upper bound of the persistent journal (journald `SystemMaxUse`). |
@@ -58,7 +59,7 @@ system_baseline_profile_overrides:
Besides `main`, two task files are a supported interface, for a caller that drives its own reboot (for example a Kubernetes node patch flow that cordons and drains first). Their names, the fact name and the behaviour below follow the Collection's semantic versioning: changing them is a breaking change.
- `tasks_from: update`: apt update, upgrade, autoremove and autoclean, nothing else. It does not read `system_baseline_update`: calling the entry point is the request to update.
- `tasks_from: update`: apt update, upgrade, autoremove and autoclean, nothing else. It does not read `system_baseline_update`: calling the entry point is the request to update. In check mode it previews the upgrade; the main flow does not (see "Check mode").
- `tasks_from: reboot`: sets the fact `system_baseline_reboot_required` (bool, from `/var/run/reboot-required`) on Debian family hosts, then reboots when `system_baseline_reboot_if_required` is true and the fact is true. With `system_baseline_reboot_if_required: false` it only computes the fact. On other families the fact is not set, so read it with `default(false)`.
```yaml
@@ -119,6 +120,10 @@ system_baseline_tmux_windows:
`system_baseline_update: false` skips the package update of the main flow, for hosts patched by a separate, operator-run flow (for example a full upgrade with a rolling reboot). Everything else, unattended-upgrades included, still runs. The reboot check still runs as well, so set `system_baseline_reboot_if_required: false` too when that flow owns the reboot. Running the play with `--skip-tags update` skips the same task for one run only, and also the reboot.
## Check mode
In a dry run (`--check`) the main flow does not run the apt upgrade: a package that is only waiting for the next patch run, or a package cache older than an hour, is not drift, and the package module reports both as `changed`, so a scheduled dry run would flag every host whenever a package landed in between. The autoremove and autoclean step still runs, and is checked: a leftover package it would remove is reported as `changed`, on purpose. `apt-get autoclean` runs in this step in a real run, in the main flow and in the `update` entry point. The `update` entry point is unchanged: it is an explicit request to update, so in check mode it still previews the upgrade.
## Unattended-upgrades origins
A profile's `unattended_upgrade_origins` list pins the origins unattended-upgrades may install from. apt merges every file in `/etc/apt/apt.conf.d` and appends list entries across files, so a later file that only lists origins would widen the distribution's `50unattended-upgrades`, never narrow it. A non-empty list is therefore written to `/etc/apt/apt.conf.d/90unattended-upgrades-origins`, which sorts after `50unattended-upgrades`, clears `Unattended-Upgrade::Allowed-Origins` and `Unattended-Upgrade::Origins-Pattern` (apt's `#clear` directive) and sets only the listed patterns. The origin lists in `50unattended-upgrades` itself are not edited. An empty or missing list removes the drop-in.
@@ -129,6 +134,26 @@ A profile's `unattended_upgrade_origins` list pins the origins unattended-upgrad
- A file in `/etc/apt/apt.conf.d` that sorts after `90unattended-upgrades-origins` can still add origins, and so can `/etc/apt/apt.conf`, which apt reads after `apt.conf.d`.
- Check the merged result on a host with `apt-config dump | grep -E 'Unattended-Upgrade::(Origins-Pattern|Allowed-Origins)'`.
## Unattended-upgrades package blacklist
`system_baseline_unattended_upgrade_package_blacklist` keeps individual packages out of unattended-upgrades, for a host whose kernel or drivers must not change (for example one with hardware passthrough). Each entry is a regular expression matched against the package name, so `linux-image-.*` covers every kernel image; anchor an entry (`^name$`) when it must not match longer names too. A non-empty list is written to `/etc/apt/apt.conf.d/90unattended-upgrades-blacklist` as `Unattended-Upgrade::Package-Blacklist`. apt appends list entries across files, so the entries are added to those of `50unattended-upgrades`, which is not edited. An empty list removes the file. An entry may not hold a double quote, a backslash or a line break.
- Example for Proxmox VE hosts: packages that should only ever change through a deliberate `apt dist-upgrade` (Proxmox's documented way to update, because its packages add and remove dependencies). The `pve` profile already pins unattended-upgrades to Debian's origins, so these never come from the Proxmox repository through unattended-upgrades; the list keeps that true if the pin is ever removed or widened. Adjust it to the repositories you use:
```yaml
system_baseline_unattended_upgrade_package_blacklist:
- "^pve-.*" # pve-manager, pve-kernel-*, pve-qemu-kvm, pve-container ...
- "^libpve-.*"
- "^proxmox-.*" # proxmox-ve, proxmox-kernel-*, proxmox-backup-client ...
- "^qemu-server$"
- "^ceph.*"
- "^corosync$"
```
- Like the other unattended-upgrades settings, it is applied only when `unattended-upgrades` is in the profile's packages.
- This is unattended-upgrades only. The role's own apt upgrade (`update` tag, and the `update` entry point) is not limited by it; set `system_baseline_update: false` for a host that is patched by a separate flow.
- Check the merged result on a host with `apt-config dump | grep Package-Blacklist`.
## Notes
- The `pve` profile has no `ufw`; the `ubuntu_*` profiles install it and `fail2ban`.
+3
View File
@@ -230,5 +230,8 @@ system_baseline_apt_periodic_settings: "{{ system_baseline_profile.apt_periodic_
system_baseline_unattended_upgrade_settings: "{{ system_baseline_profile.unattended_upgrade_settings }}"
# default([]): a system_baseline_profiles written before this key existed keeps the distribution default.
system_baseline_unattended_upgrade_origins: "{{ system_baseline_profile.unattended_upgrade_origins | default([]) }}"
# Packages unattended-upgrades must not touch, on top of the profile: a per-host list, empty by default (see README, "Unattended-upgrades
# package blacklist"). Entries are regular expressions matched against the package name.
system_baseline_unattended_upgrade_package_blacklist: []
system_baseline_sysctl_hardening: "{{ system_baseline_profile.sysctl_hardening }}"
system_baseline_secure_tmp_mounts: "{{ system_baseline_profile.secure_tmp_mounts }}"
+17 -1
View File
@@ -102,6 +102,19 @@ argument_specs:
default: true
description:
- Reboot when C(/var/run/reboot-required) exists after the run.
system_baseline_unattended_upgrade_package_blacklist:
type: list
elements: str
default: []
description:
- >-
Packages unattended-upgrades must leave alone, for a host whose kernel or drivers must not change. Entries are regular
expressions matched against the package name, so C(linux-image-.*) covers every kernel image; anchor an entry (C(^name$))
when it must not match longer names too.
- >-
A non-empty list is written to C(/etc/apt/apt.conf.d/90unattended-upgrades-blacklist) as C(Unattended-Upgrade::Package-Blacklist).
apt appends list entries across files, so these are added to those of C(50unattended-upgrades). An empty list removes the file.
An entry may not hold a double quote, a backslash or a line break.
system_baseline_update:
type: bool
default: true
@@ -111,11 +124,14 @@ argument_specs:
separate flow; the reboot check still runs, so set C(system_baseline_reboot_if_required) as well when that flow also owns
the reboot.
- The C(update) entry point does not read it.
- In check mode the main flow skips the upgrade itself (a pending update is not drift); autoremove and autoclean are still checked.
update:
short_description: Update and upgrade apt packages
description:
- Runs an apt update, upgrade, autoremove and autoclean, and nothing else.
- Calling it is a request to update, so it does not read C(system_baseline_update), which only gates the main flow.
- >-
Calling it is a request to update, so it does not read C(system_baseline_update), which only gates the main flow. In check mode it
still previews the upgrade.
- >-
A supported entry point (C(tasks_from=update)) for a caller that drives its own reboot, for example a
Kubernetes node patch flow that drains the node first.
@@ -19,6 +19,21 @@
that: "'is invalid' in ansible_failed_result.msg | default('')"
quiet: true
# A quote, a null item and a bare string (not a list) each stop the run: the bare string would otherwise be split into one-character
# patterns, and the null item would become an empty pattern that matches every package.
- name: A bad package blacklist is refused
hosts: all
gather_facts: false
tasks:
- name: Refuse each bad value
ansible.builtin.include_tasks: tasks/refuse_blacklist.yml
vars:
system_baseline_refused_blacklist: "{{ item }}"
loop:
- ['bad"name']
- [null]
- linux-image-.*
- name: Converge the LXC profile
hosts: all
gather_facts: true
@@ -0,0 +1,18 @@
---
# One refusal: the role must stop on validation, before it changes anything, with a message that names the variable.
- name: Run the role with a bad package blacklist
block:
- name: Include system_baseline
ansible.builtin.include_role:
name: mortis.kamino.system_baseline
vars:
system_baseline_system_type: ubuntu_lxc
system_baseline_unattended_upgrade_package_blacklist: "{{ system_baseline_refused_blacklist }}"
- name: Unreachable when validation works
ansible.builtin.fail:
msg: system_baseline ran with an invalid package blacklist
rescue:
- name: The validation stopped the play
ansible.builtin.assert:
that: "'system_baseline_unattended_upgrade_package_blacklist must be' in ansible_failed_result.msg | default('')"
quiet: true
@@ -270,3 +270,84 @@
- system_baseline_verify_apt_config_restored.stdout_lines | select('match', 'Unattended-Upgrade::Allowed-Origins::\s') | list | length > 0
- system_baseline_verify_apt_config_restored.stdout is not search('origin=Debian')
quiet: true
# The package blacklist: written and parsed by apt as a list, left alone by a second run, removed by an empty list. Here and not in
# converge, because converge runs the default (empty) list.
- name: The unattended-upgrades package blacklist is written, kept and removed
hosts: all
gather_facts: false
vars:
system_baseline_verify_blacklist: ["linux-image-.*", "nvidia-.*"]
tasks:
- name: Run the unattended-upgrades tasks with a blacklist
ansible.builtin.include_role:
name: mortis.kamino.system_baseline
tasks_from: unattended_upgrades
vars:
system_baseline_system_type: ubuntu_lxc
system_baseline_unattended_upgrade_package_blacklist: "{{ system_baseline_verify_blacklist }}"
- name: Stat the blacklist drop-in
ansible.builtin.stat:
path: /etc/apt/apt.conf.d/90unattended-upgrades-blacklist
register: system_baseline_verify_blacklist_first
- name: Dump the merged apt configuration
ansible.builtin.command: apt-config dump
register: system_baseline_verify_blacklist_dump
changed_when: false
- name: Apt reads both entries as a list
ansible.builtin.assert:
that:
- system_baseline_verify_blacklist_first.stat.exists
- >-
system_baseline_verify_blacklist_dump.stdout_lines | select('match', 'Unattended-Upgrade::Package-Blacklist::\s') | list ==
['Unattended-Upgrade::Package-Blacklist:: "linux-image-.*";', 'Unattended-Upgrade::Package-Blacklist:: "nvidia-.*";']
quiet: true
- name: Run the same tasks again
ansible.builtin.include_role:
name: mortis.kamino.system_baseline
tasks_from: unattended_upgrades
vars:
system_baseline_system_type: ubuntu_lxc
system_baseline_unattended_upgrade_package_blacklist: "{{ system_baseline_verify_blacklist }}"
- name: Stat the blacklist drop-in again
ansible.builtin.stat:
path: /etc/apt/apt.conf.d/90unattended-upgrades-blacklist
register: system_baseline_verify_blacklist_second
- name: A second run does not rewrite the file
ansible.builtin.assert:
that:
- system_baseline_verify_blacklist_second.stat.checksum == system_baseline_verify_blacklist_first.stat.checksum
- system_baseline_verify_blacklist_second.stat.mtime == system_baseline_verify_blacklist_first.stat.mtime
quiet: true
- name: Run the same tasks with an empty blacklist
ansible.builtin.include_role:
name: mortis.kamino.system_baseline
tasks_from: unattended_upgrades
vars:
system_baseline_system_type: ubuntu_lxc
system_baseline_unattended_upgrade_package_blacklist: []
- name: Stat the blacklist drop-in after the empty list
ansible.builtin.stat:
path: /etc/apt/apt.conf.d/90unattended-upgrades-blacklist
register: system_baseline_verify_blacklist_removed
- name: Dump the merged apt configuration after the empty list
ansible.builtin.command: apt-config dump
register: system_baseline_verify_blacklist_dump_removed
changed_when: false
- name: The file is gone and apt lists no blacklisted package
ansible.builtin.assert:
that:
- not system_baseline_verify_blacklist_removed.stat.exists
- system_baseline_verify_blacklist_dump_removed.stdout_lines | select('match', 'Unattended-Upgrade::Package-Blacklist::\s') | list == []
quiet: true
tags: always
+2
View File
@@ -6,6 +6,8 @@
# Only the main flow honours system_baseline_update: the tasks_from: update entry point is an explicit request to update.
- name: Update & Upgrade Dist
ansible.builtin.import_tasks: update.yml
vars:
__system_baseline_main_flow: true
when: system_baseline_update | bool
tags: update
@@ -40,6 +40,23 @@
state: absent
when: system_baseline_unattended_upgrade_origins | length == 0
- name: Keep packages out of unattended-upgrades
become: true
ansible.builtin.template:
src: unattended-upgrades-blacklist.j2
dest: /etc/apt/apt.conf.d/90unattended-upgrades-blacklist
owner: root
group: root
mode: "0644"
when: system_baseline_unattended_upgrade_package_blacklist | length > 0
- name: Remove the package blacklist when none is set
become: true
ansible.builtin.file:
path: /etc/apt/apt.conf.d/90unattended-upgrades-blacklist
state: absent
when: system_baseline_unattended_upgrade_package_blacklist | length == 0
- name: Validate unattended-upgrades config
become: true
ansible.builtin.command: unattended-upgrades --dry-run --debug
+12 -2
View File
@@ -1,9 +1,19 @@
---
# In the main flow a dry run (--check) does not run the upgrade: a package that is only waiting for the next patch run is not drift, and
# the package module reports `changed` for it, so a scheduled dry run flagged every host whenever a package landed in between. The
# tasks_from: update entry point is an explicit request to update and still previews the upgrade in check mode: only main.yml sets
# __system_baseline_main_flow. Leftover packages (autoremove) and the cache (autoclean) stay checked either way.
- name: Update & upgrade apt packages
ansible.builtin.package:
update_cache: true
upgrade: true
autoremove: true
autoclean: true
cache_valid_time: 3600
become: true
when: not (ansible_check_mode and __system_baseline_main_flow | default(false))
# autoremove must stay in this task: the apt module accepts autoclean alone only together with one of autoremove, name, update_cache or upgrade.
- name: Remove unused packages and clean the apt cache
ansible.builtin.package:
autoremove: true
autoclean: true
become: true
+15
View File
@@ -35,6 +35,21 @@
when: system_baseline_tmux_autostart | bool
tags: always
# Each package pattern is written inside a double-quoted apt.conf string, like the origins below: the same characters are refused.
- name: Validate the unattended-upgrades package blacklist
ansible.builtin.assert:
that:
- system_baseline_unattended_upgrade_package_blacklist is sequence
- system_baseline_unattended_upgrade_package_blacklist is not string
- system_baseline_unattended_upgrade_package_blacklist is not mapping
- system_baseline_unattended_upgrade_package_blacklist | select('string') | select('match', '^[^"\\\\\n\r]+\Z') | list | length
== system_baseline_unattended_upgrade_package_blacklist | length
fail_msg: >-
system_baseline_unattended_upgrade_package_blacklist must be a list of non-empty one-line strings without a double quote
or a backslash.
quiet: true
tags: always
# Each origin is written inside a double-quoted apt.conf string: a quote or a line break would end it, a backslash could escape.
- name: Validate the unattended-upgrades origins
ansible.builtin.assert:
@@ -0,0 +1,8 @@
// Managed by Ansible (mortis.kamino.system_baseline, tasks/unattended_upgrades.yml). Do not edit: the next run overwrites it.
// apt appends list entries across apt.conf.d files, so these packages are added to Unattended-Upgrade::Package-Blacklist of
// 50unattended-upgrades. Entries are regular expressions matched against the package name.
Unattended-Upgrade::Package-Blacklist {
{% for package in system_baseline_unattended_upgrade_package_blacklist %}
"{{ package }}";
{% endfor %}
};
+1 -1
View File
@@ -253,7 +253,7 @@ def matrix_of(text): # noqa: C901, PLR0912, PLR0915 hand-written block-YAML re
if (keys["job_image"][0] or "").strip()[:1] in "\"'":
raise CheckError(
f"{MATRIX_FILE}: image '{name}': job_image must be written unquoted "
"(the bot-diff guard and Renovate read the plain form)"
"(the bot-diff check and Renovate read the plain form)"
)
matrix[name]["job_image"] = values["job_image"]
return matrix
+2
View File
@@ -89,6 +89,8 @@ FORBIDDEN = [
"*.env.*",
"*/.env*",
".env*",
# Contributor rules: a consumer's agent reading an installed role would load them.
"*/agents.md",
]
# Names Windows treats as devices, with or without an extension (and with trailing spaces).
WINDOWS_RESERVED = {
+16
View File
@@ -70,6 +70,22 @@ class TarballTest(unittest.TestCase):
self.assertEqual(len(found), 1, name)
self.assertIn("forbidden pattern", found[0], name)
def test_agents_md_is_refused_at_any_depth(self):
for name in (
"roles/AGENTS.md",
"roles/x/AGENTS.md",
"roles/x/templates/Agents.md",
):
found = check_tarball.problems([name])
self.assertEqual(len(found), 1, name)
self.assertIn("forbidden pattern", found[0], name)
self.assertEqual(
check_tarball.problems(
["roles/x/README.md", "roles/x/files/agents_notes.md"]
),
[],
)
def test_ambiguous_names_are_rejected(self):
cases = {
"roles/a/x ": "ends in a space or a dot",