53 Commits
Author SHA1 Message Date
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
Dragonish 560dc620a3 Merge pull request 'chore(release): 1.10.2' (#315) from chore/release-1.10.2 into main
Lint / lint (push) Successful in 2m15s
Molecule / molecule (push) Successful in 11m53s
Build / build (push) Successful in 18s
Reviewed-on: #315
Reviewed-by: Defame1297 <[email protected]>
2026-11-23 14:04:10 +00:00
Defame1297 749a301e12 Merge branch 'main' into chore/release-1.10.2
Build / build (pull_request) Successful in 16s
Lint / lint (pull_request) Successful in 1m18s
Molecule / molecule (pull_request) Successful in 11m58s
2026-11-23 13:50:35 +00:00
Defame1297 e10c973dc5 Merge pull request 'chore(agents): make Claude Code write Assisted-by instead of Co-Authored-By' (#313) from chore/claude-attribution-settings into main
Build / build (push) Successful in 17s
Lint / lint (push) Successful in 1m40s
Reviewed-on: #313
Reviewed-by: Defame1297 <[email protected]>
2026-11-23 13:06:01 +00:00
Defame1297 55e0f6ad93 Merge branch 'main' into chore/claude-attribution-settings
Build / build (pull_request) Successful in 17s
Lint / lint (pull_request) Successful in 1m13s
Molecule / molecule (pull_request) Successful in 11m57s
2026-11-23 12:50:43 +00:00
Dragonish 4bc176656a chore(release): 1.10.2
Build / build (pull_request) Successful in 16s
Lint / lint (pull_request) Successful in 1m17s
Molecule / molecule (pull_request) Successful in 11m54s
Patch release for the systemd_hardening socket handling (#308, #314).

Assisted-by: Claude Code
2026-11-23 12:33:35 +00:00
Defame1297 0bdb0bf33f Merge pull request 'fix(systemd_hardening): disable and mask the socket of a listed service too' (#314) from fix/308-systemd-hardening-sockets into main
Build / build (push) Successful in 17s
Lint / lint (push) Successful in 1m20s
Molecule / molecule (push) Successful in 11m56s
Reviewed-on: #314
2026-11-23 12:13:56 +00:00
Dragonish f256c1c7e5 fix(systemd_hardening): disable and mask the socket of a listed service too
Build / build (pull_request) Successful in 18s
Lint / lint (pull_request) Successful in 1m11s
Molecule / molecule (pull_request) Successful in 1m2s
Look up every listed name as a socket and as a service and act on each
installed unit, the socket first. A service whose socket stays active is
started again by the next connection to its port.

Assisted-by: Claude Code
2026-11-23 11:18:49 +00:00
Defame1297 5d9a26c1a6 Merge branch 'main' into chore/claude-attribution-settings
Build / build (pull_request) Successful in 18s
Lint / lint (pull_request) Successful in 1m30s
Molecule / molecule (pull_request) Successful in 11m34s
2026-11-23 10:45:51 +00:00
Defame1297 545f2fe94a Merge pull request 'chore(deps): refresh pip-compile outputs' (#306) from renovate/pip-compile-refresh into main
Build / build (push) Successful in 17s
Images / image (Dockerfile, ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8, molecule-ubuntu2404, images/molecule-ubuntu2404, 0.1.8) (push) Successful in 12m46s
Lint / lint (push) Successful in 1m20s
Images / image (Dockerfile, ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db, molecule-ubuntu2604, images/molecule-ubuntu2604, 0.1.5) (push) Successful in 10m10s
Images / image (images/ci/Dockerfile, ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db, ci, , 0.2.35) (push) Successful in 16m2s
Reviewed-on: #306
2026-11-23 10:45:41 +00:00
Defame1297 fa661be5c2 ci(molecule): skip scenarios for a change under .claude/ only
Build / build (pull_request) Successful in 14s
Molecule / molecule (pull_request) Canceled after 0s
Lint / lint (pull_request) Canceled after 23s
No scenario reads .claude/: Claude Code reads it on a contributor's
machine. Add it to the IGNORED list beside apm.yml, so a change to the
agent settings or apm-deployed hooks no longer runs every scenario.

Assisted-by: Claude Code
2026-11-23 10:41:45 +00:00
Defame1297 bfdbc9b42b chore(agents): make Claude Code write Assisted-by instead of Co-Authored-By
Build / build (pull_request) Canceled after 0s
Lint / lint (pull_request) Canceled after 0s
Molecule / molecule (pull_request) Canceled after 0s
Set attribution in the tracked .claude/settings.json: commit and pull
request attribution become "Assisted-by: Claude Code", and sessionUrl is
false so no Claude-Session trailer or session link is added. The setting
takes only a fixed string, so the model is not named.

Closes #152

Assisted-by: Claude Code
2026-11-23 10:34:41 +00:00
renovate-bot 57de3236ea chore(deps): refresh pip-compile outputs
renovate/stability-days Updates have met minimum release age requirement
Build / build (pull_request) Successful in 17s
Lint / lint (pull_request) Successful in 1m9s
Molecule / molecule (pull_request) Successful in 1s
2026-11-23 10:28:11 +00:00
Dragonish 7f4178b0da Merge pull request 'chore(release): 1.10.1' (#307) from chore/release-1.10.1 into main
Lint / lint (push) Successful in 1m18s
Molecule / molecule (push) Successful in 13m46s
Build / build (push) Successful in 14s
Reviewed-on: #307
Reviewed-by: Defame1297 <[email protected]>
2026-11-23 08:19:05 +00:00
Dragonish 7b6183f869 Merge branch 'main' into chore/release-1.10.1
Build / build (pull_request) Successful in 15s
Lint / lint (pull_request) Successful in 1m39s
Molecule / molecule (pull_request) Successful in 12m3s
2026-11-23 08:05:00 +00:00
Dragonish 0a9ea21f77 chore(release): 1.10.1
Build / build (pull_request) Successful in 19s
Lint / lint (pull_request) Successful in 1m4s
Molecule / molecule (pull_request) Canceled after 7m2s
Patch release for the systemd_hardening unit lookup (#283, #298).

Assisted-by: Claude Code
2026-11-23 07:52:58 +00:00
Defame1297 20bad9c95b Merge pull request 'chore(deps): update pre-commit hook zizmorcore/zizmor-pre-commit to v1.33.0' (#305) from renovate/zizmorcore-zizmor-pre-commit-1.x into main
Build / build (push) Successful in 15s
Images / image (Dockerfile, ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8, molecule-ubuntu2404, images/molecule-ubuntu2404, 0.1.8) (push) Successful in 39s
Lint / lint (push) Successful in 1m9s
Images / image (Dockerfile, ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db, molecule-ubuntu2604, images/molecule-ubuntu2604, 0.1.5) (push) Successful in 18s
Images / image (images/ci/Dockerfile, ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db, ci, , 0.2.34) (push) Successful in 5m14s
Reviewed-on: #305
2026-11-23 07:47:52 +00:00
Defame1297 b105c3c864 Merge branch 'main' into renovate/zizmorcore-zizmor-pre-commit-1.x
Build / build (pull_request) Successful in 14s
Lint / lint (pull_request) Successful in 1m5s
Molecule / molecule (pull_request) Successful in 1s
2026-11-23 07:45:41 +00:00
kamino-renovate Bot efc12897f5 Merge pull request 'chore(deps): update git.rkdr.net/mortis/ci docker tag to v0.2.33' (#304) from renovate/git.rkdr.net-mortis-ci-0.x into main
Build / build (push) Successful in 14s
Lint / lint (push) Successful in 54s
2026-11-23 07:45:23 +00:00
Defame1297 a1779c0aba Merge branch 'main' into renovate/git.rkdr.net-mortis-ci-0.x
Build / build (pull_request) Successful in 14s
Gitea release key / check (pull_request) Successful in 30s
Lint / lint (pull_request) Successful in 52s
Molecule / molecule (pull_request) Successful in 2s
2026-11-23 07:43:31 +00:00
Defame1297 344adbfb7a Merge pull request 'ci(molecule): run scenarios in four lanes and drop molecule's trailing destroy' (#303) from ci/molecule-parallel-scenarios into main
Build / build (push) Successful in 20s
Lint / lint (push) Successful in 1m5s
Molecule / molecule (push) Successful in 11m54s
Reviewed-on: #303
Reviewed-by: Defame1297 <[email protected]>
2026-11-23 07:22:22 +00:00
Defame1297 c19c7abb20 Merge branch 'main' into ci/molecule-parallel-scenarios
Build / build (pull_request) Successful in 23s
Lint / lint (pull_request) Successful in 1m16s
Molecule / molecule (pull_request) Successful in 11m47s
2026-11-23 06:51:55 +00:00
Defame1297 fabbe7d977 Merge pull request 'test(molecule): move refusal plays from converge to verify' (#302) from test/refusal-plays-to-verify into main
Build / build (push) Successful in 19s
Lint / lint (push) Successful in 1m8s
Molecule / molecule (push) Successful in 22m5s
Reviewed-on: #302
2026-11-23 06:45:16 +00:00
renovate-bot 43fcc382c6 chore(deps): update pre-commit hook zizmorcore/zizmor-pre-commit to v1.33.0
renovate/stability-days Updates have met minimum release age requirement
Build / build (pull_request) Successful in 20s
Lint / lint (pull_request) Successful in 1m18s
Molecule / molecule (pull_request) Successful in 1s
2026-11-23 03:17:41 +00:00
renovate-bot 4d3ed96ed4 chore(deps): update git.rkdr.net/mortis/ci docker tag to v0.2.33
renovate/stability-days Updates have met minimum release age requirement
Build / build (pull_request) Successful in 31s
Gitea release key / check (pull_request) Successful in 12s
Lint / lint (pull_request) Successful in 48s
Molecule / molecule (pull_request) Successful in 2s
2026-11-23 03:17:39 +00:00
Defame1297 1ab01b6e3a ci(molecule): run the selected scenarios side by side in four lanes
Build / build (pull_request) Successful in 19s
Lint / lint (pull_request) Successful in 1m7s
Molecule / molecule (pull_request) Successful in 11m58s
A full run executes 15 scenarios one after another, about 1100 s in
total, with the slowest (traefik/default) at about 216 s. The scenarios
share nothing on the runner's Docker daemon but the daemon itself: their
container names are unique. So scripts/run_molecule_scenarios.sh now runs
MOLECULE_LANES (default 4, a positive integer) of them at once inside the
one job, with the slowest scenario as the floor; the saving will be
measured in CI.

Each scenario gets its own ANSIBLE_HOME under the job tree. With
Runtime(isolated=False), ansible-compat uses ANSIBLE_HOME as molecule's
cache dir: molecule's prerun installs the collection under test there with
`ansible-galaxy collection install --force` (which first deletes the
installed copy), and the scenario's ephemeral directory (inventory,
ansible.cfg, state) lives under it. A shared one would let a scenario
delete the copy another is running.

Each scenario's output goes to its own log, printed afterwards in the
selection order inside its own group with its wall time, plus a timing
summary. The failure list, the ran-N-of-M guard, </dev/null stdin, the
role-directory cwd and the per-scenario container removal are kept. A
TERM, INT or HUP to the script stops each lane's whole process tree,
including the process groups of ansible's detached workers (they call
setsid), terminates it, ignores further signals until done, and exits
128 plus the first signal. A kill of the step's process group reaches
the lanes and molecule but not ansible's detached workers. Either way a
cancelled job leaves no molecule behind to recreate a container after
the next run's cleanup. The logic moved from the workflow into a script
so a unit test with stub molecule and docker can hold it; the test also
fails a scenario whose platform name is not unique or not matched by the
stale-container filter, which is what makes running side by side safe.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-22 22:37:00 +00:00
Defame1297 f77586dc60 ci(molecule): remove each scenario's containers in the workflow instead of molecule's destroy
molecule's trailing destroy runs the Docker driver's destroy playbook, whose
"Wait for instance(s) deletion to complete" task alone costs about 5.6 s per
scenario, about 84 s over the 15 scenarios of a full run. The whole destroy
phase measured about 103 s per full run (the median across full runs, among
them 4764, 4714, 4698 and 4578). The workflow already removes stale
containers before the run, so it can remove each scenario's containers itself
with `docker rm -f` as soon as the scenario ends, pass or fail, and skip the
playbook.

The names come from each scenario's molecule.yml (platforms[].name) via the
molecule venv's Python and PyYAML, so no list is kept in the workflow. A
failed removal fails the step. The test_sequence rule in the workflow guidance
now says both destroys are left out and that platform names are literal.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-22 22:33:52 +00:00
Defame1297 fdb3f8c1df test(molecule): move refusal plays from converge to verify
Build / build (pull_request) Successful in 25s
Lint / lint (pull_request) Successful in 1m16s
Molecule / molecule (pull_request) Successful in 9m29s
molecule's idempotence step reruns converge.yml, so plays that only prove a
role refuses bad input ran twice and added nothing the second time. The ufw,
sshd, gitea and traefik scenarios now keep only the plays that apply the role
in converge.yml; the refusal plays and gitea's child ansible-playbook guard
checks run once, first in verify.yml. Every existing assertion runs after
them, so verify still proves a refused run left the host unchanged.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-22 22:15:37 +00:00
Defame1297 00c6cbeba4 Merge pull request 'ci(molecule): run only the image-smoke scenario a pull request changes' (#301) from ci/narrow-image-smoke into main
Build / build (push) Successful in 19s
Lint / lint (push) Successful in 1m6s
Reviewed-on: #301
2026-11-22 21:18:10 +00:00
Defame1297 5c8b8f5342 ci(molecule): run only the image-smoke scenario a pull request changes
Build / build (pull_request) Successful in 20s
Lint / lint (pull_request) Successful in 1m6s
Molecule / molecule (pull_request) Successful in 1s
A file under extensions/molecule/<name>/ ran every scenario, although
only that image-smoke scenario reads it: they test the images, not the
roles. It now selects that scenario only. A shared file such as
extensions/molecule/requirements.yml, or a name that is not a scenario,
still runs everything.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-22 21:14:45 +00:00
Defame1297 b49c953e8d Merge pull request 'ci(molecule): stop running every scenario for files no scenario reads' (#299) from ci/narrow-molecule-ignore into main
Build / build (push) Successful in 21s
Lint / lint (push) Successful in 1m3s
Reviewed-on: #299
Reviewed-by: Defame1297 <[email protected]>
2026-11-22 20:50:46 +00:00
Defame1297 5f2003e07f Merge branch 'main' into ci/narrow-molecule-ignore
Build / build (pull_request) Successful in 24s
Lint / lint (pull_request) Successful in 1m27s
Molecule / molecule (pull_request) Successful in 18m18s
2026-11-22 20:13:01 +00:00
Dragonish 03ed536a14 Merge pull request 'fix(systemd_hardening): look up the listed units instead of listing every unit file' (#298) from fix/283-systemd-hardening-probe into main
Build / build (push) Successful in 24s
Lint / lint (push) Successful in 1m7s
Molecule / molecule (push) Successful in 19m35s
Reviewed-on: #298
Reviewed-by: Defame1297 <[email protected]>
2026-11-22 20:09:25 +00:00
Defame1297 00bac19705 ci(molecule): stop running every scenario for files no scenario reads
Build / build (pull_request) Canceled after 0s
Lint / lint (pull_request) Canceled after 0s
Molecule / molecule (pull_request) Canceled after 0s
A pull request ran every scenario when it changed the selector itself,
which happened whenever a new file was added to its IGNORED list.
Molecule runs the base branch's copy, so the pull request's copy is
never exercised by a scenario. Ignore it, nested AGENTS.md files, role
READMEs, .python-version and scripts/lock-requirements.sh.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-22 20:09:08 +00:00
Defame1297 4dc221c17f Merge branch 'main' into fix/283-systemd-hardening-probe
Build / build (pull_request) Successful in 25s
Molecule / molecule (pull_request) Successful in 55s
Lint / lint (pull_request) Successful in 1m22s
2026-11-22 20:03:08 +00:00
Defame1297 c60c6aa970 Merge pull request 'chore(agents): ignore local Claude settings and commit apm-deployed hooks' (#297) from chore/196-claude-settings-hooks into main
Build / build (push) Successful in 20s
Lint / lint (push) Successful in 1m6s
Reviewed-on: #297
Reviewed-by: Defame1297 <[email protected]>
2026-11-22 19:54:34 +00:00
Dragonish 6c2d124b3f fix(systemd_hardening): look up the listed units instead of listing every unit file
Build / build (pull_request) Successful in 20s
Molecule / molecule (pull_request) Canceled after 0s
Lint / lint (pull_request) Canceled after 38s
The role listed every service unit file to answer one question: is each
unit in its disable and mask lists installed? The listing keeps PID 1 busy
for as long as the host has unit files. Ask about the listed units only,
with one `systemctl show --property=LoadState`; a unit with no unit file
reports `not-found` and is skipped as before.

An instance name such as [email protected] is now matched when its template
exists. A template name such as [email protected] makes the lookup fail, where
the listing matched it.

Closes #283

Assisted-by: Claude Code
2026-11-22 19:41:23 +00:00
Defame1297 8df9070cd8 chore(agents): ignore local Claude settings and commit apm-deployed hooks
Build / build (pull_request) Successful in 22s
Lint / lint (pull_request) Successful in 1m14s
Molecule / molecule (pull_request) Successful in 18m40s
Ignore .claude/settings.local.json and stop ignoring .claude/hooks/, so
hooks apm deploys are committed for review. Track .claude/settings.json
with disableSkillShellExecution, so no committed skill runs a shell
command when it loads. State the apm primitive policy in apm.yml and the
hook-ownership rule in the setup doc.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-22 19:33:26 +00:00
Defame1297 5962b9b6fb Merge pull request 'chore: trim the apm plugins and pin apm-cli' (#296) from chore/193-trim-apm-pin-apm-cli into main
Build / build (push) Successful in 20s
Images / image (Dockerfile, ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8, molecule-ubuntu2404, images/molecule-ubuntu2404, 0.1.8) (push) Successful in 8s
Lint / lint (push) Successful in 1m8s
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.33) (push) Successful in 4m12s
Reviewed-on: #296
2026-11-22 18:34:57 +00:00
Defame1297 7bb4d13dc0 Merge branch 'main' into chore/193-trim-apm-pin-apm-cli
Lint / lint (pull_request) Successful in 1m13s
Molecule / molecule (pull_request) Successful in 1s
Build / build (pull_request) Successful in 22s
2026-11-22 18:09:04 +00:00
Defame1297 f7d23a7c04 chore: trim the apm plugins and pin apm-cli
Lint / lint (pull_request) Canceled after 0s
Molecule / molecule (pull_request) Canceled after 0s
Build / build (pull_request) Canceled after 20s
Keep only the git and mattpocock plugins in apm.yml (bin, core and gitea
dropped, per #104) and regenerate apm.lock.yaml with apm-cli 0.36.1.

Pin apm-cli 0.36.1 in requirements-dev.txt and its hashed lock, the floor
set by #252: before 0.29.0, `apm audit --ci` compares the whole
.claude/settings.json. This is an image input, so the ci image moves to
0.2.33.

Closes #193

Assisted-by: Claude Code:claude-opus-5-5
2026-11-22 17:39:57 +00:00
78 changed files with 5720 additions and 2162 deletions

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
{
"attribution": {
"commit": "Assisted-by: Claude Code",
"pr": "Assisted-by: Claude Code",
"sessionUrl": false
},
"disableSkillShellExecution": true
}
+14 -8
View File
@@ -84,18 +84,24 @@ issue.
too, until #166 removes that trigger. *Why:* a pull request runs only its selection, so
drift in the other roles shows up here. *Held:* review.
- **A new commit cancels the pull request's running Molecule run, and the run step first removes
the containers a cancelled run left.** Two runs never overlap only because the runner has a
single slot, and the scenarios' container names are fixed; raising the runner's capacity needs
per-run container names first (#166). *Why:* a cancelled run is killed before it can destroy
its instances, and two runs would collide on the same names. *Held:* review.
the containers a cancelled run left.** The scenarios of one run overlap
(`scripts/run_molecule_scenarios.sh`, `MOLECULE_LANES` at a time), so no two scenarios may share a
platform name. Two runs never overlap only because the runner has a single slot, and the
scenarios' container names are fixed; raising the runner's capacity needs per-run container
names first (#166). *Why:* a cancelled run is killed before it can remove its instances, and
two overlapping scenarios or runs would collide on the same names. *Held:* review; that no two
scenarios share a platform name is held by the test the `test_sequence` rule below names.
- **Molecule tests the pull request's pins, as Lint and Build do.** *Why:* the pull request that
raises the ansible-core floor must be behaviour-tested on the new core before it automerges.
*Held:* aspirational until #225 runs Molecule from the `ci` image with the pin comparison
against `/opt/ci-pins.sha256`; today it runs from the runner's own venv.
- **Every scenario sets `scenario.test_sequence` to molecule's default minus the leading
`destroy`;** copy it into a new scenario. *Why:* the workflow clears stale containers first,
and the molecule state lives in the job's own `ANSIBLE_HOME`, so a killed run leaves none
behind. *Held:* review.
- **Every scenario sets `scenario.test_sequence` to molecule's default minus both `destroy`
steps, and names its platforms literally in its `molecule.yml`;** copy it into a new scenario.
*Why:* the workflow clears stale containers first and removes each scenario's containers by
those names as soon as it ends, which skips the driver's destroy wait, and the molecule state
lives in each scenario's own `ANSIBLE_HOME` in the job tree, so a killed run leaves none
behind. *Held:* control: `tests/scripts/test_run_molecule_scenarios.py` fails a `destroy` in a
sequence, and a platform name that is not unique or not matched by the stale-container filter.
- **Scenarios live in `roles/*/molecule/*/` and `extensions/molecule/*/`.** A role scenario that
must pass on Ubuntu 24.04 and 26.04 takes `image: ${MOLECULE_IMAGE}` or
`${MOLECULE_IMAGE_2604}` per platform; the image-smoke scenarios are described in
+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.32@sha256:3282337dd3ccb20172e519d11fa996bfad2df09f3f5de14e2706d9d368af9923
image: git.rkdr.net/mortis/ci:0.2.33@sha256:2020686a819c5bdac6f773237479083ccc291a00351a6647c26a2dec5341de43
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.32@sha256:3282337dd3ccb20172e519d11fa996bfad2df09f3f5de14e2706d9d368af9923
image: git.rkdr.net/mortis/ci:0.2.33@sha256:2020686a819c5bdac6f773237479083ccc291a00351a6647c26a2dec5341de43
steps:
# The container has no Node, so JavaScript actions such as actions/checkout
# cannot run; clone with git and the job token.
+1 -1
View File
@@ -87,7 +87,7 @@ jobs:
dockerfile: Dockerfile
job_image: ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db
- name: ci
version: 0.2.32
version: 0.2.35
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.32@sha256:3282337dd3ccb20172e519d11fa996bfad2df09f3f5de14e2706d9d368af9923
image: git.rkdr.net/mortis/ci:0.2.33@sha256:2020686a819c5bdac6f773237479083ccc291a00351a6647c26a2dec5341de43
env:
PIP_DISABLE_PIP_VERSION_CHECK: "1"
PRE_COMMIT_HOME: /opt/pre-commit
+12 -39
View File
@@ -44,10 +44,11 @@ permissions:
# A pull request run is cancelled when a newer commit is pushed to the same pull request (the
# same rule as lint.yml and build.yml); a run on main is never cancelled, so its group is the
# commit SHA. Scenarios use fixed container names on the runner's shared Docker daemon, so two
# runs must not overlap. The group no longer guarantees that (it is per pull request now): the
# runner's single slot does. Raise the runner's capacity and this needs a lock or a shared
# group again.
# commit SHA. The scenarios of one run overlap (scripts/run_molecule_scenarios.sh), which is safe
# because no two share a container name; but the names are fixed on the runner's shared Docker
# daemon, so two runs must not overlap. The group no longer guarantees that (it is per pull
# request now): the runner's single slot does. Raise the runner's capacity and this needs
# per-run container names first (#166), or a lock or a shared group again.
concurrency:
group: molecule-${{ github.event_name == 'pull_request' && github.ref || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
@@ -127,10 +128,9 @@ jobs:
echo "KAMINO_COLLECTIONS=$dest" >> "$GITHUB_ENV"
# A pull request runs only the scenarios of the roles it changes (scripts/select_molecule_scenarios.py
# explains the rules); a push to main and a manual dispatch run all of them.
# molecule test destroys its instance on success and on failure; a cancelled run is killed
# before it can, so the step first removes what such a run left, since the next run may not
# select the same scenarios.
# explains the rules); a push to main and a manual dispatch run all of them, a few at a time.
# scripts/run_molecule_scenarios.sh runs them and removes each scenario's containers as soon as
# it ends; a cancelled run is killed before it can, so the step first removes what one left.
- name: Run the scenarios
working-directory: ac/ansible_collections/mortis/kamino
env:
@@ -148,12 +148,11 @@ jobs:
# molecule calls ansible-config and ansible-playbook by name
export PATH="$MOLECULE_VENV/bin:$PATH"
# The collection under test first, then the pinned collections the roles use. molecule also
# installs the collection under test into ANSIBLE_HOME; keep that inside the
# job tree so no run resolves a copy another run left in the runner user's
# home (the version stays 0.1.0, so a stale copy would look current). The rm
# installs the collection under test into ANSIBLE_HOME, which the run script gives each
# scenario inside the job tree, so no run resolves a copy another run left in the runner
# user's home (the version stays 0.1.0, so a stale copy would look current). The rm
# clears a copy left there by runs before this was set.
ac_root="$(cd ../../.. && pwd)"
export ANSIBLE_HOME="$ac_root/.ansible"
export ANSIBLE_COLLECTIONS_PATH="$ac_root:$KAMINO_COLLECTIONS"
rm -rf "$HOME/.ansible/collections/ansible_collections/mortis"
# The selector comes from the base branch, so a pull request cannot edit the rules it is
@@ -169,30 +168,4 @@ jobs:
echo "::notice::no base copy of $sel; running this checkout's copy"
fi
selected="$(python3 -I "$sel" "$BASE_REF")" || exit 1
failed=""
ran=0
while IFS= read -r dir; do
[ -n "$dir" ] || continue
name="$(basename "$dir")"
case "$dir" in
extensions/*)
label="$name"
echo "::group::molecule test: $label"
molecule test -s "$name" </dev/null || failed="$failed $label"
;;
*)
role="${dir#roles/}"
role="${role%%/*}"
label="$role/$name"
echo "::group::molecule test: $label"
(cd "roles/$role" && molecule test -s "$name" </dev/null) || failed="$failed $label"
;;
esac
ran=$((ran + 1))
echo "::endgroup::"
done <<< "$selected"
echo "Scenarios run: $ran"
# A scenario that swallowed the rest of the list must not pass quietly.
want="$(grep -c . <<< "$selected" || true)"
test "$ran" -eq "$want" || { echo "::error::ran $ran of $want selected scenarios"; exit 1; }
test -z "$failed" || { echo "::error::Failed:$failed"; exit 1; }
scripts/run_molecule_scenarios.sh "$ac_root/molecule-runs" <<< "$selected"
+4 -3
View File
@@ -13,9 +13,10 @@ vault-pass*
gitleaks-report.json
# galaxy-importer output
importer_result.json
# APM: apm_modules/ is the dependency cache; .claude/skills,
# agents and hooks are `apm install` deploy output, regenerated on every install.
# APM: apm_modules/ is the dependency cache. Deployed skills and agents stay out
# while their source is private; deployed hooks are committed for review.
apm_modules/
.claude/skills/
.claude/agents/
.claude/hooks/
# Claude Code: personal settings and allowlists, never shared
.claude/settings.local.json
+1 -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: 06a39750ec31860bb44f2acf67182c40016cd1e7 # frozen: v1.32.0
rev: 0eb9e4a60caf04df64b499ed1e8bef55f4440eae # frozen: v1.33.0
hooks:
- id: zizmor
args: [--no-progress, --offline]
+24
View File
@@ -4,6 +4,30 @@ 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
=======
Bugfixes
--------
- systemd_hardening - Disable and mask the socket of a listed service as well. A service whose socket stayed active was started again by the next connection to its port (``rpcbind`` listens on port 111 through ``rpcbind.socket``). Every name in the disable and mask lists is now looked up as a socket and as a service, with or without a ``.service`` or ``.socket`` suffix, and each installed unit is acted on, the socket first. A socket that belongs to a listed name, such as ``rpcbind.socket``, is now stopped and disabled, or masked, where before it was left alone.
v1.10.1
=======
Bugfixes
--------
- systemd_hardening - Look up the listed units with one ``systemctl show`` instead of listing every unit file. The listing can keep PID 1 busy for seconds on a host with slow storage, and the cost grows with the number of unit files. A unit is still skipped when it has no unit file. An instance name such as ``[email protected]`` is now matched when its template exists, and a template name such as ``[email protected]`` in the lists now makes the lookup fail instead of matching.
v1.10.0
=======
+3 -3
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.0 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.0
version: v1.11.0
```
Its dependencies (`community.general`, `ansible.posix`) are declared in `galaxy.yml`, so
@@ -40,7 +40,7 @@ the environment that uses it) 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`.
+431 -876
View File
File diff suppressed because it is too large. Load diff
+6 -15
View File
@@ -3,27 +3,18 @@ version: 0.1.0
description: Ansible Collection mortis.kamino. Consumer-side apm manifest for holocron skills.
license: GPL-3.0-or-later
# Consumer side: holocron plugins are addressed as git+path objects rather than
# <name>@holocron marketplace aliases, so nothing outside this manifest is
# needed. Unpinned (default branch) on purpose: Renovate cannot keep a pin
# current here. Its apm manager documents only the string form (not these
# git+path objects), is not in
# renovate.json's enabledManagers, and holocron's v* tags are repo-wide and
# lag main (v2.0.1 is 164 commits behind and predates plugins/mattpocock). A
# hand-kept ref would just go stale. The third-party skills are pinned inside
# plugins/mattpocock/apm.yml, upstream of this manifest.
# git and mattpocock only (#104): bin and core are unused here, and gitea returns once it is
# rebuilt on the tea CLI.
# Hook primitives come from apm; no instruction primitive is deployed until the root AGENTS.md
# has a managed section. `apm approve` writes the executables.allow entry into this file, and it
# is committed because an unattended `apm install` cannot answer the prompt.
targets:
- claude
dependencies:
apm:
- git: https://git.rkdr.net/Mortis/Holocron.git
path: plugins/bin
- git: https://git.rkdr.net/Mortis/Holocron.git
path: plugins/core
- git: https://git.rkdr.net/Mortis/Holocron.git
path: plugins/git
- git: https://git.rkdr.net/Mortis/Holocron.git
path: plugins/gitea
- git: https://git.rkdr.net/Mortis/Holocron.git
path: plugins/mattpocock
mcp: []
+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.0
version: 1.11.0
+47
View File
@@ -58,6 +58,53 @@ releases:
- gitea-release-key-check.yml
- gitea-runner-role.yml
release_date: '2026-11-22'
1.10.1:
changes:
bugfixes:
- systemd_hardening - Look up the listed units with one ``systemctl show`` instead
of listing every unit file. The listing can keep PID 1 busy for seconds on
a host with slow storage, and the cost grows with the number of unit files.
A unit is still skipped when it has no unit file. An instance name such as
``[email protected]`` is now matched when its template exists, and a template
name such as ``[email protected]`` in the lists now makes the lookup fail instead
of matching.
fragments:
- systemd-hardening-unit-lookup.yml
release_date: '2026-11-23'
1.10.2:
changes:
bugfixes:
- systemd_hardening - Disable and mask the socket of a listed service as well.
A service whose socket stayed active was started again by the next connection
to its port (``rpcbind`` listens on port 111 through ``rpcbind.socket``).
Every name in the disable and mask lists is now looked up as a socket and
as a service, with or without a ``.service`` or ``.socket`` suffix, and each
installed unit is acted on, the socket first. A socket that belongs to a listed
name, such as ``rpcbind.socket``, is now stopped and disabled, or masked,
where before it was left alone.
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:
+5 -1
View File
@@ -41,8 +41,12 @@ held by review until an offline link check exists.
*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.** (`.gitignore` lists it once issue #196 lands; until then, leave it out of your commits.)
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.
*Held by:* review (`.claude/` is under `CODEOWNERS`).
- **Every hook in the tracked `.claude/settings.json` arrives through apm; personal hooks go in
`.claude/settings.local.json`.**
*Reason:* a hook nobody owns is checked by nothing.
*Held by:* review (`.claude/` is under `CODEOWNERS`).
@@ -26,10 +26,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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
@@ -41,4 +40,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+3 -5
View File
@@ -26,10 +26,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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
@@ -41,4 +40,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+1 -1
View File
@@ -1,7 +1,7 @@
---
namespace: mortis
name: kamino
version: 1.10.0
version: 1.11.0
readme: README.md
authors:
- Defame1297
+1657 -452
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -12,3 +12,6 @@ pre-commit==4.7.0
antsibull-changelog==0.37.0
galaxy-importer==0.4.44
reuse==6.3.0
# apm-cli: for changing apm.yml (run apm install, commit the lock). Keep it at 0.36.1 or later (#252):
# before 0.29.0, `apm audit --ci` compares the whole .claude/settings.json and fails on any hand-written key.
apm-cli==0.36.1
@@ -26,10 +26,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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
@@ -40,4 +39,3 @@ scenario:
- check
- verify
- cleanup
- destroy
@@ -26,10 +26,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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
@@ -41,4 +40,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+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
+3 -5
View File
@@ -27,10 +27,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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
@@ -42,4 +41,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+3 -5
View File
@@ -25,10 +25,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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
@@ -40,4 +39,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+1 -1
View File
@@ -1,5 +1,5 @@
---
# Run by converge.yml in a child ansible-playbook process, because the mint guard
# 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. With the CI variable set it fails at the CI
+3 -114
View File
@@ -1,118 +1,7 @@
---
# Guard and no-op paths of the mint entry point (nothing is installed). Each
# failure case wraps the include in block/rescue, so the play passes when the
# guard fires, and fails when the include returns or fails with another message.
# Gitea is never installed in this scenario, so converge applies nothing; the mint guards and
# every check are in verify.yml, which runs once.
- name: Converge
hosts: all
gather_facts: false
tasks:
- name: Mint without confirmation
block:
- name: Include the mint entry point with gitea_mint_confirm unset
ansible.builtin.include_role:
name: mortis.kamino.gitea
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"
- "'gitea_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 }}/ci_guard.yml"
environment: "{{ {'GITHUB_ACTIONS': '', 'GITEA_ACTIONS': '', 'CI': '', 'ANSIBLE_NOCOLOR': '1'} | combine({item: 'true'}) }}"
loop:
- GITHUB_ACTIONS
- GITEA_ACTIONS
- CI
register: gitea_test_mint_ci
# The child is expected to fail (the CI guard fires). Its rc and output are asserted in the next task.
failed_when: false
changed_when: false
# Ansible 2.19 prints task failures to stderr, so both streams are checked.
- name: The CI guard fired for every variable
ansible.builtin.assert:
that:
- item.rc != 0
- "'refuses to run under CI' in (item.stdout ~ item.stderr)"
- "'mint is opt-in' not in (item.stdout ~ item.stderr)"
quiet: true
loop: "{{ gitea_test_mint_ci.results }}"
loop_control:
label: "{{ item.item }}"
- name: Mint outside CI with the token already defined, run as a child process
delegate_to: localhost
run_once: true
ansible.builtin.command:
argv:
- ansible-playbook
- -i
- localhost,
- "{{ playbook_dir }}/ci_guard.yml"
- -e
- gitea_api_token=molecule-not-a-token
environment:
GITHUB_ACTIONS: ""
GITEA_ACTIONS: ""
CI: ""
ANSIBLE_NOCOLOR: "1"
register: gitea_test_mint_noop
# A child failure must not abort here; the next task asserts rc and output.
failed_when: false
changed_when: false
- name: The mint was a no-op that registered no token fact
ansible.builtin.assert:
that:
- gitea_test_mint_noop.rc == 0
- "'nothing to mint' in (gitea_test_mint_noop.stdout ~ gitea_test_mint_noop.stderr)"
quiet: true
# An empty token counts as missing (configure.yml refuses it), so the mint must not report
# "nothing to mint". In check mode it creates nothing and registers no fact, and ends green
# (ci_guard.yml asserts that gitea_minted_api_token is not defined).
- name: Mint outside CI with an empty token in check mode, run as a child process
delegate_to: localhost
run_once: true
ansible.builtin.command:
argv:
- ansible-playbook
- -i
- localhost,
- "{{ playbook_dir }}/ci_guard.yml"
- --check
- -e
- gitea_api_token=
environment:
GITHUB_ACTIONS: ""
GITEA_ACTIONS: ""
CI: ""
ANSIBLE_NOCOLOR: "1"
register: gitea_test_mint_empty
# A child failure must not abort here; the next task asserts rc and output.
failed_when: false
changed_when: false
- name: An empty token was treated as missing and nothing was minted
ansible.builtin.assert:
that:
- gitea_test_mint_empty.rc == 0
- "'nothing to mint' not in (gitea_test_mint_empty.stdout ~ gitea_test_mint_empty.stderr)"
quiet: true
tasks: []
+3 -5
View File
@@ -36,10 +36,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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
@@ -51,4 +50,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+119
View File
@@ -1,4 +1,123 @@
---
# Guard and no-op paths of the mint entry point (nothing is installed). Each failure case
# wraps the include in block/rescue, or runs ci_guard.yml as a child process, so the play
# passes when the guard fires and fails when the include returns or fails with another message.
# First, so the assertions below also show the guards changed nothing.
- name: Verify the mint guards
hosts: all
gather_facts: false
tasks:
- name: Mint without confirmation
block:
- name: Include the mint entry point with gitea_mint_confirm unset
ansible.builtin.include_role:
name: mortis.kamino.gitea
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"
- "'gitea_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 }}/ci_guard.yml"
environment: "{{ {'GITHUB_ACTIONS': '', 'GITEA_ACTIONS': '', 'CI': '', 'ANSIBLE_NOCOLOR': '1'} | combine({item: 'true'}) }}"
loop:
- GITHUB_ACTIONS
- GITEA_ACTIONS
- CI
register: gitea_test_mint_ci
# The child is expected to fail (the CI guard fires). Its rc and output are asserted in the next task.
failed_when: false
changed_when: false
# Ansible 2.19 prints task failures to stderr, so both streams are checked.
- name: The CI guard fired for every variable
ansible.builtin.assert:
that:
- item.rc != 0
- "'refuses to run under CI' in (item.stdout ~ item.stderr)"
- "'mint is opt-in' not in (item.stdout ~ item.stderr)"
quiet: true
loop: "{{ gitea_test_mint_ci.results }}"
loop_control:
label: "{{ item.item }}"
- name: Mint outside CI with the token already defined, run as a child process
delegate_to: localhost
run_once: true
ansible.builtin.command:
argv:
- ansible-playbook
- -i
- localhost,
- "{{ playbook_dir }}/ci_guard.yml"
- -e
- gitea_api_token=molecule-not-a-token
environment:
GITHUB_ACTIONS: ""
GITEA_ACTIONS: ""
CI: ""
ANSIBLE_NOCOLOR: "1"
register: gitea_test_mint_noop
# A child failure must not abort here; the next task asserts rc and output.
failed_when: false
changed_when: false
- name: The mint was a no-op that registered no token fact
ansible.builtin.assert:
that:
- gitea_test_mint_noop.rc == 0
- "'nothing to mint' in (gitea_test_mint_noop.stdout ~ gitea_test_mint_noop.stderr)"
quiet: true
# An empty token counts as missing (configure.yml refuses it), so the mint must not report
# "nothing to mint". In check mode it creates nothing and registers no fact, and ends green
# (ci_guard.yml asserts that gitea_minted_api_token is not defined).
- name: Mint outside CI with an empty token in check mode, run as a child process
delegate_to: localhost
run_once: true
ansible.builtin.command:
argv:
- ansible-playbook
- -i
- localhost,
- "{{ playbook_dir }}/ci_guard.yml"
- --check
- -e
- gitea_api_token=
environment:
GITHUB_ACTIONS: ""
GITEA_ACTIONS: ""
CI: ""
ANSIBLE_NOCOLOR: "1"
register: gitea_test_mint_empty
# A child failure must not abort here; the next task asserts rc and output.
failed_when: false
changed_when: false
- name: An empty token was treated as missing and nothing was minted
ansible.builtin.assert:
that:
- gitea_test_mint_empty.rc == 0
- "'nothing to mint' not in (gitea_test_mint_empty.stdout ~ gitea_test_mint_empty.stderr)"
quiet: true
- name: Verify
hosts: all
gather_facts: false
@@ -44,10 +44,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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
@@ -59,4 +58,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
@@ -25,10 +25,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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
@@ -40,4 +39,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+2 -157
View File
@@ -8,28 +8,9 @@
roles:
- role: mortis.kamino.sshd
# A play without sshd_profile: the role must refuse it and leave the config
# converged above untouched. The block proves the refusal (not its wording); the play
# still passes, so the idempotence run stays clean.
- name: Converge the role without a profile
hosts: all
gather_facts: false
tasks:
- name: Missing sshd_profile is rejected
block:
- name: Apply the role without sshd_profile
ansible.builtin.include_role:
name: mortis.kamino.sshd
- name: Fail when the missing profile was accepted
ansible.builtin.fail:
msg: the sshd role accepted a run without sshd_profile
rescue:
- name: The role refused the run
ansible.builtin.debug:
msg: Rejected as expected
# The plays below only load the role's defaults and run validate.yml, which changes nothing
# on the container. They cover the profiles the converge above cannot run and the guards.
# on the container. They cover the profiles the converge above cannot run and the values
# the guards accept.
- name: Every profile passes validation and keeps its root login policy
hosts: all
gather_facts: false
@@ -83,29 +64,6 @@
- sshd_settings_effective.PubkeyAuthentication == "yes"
quiet: true
- name: The lock-out guard refuses a lock-out
hosts: all
gather_facts: false
vars:
sshd_profile: ubuntu_lxc
sshd_settings:
PubkeyAuthentication: "no"
tasks:
- name: Apply a lock-out configuration
block:
- name: Include the validation
ansible.builtin.include_role:
name: mortis.kamino.sshd
tasks_from: validate.yml
- name: Fail when the lock-out was accepted
ansible.builtin.fail:
msg: the sshd role accepted a lock-out configuration
rescue:
- name: The lock-out guard stopped the play
ansible.builtin.assert:
that: "'lock you out' in ansible_failed_result.msg | default('')"
quiet: true
- name: The Proxmox guard accepts every value that allows root key login
hosts: all
gather_facts: false
@@ -119,116 +77,3 @@
sshd_settings:
PermitRootLogin: "{{ item }}"
loop: [prohibit-password, without-password, "yes", Prohibit-Password]
- name: The Proxmox guard refuses a pve profile without root login
hosts: all
gather_facts: false
vars:
sshd_profile: pve
sshd_settings:
PermitRootLogin: "no"
tasks:
- name: Apply a pve configuration without root login
block:
- name: Include the validation
ansible.builtin.include_role:
name: mortis.kamino.sshd
tasks_from: validate.yml
- name: Fail when the Proxmox guard was bypassed
ansible.builtin.fail:
msg: the sshd role accepted a pve profile without root login
rescue:
- name: The Proxmox guard stopped the play
ansible.builtin.assert:
that: "'needs root public-key login' in ansible_failed_result.msg | default('')"
quiet: true
- name: The Proxmox guard refuses forced-commands-only
hosts: all
gather_facts: false
vars:
sshd_profile: pve
sshd_settings:
PermitRootLogin: forced-commands-only
tasks:
- name: Apply a pve configuration with forced commands only
block:
- name: Include the validation
ansible.builtin.include_role:
name: mortis.kamino.sshd
tasks_from: validate.yml
- name: Fail when the Proxmox guard was bypassed
ansible.builtin.fail:
msg: the sshd role accepted forced-commands-only for the pve profile
rescue:
- name: The Proxmox guard stopped the play
ansible.builtin.assert:
that: "'needs root public-key login' in ansible_failed_result.msg | default('')"
quiet: true
- name: The Proxmox guard refuses a pve profile without RSA keys
hosts: all
gather_facts: false
vars:
sshd_profile: pve
sshd_settings:
PubkeyAcceptedAlgorithms: "ssh-ed25519"
tasks:
- name: Apply a pve configuration without RSA keys
block:
- name: Include the validation
ansible.builtin.include_role:
name: mortis.kamino.sshd
tasks_from: validate.yml
- name: Fail when the RSA guard was bypassed
ansible.builtin.fail:
msg: the sshd role accepted a pve profile without RSA keys
rescue:
- name: The RSA guard stopped the play
ansible.builtin.assert:
that: "'must both include rsa-sha2-512' in ansible_failed_result.msg | default('')"
quiet: true
- name: The guard refuses SHA-1 ssh-rsa
hosts: all
gather_facts: false
vars:
sshd_profile: pve
sshd_settings:
HostKeyAlgorithms: "ssh-ed25519, rsa-sha2-512, ssh-rsa"
tasks:
- name: Apply a configuration that allows ssh-rsa
block:
- name: Include the validation
ansible.builtin.include_role:
name: mortis.kamino.sshd
tasks_from: validate.yml
- name: Fail when the ssh-rsa guard was bypassed
ansible.builtin.fail:
msg: the sshd role accepted ssh-rsa
rescue:
- name: The ssh-rsa guard stopped the play
ansible.builtin.assert:
that: "'must not list ssh-rsa' in ansible_failed_result.msg | default('')"
quiet: true
- name: An unknown profile is refused
hosts: all
gather_facts: false
vars:
sshd_profile: not_a_profile
tasks:
- name: Apply the role with an unknown profile
block:
- name: Include the validation
ansible.builtin.include_role:
name: mortis.kamino.sshd
tasks_from: validate.yml
- name: Fail when the unknown profile was accepted
ansible.builtin.fail:
msg: the sshd role accepted an unknown profile
rescue:
- name: The profile check stopped the play
ansible.builtin.assert:
that: "'is invalid' in ansible_failed_result.msg | default('')"
quiet: true
+3 -5
View File
@@ -26,10 +26,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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
@@ -41,4 +40,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+158
View File
@@ -1,4 +1,162 @@
---
# The refusal cases: here, not in converge.yml, because idempotence reruns converge. Each
# fails in validate.yml; they run first, so the assertions below also show the host unchanged.
# A play without sshd_profile: the role must refuse it. The block proves the refusal
# (not its wording).
- name: The role refuses a run without a profile
hosts: all
gather_facts: false
tasks:
- name: Missing sshd_profile is rejected
block:
- name: Apply the role without sshd_profile
ansible.builtin.include_role:
name: mortis.kamino.sshd
- name: Fail when the missing profile was accepted
ansible.builtin.fail:
msg: the sshd role accepted a run without sshd_profile
rescue:
- name: The role refused the run
ansible.builtin.debug:
msg: Rejected as expected
- name: The lock-out guard refuses a lock-out
hosts: all
gather_facts: false
vars:
sshd_profile: ubuntu_lxc
sshd_settings:
PubkeyAuthentication: "no"
tasks:
- name: Apply a lock-out configuration
block:
- name: Include the validation
ansible.builtin.include_role:
name: mortis.kamino.sshd
tasks_from: validate.yml
- name: Fail when the lock-out was accepted
ansible.builtin.fail:
msg: the sshd role accepted a lock-out configuration
rescue:
- name: The lock-out guard stopped the play
ansible.builtin.assert:
that: "'lock you out' in ansible_failed_result.msg | default('')"
quiet: true
- name: The Proxmox guard refuses a pve profile without root login
hosts: all
gather_facts: false
vars:
sshd_profile: pve
sshd_settings:
PermitRootLogin: "no"
tasks:
- name: Apply a pve configuration without root login
block:
- name: Include the validation
ansible.builtin.include_role:
name: mortis.kamino.sshd
tasks_from: validate.yml
- name: Fail when the Proxmox guard was bypassed
ansible.builtin.fail:
msg: the sshd role accepted a pve profile without root login
rescue:
- name: The Proxmox guard stopped the play
ansible.builtin.assert:
that: "'needs root public-key login' in ansible_failed_result.msg | default('')"
quiet: true
- name: The Proxmox guard refuses forced-commands-only
hosts: all
gather_facts: false
vars:
sshd_profile: pve
sshd_settings:
PermitRootLogin: forced-commands-only
tasks:
- name: Apply a pve configuration with forced commands only
block:
- name: Include the validation
ansible.builtin.include_role:
name: mortis.kamino.sshd
tasks_from: validate.yml
- name: Fail when the Proxmox guard was bypassed
ansible.builtin.fail:
msg: the sshd role accepted forced-commands-only for the pve profile
rescue:
- name: The Proxmox guard stopped the play
ansible.builtin.assert:
that: "'needs root public-key login' in ansible_failed_result.msg | default('')"
quiet: true
- name: The Proxmox guard refuses a pve profile without RSA keys
hosts: all
gather_facts: false
vars:
sshd_profile: pve
sshd_settings:
PubkeyAcceptedAlgorithms: "ssh-ed25519"
tasks:
- name: Apply a pve configuration without RSA keys
block:
- name: Include the validation
ansible.builtin.include_role:
name: mortis.kamino.sshd
tasks_from: validate.yml
- name: Fail when the RSA guard was bypassed
ansible.builtin.fail:
msg: the sshd role accepted a pve profile without RSA keys
rescue:
- name: The RSA guard stopped the play
ansible.builtin.assert:
that: "'must both include rsa-sha2-512' in ansible_failed_result.msg | default('')"
quiet: true
- name: The guard refuses SHA-1 ssh-rsa
hosts: all
gather_facts: false
vars:
sshd_profile: pve
sshd_settings:
HostKeyAlgorithms: "ssh-ed25519, rsa-sha2-512, ssh-rsa"
tasks:
- name: Apply a configuration that allows ssh-rsa
block:
- name: Include the validation
ansible.builtin.include_role:
name: mortis.kamino.sshd
tasks_from: validate.yml
- name: Fail when the ssh-rsa guard was bypassed
ansible.builtin.fail:
msg: the sshd role accepted ssh-rsa
rescue:
- name: The ssh-rsa guard stopped the play
ansible.builtin.assert:
that: "'must not list ssh-rsa' in ansible_failed_result.msg | default('')"
quiet: true
- name: An unknown profile is refused
hosts: all
gather_facts: false
vars:
sshd_profile: not_a_profile
tasks:
- name: Apply the role with an unknown profile
block:
- name: Include the validation
ansible.builtin.include_role:
name: mortis.kamino.sshd
tasks_from: validate.yml
- name: Fail when the unknown profile was accepted
ansible.builtin.fail:
msg: the sshd role accepted an unknown profile
rescue:
- name: The profile check stopped the play
ansible.builtin.assert:
that: "'is invalid' in ansible_failed_result.msg | default('')"
quiet: true
# Lock-out signals only: the drop-in is in place, the daemon accepts the config and
# runs, and the effective settings keep key authentication on and passwords and
# root login off. The remaining hardening values restate the role's own defaults
@@ -32,10 +32,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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
@@ -47,4 +46,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+4 -3
View File
@@ -4,7 +4,7 @@ Disables and masks risky services, writes a systemd manager hardening drop-in an
## Supported platforms
Hosts with systemd and `systemctl list-unit-files`: Ubuntu 24.04 (noble) LXCs, Ubuntu 22.04 (jammy) VMs and Debian 13 (trixie) Proxmox hosts. The role is applied to the three system types in `systemd_hardening_profiles`: `pve` (Proxmox hosts), `ubuntu_lxc` and `ubuntu_vm`. The molecule scenario (`molecule/default/`, CI only) runs the `ubuntu_lxc` profile on Ubuntu 24.04 against stub unit files, because the test image installs none of the services the role disables or masks. It checks the disable and mask results, the manager and service drop-ins (loaded by systemd after the reload) and the refusals; it cannot show that a real `rpcbind` or similar stops. The `pve` and `ubuntu_vm` profiles and Ubuntu 22.04 and Debian 13 are not verified by a test.
Hosts with systemd: Ubuntu 24.04 (noble) LXCs, Ubuntu 22.04 (jammy) VMs and Debian 13 (trixie) Proxmox hosts. The role is applied to the three system types in `systemd_hardening_profiles`: `pve` (Proxmox hosts), `ubuntu_lxc` and `ubuntu_vm`. The molecule scenario (`molecule/default/`, CI only) runs the `ubuntu_lxc` profile on Ubuntu 24.04 against stub unit files (a socket and a service for the ones that ship both, a service only and a socket only for the others), because the test image installs none of the services the role disables or masks. It checks that the stub sockets and services end up stopped and disabled or masked, that a listed unit that does not exist is skipped, the manager and service drop-ins (loaded by systemd after the reload) and the refusals; it cannot show that a real `rpcbind` or similar stops. The `pve` and `ubuntu_vm` profiles and Ubuntu 22.04 and Debian 13 are not verified by a test.
## Requirements and run order
@@ -29,7 +29,7 @@ Two variables below, `systemd_hardening_disable_services_extra` and `systemd_har
## Tags
Only `always` (the `systemd_hardening_system_type` assert) works as intended. `disable`, `mask`, `harden-manager` and `dropins` sit on the `include_tasks` lines in `tasks/main.yml`, and tags on a dynamic include select only the include itself: the included tasks are untagged, so they are skipped. `--tags disable` or `--tags mask` therefore runs only the assert and the unit listing, and `--tags harden-manager` or `--tags dropins` runs only the assert. Do not use these tags for selective runs; run the role untagged.
Only `always` (the `systemd_hardening_system_type` assert) works as intended. `disable`, `mask`, `harden-manager` and `dropins` sit on the `include_tasks` lines in `tasks/main.yml`, and tags on a dynamic include select only the include itself: the included tasks are untagged, so they are skipped. `--tags disable` or `--tags mask` therefore runs only the assert and the unit lookup, and `--tags harden-manager` or `--tags dropins` runs only the assert. Do not use these tags for selective runs; run the role untagged.
## Example play
@@ -49,7 +49,8 @@ Only `always` (the `systemd_hardening_system_type` assert) works as intended. `d
## Notes
- Only units that appear in `systemctl list-unit-files --type=service` are disabled or masked, with or without the `.service` suffix.
- Every name in `systemd_hardening_disable_services` and `systemd_hardening_mask_services` is looked up as a socket and as a service, with or without the `.service` or `.socket` suffix. Only units that systemd has a unit file for (`LoadState` is not `not-found`) are disabled or masked, the socket first: a stopped service whose socket still listens is started again by the next connection. A name with only a service, only a socket, or neither is fine. The role asks about the listed units only, with one `systemctl show`, and does not list every unit file. A template name such as `[email protected]` is not supported: that call fails.
- `systemctl disable` does nothing for a static unit (one with no `[Install]` section), so the systemd module can report `changed` on every run for it; list only names whose units can be enabled, and note that this now applies to a listed name's socket as well.
- The manager drop-in (`DefaultLimitNOFILE`, `DefaultLimitNPROC`, `DefaultLimitCORE`, and task, memory and CPU accounting) is written verbatim by `tasks/harden_manager.yml` and has no variable.
- Drop-in and manager changes notify `systemd reload`, which runs `daemon-reload`. Handlers are flushed at the end of the role.
- Policy lives in defaults, not `vars/`, so group_vars and host_vars can override it.
@@ -7,7 +7,9 @@ argument_specs:
Validates C(systemd_hardening_system_type) against C(systemd_hardening_profiles), then disables the unwanted services and masks the high-risk
services that have an installed unit file, writes C(/etc/systemd/system.conf.d/hardening.conf) and renders a drop-in for every
unit in C(systemd_hardening_services).
- Units that are not installed are skipped. Handlers are flushed at the end of the role.
- >-
Every listed name is handled as a socket and as a service, the socket first; units that are not installed are skipped.
Handlers are flushed at the end of the role.
- >-
The role also reads C(systemd_hardening_disable_services_extra) (default is the profile entry for C(systemd_hardening_system_type)) and the
derived C(systemd_hardening_disable_services_effective) (the base list plus the extra list, a result, do not set it). They are
@@ -35,13 +37,17 @@ argument_specs:
elements: str
default: [rpcbind, avahi-daemon, cups, bluetooth, nfs-server]
description:
- Services stopped and disabled on every system type, with or without the C(.service) suffix. Only installed units are touched.
- >-
Services stopped and disabled on every system type, with or without the C(.service) or C(.socket) suffix, together with the
socket of the same name. Only installed units are touched.
systemd_hardening_mask_services:
type: list
elements: str
default: [telnet, rsh, rlogin, xinetd]
description:
- Services masked and stopped. Only installed units are touched.
- >-
Services masked and stopped, with or without the C(.service) or C(.socket) suffix, together with the socket of the same name.
Only installed units are touched.
systemd_hardening_services:
type: dict
default: {}
@@ -25,10 +25,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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
@@ -40,4 +39,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
@@ -1,8 +1,12 @@
---
# The image installs none of the services the role touches, so the units it acts on are
# stubs in /usr/lib/systemd/system (not /etc: `systemctl mask` refuses to replace a regular
# file there). Nothing is started. rpcbind is enabled so the role has something to
# disable; telnet only needs to exist; testsvc receives the drop-in.
# file there). rpcbind and telnet are a socket and a service each, as the real packages ship them;
# cups has only a service and bluetooth only a socket (its Service= is a stub of another name:
# systemd refuses to start a socket whose service is not loaded), so the role meets every shape. The sockets
# listen on a unix socket under /run and are started, so the role has something to stop. rpcbind,
# cups and bluetooth are enabled so the role has something to disable; telnet only needs to
# exist; testsvc receives the drop-in.
- name: Prepare
hosts: all
gather_facts: false
@@ -22,10 +26,35 @@
owner: root
group: root
mode: "0644"
loop: [rpcbind, telnet, testsvc]
loop: [rpcbind, telnet, cups, testsvc, molecule-bluetooth-target]
- name: Enable rpcbind and reload systemd
- name: Install the stub socket unit files
ansible.builtin.copy:
dest: "/usr/lib/systemd/system/{{ item }}.socket"
content: |
[Unit]
Description=molecule stub socket for {{ item }}
[Socket]
ListenStream=/run/molecule-{{ item }}.sock
{% if item == 'bluetooth' %}
Service=molecule-bluetooth-target.service
{% endif %}
[Install]
WantedBy=sockets.target
owner: root
group: root
mode: "0644"
loop: [rpcbind, telnet, bluetooth]
- name: Reload systemd
ansible.builtin.systemd:
name: rpcbind
enabled: true
daemon_reload: true
- name: Enable and start the stub sockets and services
ansible.builtin.systemd:
name: "{{ item }}"
enabled: true
state: started
loop: [rpcbind.socket, telnet.socket, bluetooth.socket, rpcbind.service, cups.service, telnet.service]
@@ -8,17 +8,45 @@
tasks:
- name: Ask systemd about the stub units
ansible.builtin.systemd:
name: "{{ item }}.service"
loop: [rpcbind, telnet]
name: "{{ item }}"
loop: [rpcbind.socket, rpcbind.service, cups.service, bluetooth.socket, telnet.socket, telnet.service]
register: systemd_hardening_verify_units
check_mode: true
- name: The disabled unit is disabled and the masked unit is masked
- name: The disabled units, sockets and services alike, are disabled and stopped
ansible.builtin.assert:
that:
- systemd_hardening_verify_units.results[0].status.UnitFileState == "disabled"
- systemd_hardening_verify_units.results[1].status.UnitFileState == "masked"
- item.status.UnitFileState == "disabled"
- item.status.ActiveState == "inactive"
quiet: true
loop: "{{ systemd_hardening_verify_units.results | rejectattr('item', 'match', '^telnet[.]') | list }}"
loop_control:
label: "{{ item.item }}"
- name: The masked units, socket and service, are masked and stopped
ansible.builtin.assert:
that:
- item.status.UnitFileState == "masked"
- item.status.ActiveState == "inactive"
quiet: true
loop: "{{ systemd_hardening_verify_units.results | selectattr('item', 'match', '^telnet[.]') | list }}"
loop_control:
label: "{{ item.item }}"
- name: Ask systemd about the listed units that are not installed
ansible.builtin.command: systemctl show --property=LoadState {{ item }} # noqa: command-instead-of-module
loop: [cups.socket, bluetooth.service, rsh.service, rsh.socket]
register: systemd_hardening_verify_absent
changed_when: false
- name: The missing units were skipped, not masked or created
ansible.builtin.assert:
that:
- item.stdout == "LoadState=not-found"
quiet: true
loop: "{{ systemd_hardening_verify_absent.results }}"
loop_control:
label: "{{ item.item }}"
- name: Read the manager drop-in
ansible.builtin.slurp:
@@ -1,11 +1,12 @@
---
# Every installed socket and service of a listed name is stopped and disabled, the socket first: a
# stopped service whose socket is still listening is started again by the next connection.
- name: Disable unwanted services if present
become: true
ansible.builtin.systemd:
name: "{{ item }}"
enabled: false
state: stopped
loop: "{{ systemd_hardening_disable_services_effective }}"
# Only act on installed units; items may be given with or without the
# ".service" suffix.
when: (item | regex_replace('\.service$', '') ~ '.service') in systemd_hardening_installed_units
loop: >-
{{ systemd_hardening_disable_services_effective | map('regex_replace', '[.](service|socket)$', '') | unique
| product(['socket', 'service']) | map('join', '.') | select('in', systemd_hardening_installed_units) | list }}
+36 -14
View File
@@ -20,22 +20,44 @@
success_msg: "systemd_hardening_system_type '{{ systemd_hardening_system_type }}' is valid."
tags: always
# Not service_facts: it returns a fact named `services`, which (with
# inject_facts_as_vars) overrides any inventory variable of that name, such as
# a list of services a playbook installs. Only installed unit files are listed,
# so units that are merely referenced (LoadState not-found) are excluded.
- name: List installed service unit files # noqa: command-instead-of-module
become: true
ansible.builtin.command: systemctl list-unit-files --type=service --no-legend --plain
register: systemd_hardening_unit_files
changed_when: false
check_mode: false
# Ask systemd about the listed units only: listing every unit file keeps PID 1 busy for as long as
# the host has unit files, which on slow storage can outlast a short hardware watchdog. `systemctl show`
# prints one block per argument in the order given, `LoadState=not-found` for a unit with no unit
# file, and keeps the order for an alias. Not service_facts: it sets a fact named `services`, which
# overrides an inventory variable of that name.
# Every listed name is looked up as a socket and as a service, socket first: stopping a service
# whose socket is still listening does not close the port, systemd starts the service again on the
# next connection. A name may be given with or without .service or .socket.
- name: Find which of the listed units are installed
tags: [disable, mask]
vars:
__systemd_hardening_probe_units: >-
{{ (systemd_hardening_disable_services_effective + systemd_hardening_mask_services)
| map('regex_replace', '[.](service|socket)$', '') | unique
| product(['socket', 'service']) | map('join', '.') | list }}
block:
- name: Look up the listed units # noqa: command-instead-of-module
become: true
ansible.builtin.command:
argv: "{{ ['systemctl', 'show', '--property=LoadState', '--'] + __systemd_hardening_probe_units }}"
register: __systemd_hardening_probe
changed_when: false
check_mode: false
when: __systemd_hardening_probe_units | length > 0
- name: Set installed service units
ansible.builtin.set_fact:
systemd_hardening_installed_units: "{{ systemd_hardening_unit_files.stdout_lines | map('split') | map('first') | list }}"
tags: [disable, mask]
- name: Set installed units
ansible.builtin.set_fact:
systemd_hardening_installed_units: >-
{{ __systemd_hardening_probe_units | zip(__systemd_hardening_probe_states)
| rejectattr('1', 'eq', 'LoadState=not-found') | map(attribute='0') | list }}
vars:
__systemd_hardening_probe_states: "{{ (__systemd_hardening_probe.stdout | default('')).strip().split('\n\n') }}"
when: __systemd_hardening_probe_units | length > 0
- name: Set no installed units
ansible.builtin.set_fact:
systemd_hardening_installed_units: []
when: __systemd_hardening_probe_units | length == 0
- name: Disable unwanted services
ansible.builtin.include_tasks: disable_services.yml
@@ -1,10 +1,12 @@
---
# Same shape as disable_services.yml: every installed socket and service of a listed name is masked, the socket first.
# A unit that is not installed can't be started, so masking it is unnecessary.
- name: Mask high-risk services
become: true
ansible.builtin.systemd:
name: "{{ item }}"
masked: true
state: stopped
loop: "{{ systemd_hardening_mask_services }}"
# A unit that isn't installed can't be started, so masking it is unnecessary.
when: (item | regex_replace('\.service$', '') ~ '.service') in systemd_hardening_installed_units
loop: >-
{{ systemd_hardening_mask_services | map('regex_replace', '[.](service|socket)$', '') | unique
| product(['socket', 'service']) | map('join', '.') | select('in', systemd_hardening_installed_units) | list }}
+2 -47
View File
@@ -1,6 +1,6 @@
---
# Role variables come from the inventory group_vars in molecule.yml, so every play
# renders identical configuration (idempotence).
# Role variables come from the inventory group_vars in molecule.yml, so the idempotence step
# reruns converge with identical configuration; verify's plays override only what they test.
# The base ufw play comes first: traefik passes its rules through the mortis.kamino.ufw
# service_rules entry point, which needs ufw installed and active. ufw_rules comes from the
# same group_vars (the SSH allow rule the lock-out guard requires).
@@ -10,48 +10,3 @@
roles:
- role: mortis.kamino.ufw
- role: mortis.kamino.traefik
- name: Refuse an enabled dashboard without basicAuth users
hosts: all
gather_facts: false
tasks:
- name: Run the role with the dashboard on and no users
block:
- name: Include traefik
ansible.builtin.include_role:
name: mortis.kamino.traefik
vars:
traefik_dashboard_enabled: true
traefik_dashboard_basicauth_users: []
- name: Unreachable when the guard works
ansible.builtin.fail:
msg: traefik accepted an enabled dashboard without users
rescue:
- name: The dashboard guard, not something else, stopped the play
ansible.builtin.assert:
that: "'unauthenticated Traefik dashboard' in ansible_failed_result.msg | default('')"
quiet: true
- name: Refuse a dashboard-auth middleware collision
hosts: all
gather_facts: false
tasks:
- name: Run the role with a colliding middleware
block:
- name: Include traefik
ansible.builtin.include_role:
name: mortis.kamino.traefik
vars:
traefik_dashboard_basicauth_users:
- "admin:$apr1$x$y"
traefik_dynamic_middlewares:
dashboard-auth:
basicAuth: {users: []}
- name: Unreachable when the check works
ansible.builtin.fail:
msg: traefik accepted a colliding dashboard-auth middleware
rescue:
- name: The collision check, not something else, stopped the play
ansible.builtin.assert:
that: "'collides with the middleware' in ansible_failed_result.msg | default('')"
quiet: true
+6 -8
View File
@@ -23,9 +23,9 @@ platforms:
- apparmor=unconfined
provisioner:
name: ansible
# One source for every play in converge.yml. The role renders traefik.yml before
# its dashboard guard and its dashboard-auth collision check, so a play that included it with other
# values would re-render the file and break the idempotence step.
# One source for every play in converge.yml and verify.yml. The role renders traefik.yml before
# its dashboard-auth collision check, so that guard play with other values would change it (and
# restart Traefik) before verify's assertions; converge's values must also stay fixed for idempotence.
inventory:
group_vars:
all:
@@ -46,10 +46,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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
@@ -61,4 +60,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+49
View File
@@ -1,4 +1,53 @@
---
# The input guards. Both fail after the role's prereqs (packages already present), and the
# collision case re-renders traefik.yml from the same group_vars with the dashboard still off,
# so neither changes the host. They run first, so every assertion below also shows that; the
# remove path stays last, since after it the role would install Traefik again.
- name: Refuse an enabled dashboard without basicAuth users
hosts: all
gather_facts: false
tasks:
- name: Run the role with the dashboard on and no users
block:
- name: Include traefik
ansible.builtin.include_role:
name: mortis.kamino.traefik
vars:
traefik_dashboard_enabled: true
traefik_dashboard_basicauth_users: []
- name: Unreachable when the guard works
ansible.builtin.fail:
msg: traefik accepted an enabled dashboard without users
rescue:
- name: The dashboard guard, not something else, stopped the play
ansible.builtin.assert:
that: "'unauthenticated Traefik dashboard' in ansible_failed_result.msg | default('')"
quiet: true
- name: Refuse a dashboard-auth middleware collision
hosts: all
gather_facts: false
tasks:
- name: Run the role with a colliding middleware
block:
- name: Include traefik
ansible.builtin.include_role:
name: mortis.kamino.traefik
vars:
traefik_dashboard_basicauth_users:
- "admin:$apr1$x$y"
traefik_dynamic_middlewares:
dashboard-auth:
basicAuth: {users: []}
- name: Unreachable when the check works
ansible.builtin.fail:
msg: traefik accepted a colliding dashboard-auth middleware
rescue:
- name: The collision check, not something else, stopped the play
ansible.builtin.assert:
that: "'collides with the middleware' in ansible_failed_result.msg | default('')"
quiet: true
- name: Verify
hosts: all
gather_facts: false
+1 -302
View File
@@ -1,117 +1,5 @@
---
# Lock-out guard: default-deny without an SSH allow rule must be refused before
# any policy is touched.
- name: Refuse default-deny without an SSH allow rule
hosts: all
gather_facts: false
tasks:
- name: Run the role with only a non-SSH rule
block:
- name: Include ufw
ansible.builtin.include_role:
name: mortis.kamino.ufw
vars:
ufw_rules:
- {rule: allow, port: 8080, proto: tcp}
- name: Unreachable when the guard works
ansible.builtin.fail:
msg: ufw ran without an SSH allow rule
rescue:
- name: The guard, not something else, stopped the play
ansible.builtin.assert:
that: "'would lock this host out' in ansible_failed_result.msg | default('')"
quiet: true
# A delete entry removes the SSH rule it names, so it must not satisfy the guard.
- name: Run the role with an SSH rule that is only deleted
block:
- name: Include ufw
ansible.builtin.include_role:
name: mortis.kamino.ufw
vars:
ufw_rules:
- {rule: allow, port: 8080, proto: tcp}
- {rule: allow, port: 22, proto: tcp, delete: true}
- name: Unreachable when the guard ignores delete entries
ansible.builtin.fail:
msg: ufw counted a deleted SSH rule as the SSH allow rule
rescue:
- name: The guard stopped the play
ansible.builtin.assert:
that: "'would lock this host out' in ansible_failed_result.msg | default('')"
quiet: true
# The same rule added and deleted: the delete would win (deletes run last) while the
# guard counted the add. The comment, the port's type and the written default
# direction and source do not make them different.
- name: Run the role with a rule that is both added and deleted
block:
- name: Include ufw
ansible.builtin.include_role:
name: mortis.kamino.ufw
vars:
ufw_rules:
- {rule: allow, port: "22", proto: tcp, direction: in, from: any, comment: ssh}
- {rule: allow, port: 22, proto: tcp, delete: true}
- name: Unreachable when the conflict check works
ansible.builtin.fail:
msg: ufw accepted a rule that is both added and deleted
rescue:
- name: The conflict check stopped the play
ansible.builtin.assert:
that: "'both added and deleted' in ansible_failed_result.msg | default('')"
quiet: true
# Stray variable guard: variables named like <role>_ufw_rules must fail the play
# before anything changes, naming the variable. The vars sit on the include only, so they
# do not reach the plays below (the base ufw_rules and ufw_before_rules never match).
- name: Refuse stray variables named like the old *_ufw_rules
hosts: all
gather_facts: false
tasks:
- name: A stray *_ufw_rules variable
block:
- name: Include ufw with a stray rules variable
ansible.builtin.include_role:
name: mortis.kamino.ufw
vars:
ufw_rules:
- {rule: allow, port: 22, proto: tcp, comment: ssh}
stray_ufw_rules: # noqa: var-naming[no-role-prefix]
- {rule: allow, port: 7999, proto: tcp, comment: stray}
- name: Unreachable when the stray variable guard works
ansible.builtin.fail:
msg: a stray *_ufw_rules variable was accepted
rescue:
- name: The stray guard, not something else, stopped the play
ansible.builtin.assert:
that:
- "'stray_ufw_rules' in ansible_failed_result.msg | default('')"
- "'stray_ufw_before_rules' not in ansible_failed_result.msg | default('')"
- "'service_rules' in ansible_failed_result.msg | default('')"
quiet: true
- name: A stray *_ufw_before_rules variable
block:
- name: Include ufw with a stray before-rules variable
ansible.builtin.include_role:
name: mortis.kamino.ufw
vars:
ufw_rules:
- {rule: allow, port: 22, proto: tcp, comment: ssh}
stray_ufw_before_rules: # noqa: var-naming[no-role-prefix]
- {proto: udp, port: 7998, comment: stray}
- name: Unreachable when the stray variable guard works
ansible.builtin.fail:
msg: a stray *_ufw_before_rules variable was accepted
rescue:
- name: The stray guard, not something else, stopped the play
ansible.builtin.assert:
that:
- "'stray_ufw_before_rules' in ansible_failed_result.msg | default('')"
- "'stray_ufw_rules' not in ansible_failed_result.msg | default('')"
quiet: true
# Only runs that apply the role; the refusal cases are in verify.yml.
- name: Converge with an SSH rule and service rules
hosts: all
gather_facts: true
@@ -218,171 +106,6 @@
ufw_service_rules:
- {rule: allow, port: 7602, proto: tcp, comment: desired}
# Inputs the entry point must refuse, each before it changes anything. Every block
# proves the refusal and its message; the play still passes, so the idempotence run
# stays clean and verify.yml proves no rule was left behind.
- name: Refuse invalid service rule inputs
hosts: all
gather_facts: false
vars:
# A failed looped task reports "One or more items failed" in msg and the item
# messages in results; an unlooped one has the message in msg.
ufw_converge_failure: >-
{{ ansible_failed_result.msg | default('') }}
{{ ansible_failed_result.results | default([]) | map(attribute='msg', default='') | join(' ') }}
tasks:
- name: An owner name outside the allowed characters
block:
- name: Include with an invalid owner name
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
vars:
ufw_service_name: Bad-Name
ufw_service_rules:
- {rule: allow, port: 8101, proto: tcp}
- name: Unreachable when the owner name is checked
ansible.builtin.fail:
msg: an invalid owner name was accepted
rescue:
- name: The owner check stopped the play
ansible.builtin.assert:
that: "'ufw_service_name must be a string matching' in ufw_converge_failure"
quiet: true
- name: The reserved owner base
block:
- name: Include as base
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
vars:
ufw_service_name: base
ufw_service_rules:
- {rule: allow, port: 8102, proto: tcp}
- name: Unreachable when base is reserved
ansible.builtin.fail:
msg: the reserved owner base was accepted
rescue:
- name: The reserved name stopped the play
ansible.builtin.assert:
that: "'reserved for the base play' in ufw_converge_failure"
quiet: true
- name: A single quote in a comment
block:
- name: Include with a quote in the comment
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
vars:
ufw_service_name: svc_f
ufw_service_rules:
- {rule: allow, port: 8103, proto: tcp, comment: "it's"}
- name: Unreachable when comments are checked
ansible.builtin.fail:
msg: a quote in a comment was accepted
rescue:
- name: The comment check stopped the play
ansible.builtin.assert:
that: "'single quote' in ufw_converge_failure"
quiet: true
- name: A rule another owner already holds
block:
- name: Include with the spec of a svc_a rule
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
vars:
ufw_service_name: svc_f
ufw_service_rules:
- {rule: allow, port: 8001, proto: tcp, comment: other text}
- name: Unreachable when collisions are checked
ansible.builtin.fail:
msg: a rule owned by svc_a was accepted for svc_f
rescue:
- name: The collision check stopped the play
ansible.builtin.assert:
that: "'already owned by another tag' in ufw_converge_failure"
quiet: true
- name: A rule that would retag the SSH rule
block:
- name: Include with an allow rule for the SSH port
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
vars:
ufw_service_name: svc_f
ufw_service_rules:
- {rule: allow, port: 22, proto: tcp}
- name: Unreachable when the SSH port is protected
ansible.builtin.fail:
msg: a service rule for the SSH port was accepted
rescue:
- name: The SSH check stopped the play
ansible.builtin.assert:
that: "'allows the SSH port' in ufw_converge_failure"
quiet: true
- name: An unknown rule key
block:
- name: Include with a to_port key
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
vars:
ufw_service_name: svc_f
ufw_service_rules:
- {rule: allow, to_port: 8104, proto: tcp}
- name: Unreachable when keys are checked
ansible.builtin.fail:
msg: an unknown rule key was accepted
rescue:
- name: The key check stopped the play
ansible.builtin.assert:
that: "'has an unknown key' in ufw_converge_failure"
quiet: true
- name: An interface without a direction
block:
- name: Include with an interface and no direction
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
vars:
ufw_service_name: svc_f
ufw_service_rules:
- {rule: allow, port: 8105, proto: tcp, interface: eth0}
- name: Unreachable when the direction is required
ansible.builtin.fail:
msg: an interface without a direction was accepted
rescue:
- name: The direction check stopped the play
ansible.builtin.assert:
that: "'interface without direction' in ufw_converge_failure"
quiet: true
- name: Purging with an empty rule list
block:
- name: Include with an empty list and ufw_purge_stale
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
vars:
ufw_service_name: svc_a
ufw_purge_stale: true
ufw_service_rules: []
- name: Unreachable when an empty list is refused
ansible.builtin.fail:
msg: an empty list with ufw_purge_stale was accepted
rescue:
- name: The empty list stopped the play
ansible.builtin.assert:
that: "'use ufw_service_state: absent' in ufw_converge_failure"
quiet: true
# The orphan_rules entry point. prepare.yml stored two rules of svc_o1, a rule of
# svc_o2 that looks like the SSH rule, and a rule of svc_m. The managed owners below are
# the ones used above plus svc_m (listed but never called), so svc_o1 and svc_o2 are
@@ -403,9 +126,6 @@
- svc_h
- svc_m
- svc_p
ufw_converge_failure: >-
{{ ansible_failed_result.msg | default('') }}
{{ ansible_failed_result.results | default([]) | map(attribute='msg', default='') | join(' ') }}
tasks:
# The marker is written after the purge, so the expected counts are absolute on both
# passes: svc_o1 holds 2 rules before the purge and 0 once the marker exists.
@@ -442,27 +162,6 @@
- name: Nothing was deleted with an empty list
ansible.builtin.include_tasks: tasks/orphan_check.yml
- name: An invalid managed owner
block:
- name: Include with an owner name outside the allowed characters
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: orphan_rules
vars:
ufw_managed_owners: [svc_a, Bad-Name]
ufw_purge_orphans: true
- name: Unreachable when the owners are checked
ansible.builtin.fail:
msg: an invalid managed owner was accepted
rescue:
- name: The owner check stopped the play
ansible.builtin.assert:
that: "'ufw_managed_owners must be a list of strings matching' in ufw_converge_failure"
quiet: true
- name: Nothing was deleted after the invalid owner
ansible.builtin.include_tasks: tasks/orphan_check.yml
- name: Report the orphans only
ansible.builtin.include_role:
name: mortis.kamino.ufw
+3 -5
View File
@@ -25,10 +25,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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
@@ -40,4 +39,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
@@ -1,9 +1,9 @@
---
# Included by converge.yml after each orphan_rules case. The counts are absolute: svc_o1
# holds ufw_conv_o1_want rules (default ufw_conv_o1_initial: 2 before the purge, 0 after),
# and the tagged total is 20 plus those. The 20: svc_a 2, svc_b 2, svc_c 1, svc_e 2, svc_g 1,
# svc_h 2, svc_m 1, svc_o2 1, svc_o3 4 (kept orphans that may carry SSH), svc_p 4 (its
# desired rule and three kept stale rules).
# Included by converge.yml and verify.yml after each orphan_rules case. The counts are
# absolute: svc_o1 holds ufw_conv_o1_want rules (default ufw_conv_o1_initial: 2 before the
# purge, 0 after), and the tagged total is 20 plus those. The 20: svc_a 2, svc_b 2, svc_c 1,
# svc_e 2, svc_g 1, svc_h 2, svc_m 1, svc_o2 1, svc_o3 4 (kept orphans that may carry SSH),
# svc_p 4 (its desired rule and three kept stale rules).
- name: Read the rules ufw would load
ansible.builtin.command: ufw show added
register: ufw_conv_added
+314 -1
View File
@@ -1,4 +1,317 @@
---
# The refusal cases run first, so every assertion below also proves a refused run left the
# host unchanged. They are not in converge.yml because idempotence reruns it.
# Lock-out guard: default-deny without an SSH allow rule must be refused before
# any policy is touched.
- name: Refuse default-deny without an SSH allow rule
hosts: all
gather_facts: false
tasks:
- name: Run the role with only a non-SSH rule
block:
- name: Include ufw
ansible.builtin.include_role:
name: mortis.kamino.ufw
vars:
ufw_rules:
- {rule: allow, port: 8080, proto: tcp}
- name: Unreachable when the guard works
ansible.builtin.fail:
msg: ufw ran without an SSH allow rule
rescue:
- name: The guard, not something else, stopped the play
ansible.builtin.assert:
that: "'would lock this host out' in ansible_failed_result.msg | default('')"
quiet: true
# A delete entry removes the SSH rule it names, so it must not satisfy the guard.
- name: Run the role with an SSH rule that is only deleted
block:
- name: Include ufw
ansible.builtin.include_role:
name: mortis.kamino.ufw
vars:
ufw_rules:
- {rule: allow, port: 8080, proto: tcp}
- {rule: allow, port: 22, proto: tcp, delete: true}
- name: Unreachable when the guard ignores delete entries
ansible.builtin.fail:
msg: ufw counted a deleted SSH rule as the SSH allow rule
rescue:
- name: The guard stopped the play
ansible.builtin.assert:
that: "'would lock this host out' in ansible_failed_result.msg | default('')"
quiet: true
# The same rule added and deleted: the delete would win (deletes run last) while the
# guard counted the add. The comment, the port's type and the written default
# direction and source do not make them different.
- name: Run the role with a rule that is both added and deleted
block:
- name: Include ufw
ansible.builtin.include_role:
name: mortis.kamino.ufw
vars:
ufw_rules:
- {rule: allow, port: "22", proto: tcp, direction: in, from: any, comment: ssh}
- {rule: allow, port: 22, proto: tcp, delete: true}
- name: Unreachable when the conflict check works
ansible.builtin.fail:
msg: ufw accepted a rule that is both added and deleted
rescue:
- name: The conflict check stopped the play
ansible.builtin.assert:
that: "'both added and deleted' in ansible_failed_result.msg | default('')"
quiet: true
# Stray variable guard: variables named like <role>_ufw_rules must fail the play
# before anything changes, naming the variable. The vars sit on the include only, so they
# do not reach the plays below (the base ufw_rules and ufw_before_rules never match).
- name: Refuse stray variables named like the old *_ufw_rules
hosts: all
gather_facts: false
tasks:
- name: A stray *_ufw_rules variable
block:
- name: Include ufw with a stray rules variable
ansible.builtin.include_role:
name: mortis.kamino.ufw
vars:
ufw_rules:
- {rule: allow, port: 22, proto: tcp, comment: ssh}
stray_ufw_rules: # noqa: var-naming[no-role-prefix]
- {rule: allow, port: 7999, proto: tcp, comment: stray}
- name: Unreachable when the stray variable guard works
ansible.builtin.fail:
msg: a stray *_ufw_rules variable was accepted
rescue:
- name: The stray guard, not something else, stopped the play
ansible.builtin.assert:
that:
- "'stray_ufw_rules' in ansible_failed_result.msg | default('')"
- "'stray_ufw_before_rules' not in ansible_failed_result.msg | default('')"
- "'service_rules' in ansible_failed_result.msg | default('')"
quiet: true
- name: A stray *_ufw_before_rules variable
block:
- name: Include ufw with a stray before-rules variable
ansible.builtin.include_role:
name: mortis.kamino.ufw
vars:
ufw_rules:
- {rule: allow, port: 22, proto: tcp, comment: ssh}
stray_ufw_before_rules: # noqa: var-naming[no-role-prefix]
- {proto: udp, port: 7998, comment: stray}
- name: Unreachable when the stray variable guard works
ansible.builtin.fail:
msg: a stray *_ufw_before_rules variable was accepted
rescue:
- name: The stray guard, not something else, stopped the play
ansible.builtin.assert:
that:
- "'stray_ufw_before_rules' in ansible_failed_result.msg | default('')"
- "'stray_ufw_rules' not in ansible_failed_result.msg | default('')"
quiet: true
# Inputs the entry point must refuse, each before it changes anything. Every block
# proves the refusal and its message; the Verify play proves no rule was left behind.
- name: Refuse invalid service rule inputs
hosts: all
gather_facts: false
vars:
# A failed looped task reports "One or more items failed" in msg and the item
# messages in results; an unlooped one has the message in msg.
ufw_verify_failure: >-
{{ ansible_failed_result.msg | default('') }}
{{ ansible_failed_result.results | default([]) | map(attribute='msg', default='') | join(' ') }}
tasks:
- name: An owner name outside the allowed characters
block:
- name: Include with an invalid owner name
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
vars:
ufw_service_name: Bad-Name
ufw_service_rules:
- {rule: allow, port: 8101, proto: tcp}
- name: Unreachable when the owner name is checked
ansible.builtin.fail:
msg: an invalid owner name was accepted
rescue:
- name: The owner check stopped the play
ansible.builtin.assert:
that: "'ufw_service_name must be a string matching' in ufw_verify_failure"
quiet: true
- name: The reserved owner base
block:
- name: Include as base
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
vars:
ufw_service_name: base
ufw_service_rules:
- {rule: allow, port: 8102, proto: tcp}
- name: Unreachable when base is reserved
ansible.builtin.fail:
msg: the reserved owner base was accepted
rescue:
- name: The reserved name stopped the play
ansible.builtin.assert:
that: "'reserved for the base play' in ufw_verify_failure"
quiet: true
- name: A single quote in a comment
block:
- name: Include with a quote in the comment
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
vars:
ufw_service_name: svc_f
ufw_service_rules:
- {rule: allow, port: 8103, proto: tcp, comment: "it's"}
- name: Unreachable when comments are checked
ansible.builtin.fail:
msg: a quote in a comment was accepted
rescue:
- name: The comment check stopped the play
ansible.builtin.assert:
that: "'single quote' in ufw_verify_failure"
quiet: true
- name: A rule another owner already holds
block:
- name: Include with the spec of a svc_a rule
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
vars:
ufw_service_name: svc_f
ufw_service_rules:
- {rule: allow, port: 8001, proto: tcp, comment: other text}
- name: Unreachable when collisions are checked
ansible.builtin.fail:
msg: a rule owned by svc_a was accepted for svc_f
rescue:
- name: The collision check stopped the play
ansible.builtin.assert:
that: "'already owned by another tag' in ufw_verify_failure"
quiet: true
- name: A rule that would retag the SSH rule
block:
- name: Include with an allow rule for the SSH port
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
vars:
ufw_service_name: svc_f
ufw_service_rules:
- {rule: allow, port: 22, proto: tcp}
- name: Unreachable when the SSH port is protected
ansible.builtin.fail:
msg: a service rule for the SSH port was accepted
rescue:
- name: The SSH check stopped the play
ansible.builtin.assert:
that: "'allows the SSH port' in ufw_verify_failure"
quiet: true
- name: An unknown rule key
block:
- name: Include with a to_port key
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
vars:
ufw_service_name: svc_f
ufw_service_rules:
- {rule: allow, to_port: 8104, proto: tcp}
- name: Unreachable when keys are checked
ansible.builtin.fail:
msg: an unknown rule key was accepted
rescue:
- name: The key check stopped the play
ansible.builtin.assert:
that: "'has an unknown key' in ufw_verify_failure"
quiet: true
- name: An interface without a direction
block:
- name: Include with an interface and no direction
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
vars:
ufw_service_name: svc_f
ufw_service_rules:
- {rule: allow, port: 8105, proto: tcp, interface: eth0}
- name: Unreachable when the direction is required
ansible.builtin.fail:
msg: an interface without a direction was accepted
rescue:
- name: The direction check stopped the play
ansible.builtin.assert:
that: "'interface without direction' in ufw_verify_failure"
quiet: true
- name: Purging with an empty rule list
block:
- name: Include with an empty list and ufw_purge_stale
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
vars:
ufw_service_name: svc_a
ufw_purge_stale: true
ufw_service_rules: []
- name: Unreachable when an empty list is refused
ansible.builtin.fail:
msg: an empty list with ufw_purge_stale was accepted
rescue:
- name: The empty list stopped the play
ansible.builtin.assert:
that: "'use ufw_service_state: absent' in ufw_verify_failure"
quiet: true
# An orphan_rules input the entry point must refuse before it reads or deletes a rule.
- name: Refuse an invalid managed owner
hosts: all
gather_facts: false
vars:
ufw_verify_failure: >-
{{ ansible_failed_result.msg | default('') }}
{{ ansible_failed_result.results | default([]) | map(attribute='msg', default='') | join(' ') }}
tasks:
- name: An invalid managed owner
block:
- name: Include with an owner name outside the allowed characters
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: orphan_rules
vars:
ufw_managed_owners: [svc_a, Bad-Name]
ufw_purge_orphans: true
- name: Unreachable when the owners are checked
ansible.builtin.fail:
msg: an invalid managed owner was accepted
rescue:
- name: The owner check stopped the play
ansible.builtin.assert:
that: "'ufw_managed_owners must be a list of strings matching' in ufw_verify_failure"
quiet: true
# Converge's last play purged svc_o1 (want 0); svc_o2, svc_m and the tagged total carry the proof.
- name: Nothing was deleted after the invalid owner
ansible.builtin.include_tasks: tasks/orphan_check.yml
vars:
ufw_conv_o1_want: 0
- name: Verify
hosts: all
gather_facts: false
@@ -41,7 +354,7 @@
vars:
ufw_verify_untagged: "{{ ufw_verify_added.stdout_lines | select('match', '^ufw ') | reject('search', 'ansible-ufw') | list }}"
# converge.yml proves the guard's message; the 7999 and 7998 absence checks are redundant confirmation that the stray rules never reached the host.
# The refusal play proves the guard's message; the 7999 and 7998 absence checks are redundant confirmation that the stray rules never reached the host.
- name: A stray *_ufw_rules variable did not reach the firewall
ansible.builtin.assert:
that:
@@ -33,10 +33,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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
@@ -48,4 +47,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env bash
# The Molecule workflow's "Run the scenarios" step: `molecule test` for each scenario directory on
# stdin, MOLECULE_LANES (default 4) at a time, each with its own log and ANSIBLE_HOME under
# <work-dir>/<n>/ (molecule reinstalls the collection there with --force). Exit 1 on a failure.
#
# scripts/run_molecule_scenarios.sh <work-dir> < scenario-dirs
set -euo pipefail
lanes="${MOLECULE_LANES:-4}"
if ! [[ "$lanes" =~ ^[1-9][0-9]*$ ]]; then
echo "MOLECULE_LANES must be a positive integer, not '$lanes'" >&2
exit 2
fi
if [ "$#" -ne 1 ]; then
echo "usage: $0 <work-dir> < scenario-dirs" >&2
exit 2
fi
work="$1"
label_of() {
case "$1" in
extensions/*) echo "${1##*/}" ;;
*) local role="${1#roles/}"; echo "${role%%/*}/${1##*/}" ;;
esac
}
# Removes the scenario's containers by the literal platform names in its molecule.yml, in place of
# molecule's destroy, which the scenarios leave out: its driver waits about 5.6 s per scenario for
# the deletion (about 84 s over 15), and the whole destroy phase measured about 103 s a full run.
# python3 is the molecule venv's, with PyYAML.
remove_instances() {
local names ids
local py='import sys, yaml; print(*(p["name"] for p in yaml.safe_load(open(sys.argv[1]))["platforms"]))'
names="$(python3 -I -c "$py" "$1/molecule.yml")" || return 1
[ -n "$names" ] || return 1
# shellcheck disable=SC2046,SC2086 # names and ids are one word each
ids="$(docker ps -aq $(printf -- '--filter name=^/%s$ ' $names))" || return 1
# shellcheck disable=SC2086
if [ -n "$ids" ]; then docker rm -f $ids >/dev/null || return 1; fi
}
# Runs scenario $2 into $work/$1/. Its outcome is the rc file, which a lane that died lacks.
run_one() {
local out="$work/$1" dir="$2" start=$SECONDS rc=0
mkdir -p "$out/ansible"
(
export ANSIBLE_HOME="$out/ansible"
# a role scenario runs from its role's directory, as molecule expects
case "$dir" in roles/*) cd "${dir%/molecule/*}" || exit 1 ;; esac
molecule test -s "${dir##*/}"
) >"$out/log" 2>&1 </dev/null || rc=$?
if ! remove_instances "$dir" >>"$out/log" 2>&1; then
echo "could not remove the containers of $dir" >>"$out/log"
if [ "$rc" -eq 0 ]; then rc=1; fi
fi
echo "$((SECONDS - start))" >"$out/seconds"
echo "$rc" >"$out/rc"
echo "finished $(label_of "$dir"): exit $rc after $((SECONDS - start)) s"
}
dirs=()
while IFS= read -r dir; do
if [ -n "$dir" ]; then dirs+=("$dir"); fi
done
mkdir -p "$work"
# A cancelled job must not leave lanes behind that recreate containers after the next run's
# cleanup. A signal to this script stops each lane's tree so it cannot fork, then terminates it,
# with the whole group of any descendant that leads one: ansible's workers detach into their own.
# A kill of the step's process group reaches the lanes and molecule, not those detached workers.
kill_tree() {
local child leader=""
kill -STOP "$1" 2>/dev/null || return 0
# never a group this script or its caller is in: only one a descendant leads
if [ "$(ps -o pgid= -p "$1" | tr -d ' ')" = "$1" ] && [ "$1" != "$own_group" ]; then
leader=1
kill -STOP -- "-$1" 2>/dev/null || true
fi
for child in $(ps -o pid= --ppid "$1"); do kill_tree "$child"; done
if [ -n "$leader" ]; then
kill -TERM -- "-$1" 2>/dev/null || true
kill -CONT -- "-$1" 2>/dev/null || true
fi
kill -TERM "$1" 2>/dev/null || true
kill -CONT "$1" 2>/dev/null || true
}
stop_lanes() {
# a second signal must not abort the cleanup and leave a lane stopped
trap '' TERM INT HUP
local pid
for pid in $(jobs -rp); do kill_tree "$pid"; done
wait || true
exit "$1"
}
own_group="$(ps -o pgid= -p "$$" | tr -d ' ')"
trap 'stop_lanes 143' TERM
trap 'stop_lanes 130' INT
trap 'stop_lanes 129' HUP
for n in "${!dirs[@]}"; do
while [ "$(jobs -rp | wc -l)" -ge "$lanes" ]; do wait -n || true; done
run_one "$n" "${dirs[$n]}" </dev/null &
done
wait
failed=""
ran=0
times=""
for n in "${!dirs[@]}"; do
label="$(label_of "${dirs[$n]}")"
seconds="$(cat "$work/$n/seconds" 2>/dev/null || echo '?')"
times="$times $label: $seconds s"$'\n'
echo "::group::molecule test: $label ($seconds s)"
cat "$work/$n/log" 2>/dev/null || true
echo "::endgroup::"
if [ -f "$work/$n/rc" ]; then
ran=$((ran + 1))
if [ "$(cat "$work/$n/rc")" != 0 ]; then failed="$failed $label"; fi
fi
done
printf 'Scenarios run: %s\n%s' "$ran" "$times"
# A lane that died without a result must not pass quietly.
test "$ran" -eq "${#dirs[@]}" || { echo "::error::ran $ran of ${#dirs[@]} selected scenarios"; exit 1; }
test -z "$failed" || { echo "::error::Failed:$failed"; exit 1; }
+36 -11
View File
@@ -13,6 +13,9 @@ Only a pull request is narrowed, and only when <base-ref> is given and EVENT_NAM
* a file under roles/<role>/ selects that role's scenarios, and those of every role that
uses it (below);
* a file under extensions/molecule/<name>/, when that is a scenario, selects that scenario
only (the image-smoke scenarios test the images, not the roles); a shared file such as
extensions/molecule/requirements.yml is "any other file";
* a file on the IGNORED list (documentation, changelog, repository tooling that no
scenario reads) selects nothing;
* any other file selects every scenario.
@@ -38,8 +41,8 @@ nothing tested. A role whose directory is gone (the role was deleted) selects no
The workflow runs this script from the base branch's copy, not the pull request's, so a pull
request cannot edit the rules it is judged by (the same reason lint.yml runs
check_bot_pr_diff.py from origin/main). A change to this file therefore selects everything
under the base copy's rules, because the file is not on the IGNORED list.
check_bot_pr_diff.py from origin/main). No scenario runs the pull request's copy, so this file
is on the IGNORED list: its unit tests test it, and the push run after the merge runs it.
Exit codes: 0 ok (an empty selection from an all-ignored diff is ok), 1 no scenario exists at
all, or a changed role has none, 2 bad usage. Notices go to stderr as `::notice::` lines, with
@@ -63,7 +66,8 @@ IGNORED = (
"SECURITY.md",
"GLOSSARY.md",
"AGENTS.md",
"roles/AGENTS.md",
"*/AGENTS.md",
"roles/*/README.md",
"CODEOWNERS",
"CHANGELOG.rst",
"COPYING",
@@ -75,11 +79,13 @@ IGNORED = (
".ansible-lint",
".ansible-lint-ignore",
".pre-commit-config.yaml",
".python-version",
"requirements-dev.txt",
"requirements-dev.lock",
"ruff.toml",
"apm.yml",
"apm.lock.yaml",
".claude/*",
"tests/sanity/*",
"tests/scripts/*",
"images/*",
@@ -100,6 +106,8 @@ IGNORED = (
"scripts/ansible-test-sanity.sh",
"scripts/dev-setup.sh",
"scripts/reuse_lint.py",
"scripts/lock-requirements.sh",
"scripts/select_molecule_scenarios.py",
)
@@ -189,6 +197,7 @@ def select(all_scenarios, changed, root="."):
Raises ValueError when a changed role still exists but has no scenario.
"""
roles = set()
extensions = set()
for path in changed:
if is_ignored(path):
continue
@@ -196,13 +205,23 @@ def select(all_scenarios, changed, root="."):
if len(parts) > 2 and parts[0] == "roles":
roles.add(parts[1])
continue
scenario = "/".join(parts[:3])
if (
len(parts) > 3
and parts[:2] == ["extensions", "molecule"]
and scenario in all_scenarios
):
extensions.add(scenario)
continue
return list(all_scenarios), f"{printable(path)} can affect every scenario"
changed_roles = roles
roles = with_users(changed_roles, users(root, changed_roles))
chosen = [
s for s in all_scenarios if s.startswith("roles/") and s.split("/")[1] in roles
s
for s in all_scenarios
if s in extensions or (s.startswith("roles/") and s.split("/")[1] in roles)
]
covered = {s.split("/")[1] for s in chosen}
covered = {s.split("/")[1] for s in chosen if s.startswith("roles/")}
bare = sorted(
r for r in roles - covered if os.path.isdir(os.path.join(root, "roles", r))
)
@@ -211,16 +230,22 @@ def select(all_scenarios, changed, root="."):
"role without a molecule scenario (changed, or a user of a changed role): "
+ ", ".join(printable(r) for r in bare)
)
notes = []
if roles:
reason = "only roles changed: " + ", ".join(
printable(r) for r in sorted(changed_roles)
notes.append(
"roles changed: " + ", ".join(printable(r) for r in sorted(changed_roles))
)
if roles - changed_roles:
reason += "; their users: " + ", ".join(
printable(r) for r in sorted(roles - changed_roles)
notes.append(
"their users: "
+ ", ".join(printable(r) for r in sorted(roles - changed_roles))
)
else:
reason = "no change that a scenario reads"
if extensions:
notes.append(
"image-smoke scenarios changed: "
+ ", ".join(printable(e.split("/")[2]) for e in sorted(extensions))
)
reason = "; ".join(notes) or "no change that a scenario reads"
return chosen, reason
@@ -0,0 +1,304 @@
# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Tests for scripts/run_molecule_scenarios.sh with stub molecule and docker on PATH.
Run with: python3 -m unittest discover -s tests/scripts
"""
import os
import pathlib
import re
import shutil
import signal
import subprocess
import tempfile
import time
import unittest
import yaml
REPO = pathlib.Path(__file__).resolve().parents[2]
SCRIPT = REPO / "scripts" / "run_molecule_scenarios.sh"
WORKFLOW = REPO / ".gitea" / "workflows" / "molecule.yml"
# Records what each run saw, then behaves as STUB_<scenario label> asks: fail, sleep, hang (and
# record its pids), detach (as an ansible worker does, into its own process group, whose orphaned
# child no parent link reaches; record both), or read stdin (which must be empty).
MOLECULE_STUB = """#!/usr/bin/env bash
label="$(basename "$PWD")/$3"
[ "$PWD" = "$STUB_ROOT" ] && label="$3"
key="STUB_$(printf %s "$label" | tr -c 'A-Za-z0-9' _)"
echo "$label start $(date +%s.%N) home=$ANSIBLE_HOME cwd=$PWD args=$*" >> "$STUB_LOG"
echo "output of $label"
case "${!key:-}" in
fail) echo "$label end $(date +%s.%N)" >> "$STUB_LOG"; exit 2 ;;
sleep) sleep 1 ;;
hang) sleep 60 & echo "$$ $!" >> "$STUB_PIDS"; wait ;;
detach)
setsid bash -c '(sleep 60 & echo $! >> "$STUB_PIDS"); echo $$ >> "$STUB_PIDS"; exec sleep 60' &
wait ;;
stdin) echo "stdin of $label: [$(cat)]" ;;
esac
echo "$label end $(date +%s.%N)" >> "$STUB_LOG"
"""
# `ps` lists a container id per name filter; `rm` records the ids or fails on request.
DOCKER_STUB = """#!/usr/bin/env bash
echo "docker $*" >> "$STUB_DOCKER_LOG"
case "$1" in
ps) for a in "$@"; do case "$a" in name=*) n="${a#name=^/}"; echo "id-${n%$}" ;; esac; done ;;
rm) [ -z "${STUB_RM_FAIL:-}" ] || exit 1 ;;
esac
"""
PLATFORMS = {
"roles/alpha/molecule/default": ["alpha-instance"],
"roles/beta/molecule/default": ["beta-instance", "beta2-instance"],
"roles/beta/molecule/check_mode": ["beta-check-instance"],
"extensions/molecule/image-smoke": ["image-smoke"],
}
@unittest.skipUnless(shutil.which("bash"), "bash is required")
class RunMoleculeScenariosTest(unittest.TestCase):
def setUp(self):
self.tmp = pathlib.Path(tempfile.mkdtemp(prefix="kamino-runmol-")).resolve()
self.addCleanup(shutil.rmtree, self.tmp, True)
self.root = self.tmp / "kamino"
self.hung = []
for scenario, names in PLATFORMS.items():
d = self.root / scenario
d.mkdir(parents=True)
platforms = [{"name": n, "image": "${MOLECULE_IMAGE}"} for n in names]
(d / "molecule.yml").write_text(yaml.safe_dump({"platforms": platforms}))
bin_dir = self.tmp / "bin"
bin_dir.mkdir()
for name, body in (("molecule", MOLECULE_STUB), ("docker", DOCKER_STUB)):
(bin_dir / name).write_text(body)
(bin_dir / name).chmod(0o755)
self.log = self.tmp / "molecule.log"
self.docker_log = self.tmp / "docker.log"
self.log.touch()
self.docker_log.touch()
self.env = {
"PATH": f"{bin_dir}:{os.environ['PATH']}",
"HOME": str(self.tmp),
"STUB_ROOT": str(self.root),
"STUB_LOG": str(self.log),
"STUB_DOCKER_LOG": str(self.docker_log),
}
def run_script(self, scenarios, **env):
return subprocess.run(
["bash", str(SCRIPT), str(self.tmp / "work")],
cwd=self.root,
env={**self.env, **env},
input="".join(f"{s}\n" for s in scenarios),
capture_output=True,
text=True,
check=False,
)
def events(self):
"""{label: (start, end)} from the molecule stub's log."""
times = {}
for line in self.log.read_text().splitlines():
label, what, stamp = line.split()[:3]
times.setdefault(label, {})[what] = float(stamp)
return {k: (v["start"], v.get("end")) for k, v in times.items()}
def test_groups_follow_the_selection_order_with_times(self):
order = list(PLATFORMS)
proc = self.run_script(order, STUB_alpha_default="sleep")
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
groups = re.findall(
r"^::group::molecule test: (\S+) \((\d+) s\)$", proc.stdout, re.MULTILINE
)
self.assertEqual(
[g[0] for g in groups],
["alpha/default", "beta/default", "beta/check_mode", "image-smoke"],
)
self.assertGreaterEqual(int(groups[0][1]), 1)
self.assertEqual(proc.stdout.count("::endgroup::"), 4)
# each log sits inside its own group
body = proc.stdout.split("::group::molecule test: beta/default")[1].split(
"::endgroup::"
)[0]
self.assertIn("output of beta/default", body)
self.assertNotIn("output of alpha/default", body)
self.assertIn("Scenarios run: 4", proc.stdout)
self.assertIn(" image-smoke: ", proc.stdout)
def test_runs_in_lanes_and_isolates_each_scenario(self):
order = list(PLATFORMS)
stubs = {
f"STUB_{k}": "sleep"
for k in ("alpha_default", "beta_default", "image_smoke")
}
proc = self.run_script(order, MOLECULE_LANES="2", **stubs)
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
spans = self.events()
self.assertEqual(len(spans), 4)
running_at = [
sum(s <= t < e for s, e in spans.values()) for t, _end in spans.values()
]
self.assertEqual(max(running_at), 2, spans)
starts = [
line for line in self.log.read_text().splitlines() if " start " in line
]
homes = {re.search(r"home=(\S+)", s).group(1) for s in starts}
self.assertEqual(len(homes), 4)
check = next(s for s in starts if s.startswith("beta/check_mode "))
self.assertIn(
f"cwd={self.root / 'roles' / 'beta'} args=test -s check_mode", check
)
smoke = next(s for s in starts if s.startswith("image-smoke "))
self.assertIn(f"cwd={self.root} args=test -s image-smoke", smoke)
def test_a_failure_is_reported_and_its_containers_still_go(self):
proc = self.run_script(list(PLATFORMS), STUB_beta_default="fail")
self.assertEqual(proc.returncode, 1)
self.assertIn("::error::Failed: beta/default\n", proc.stdout)
self.assertIn("Scenarios run: 4", proc.stdout)
docker = self.docker_log.read_text()
for name in (n for names in PLATFORMS.values() for n in names):
self.assertIn(f"--filter name=^/{name}$", docker)
self.assertIn("docker rm -f id-beta-instance id-beta2-instance", docker)
def test_molecule_gets_no_stdin(self):
proc = self.run_script(list(PLATFORMS), STUB_alpha_default="stdin")
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
self.assertIn("stdin of alpha/default: []", proc.stdout)
self.assertIn("Scenarios run: 4", proc.stdout)
def test_a_failed_removal_fails_the_scenario(self):
proc = self.run_script(["roles/alpha/molecule/default"], STUB_RM_FAIL="1")
self.assertEqual(proc.returncode, 1)
self.assertIn(
"could not remove the containers of roles/alpha/molecule/default",
proc.stdout,
)
self.assertIn("::error::Failed: alpha/default\n", proc.stdout)
def test_a_scenario_without_a_result_fails_the_run(self):
# a lane that dies leaves no rc file: a file where the second scenario's work directory
# goes makes its lane fail before molecule starts
(self.tmp / "work").mkdir()
(self.tmp / "work" / "1").write_text("not a directory")
proc = self.run_script(
["roles/alpha/molecule/default", "roles/beta/molecule/default"]
)
self.assertEqual(proc.returncode, 1)
self.assertIn("::error::ran 1 of 2 selected scenarios", proc.stdout)
def test_lanes_must_be_a_positive_integer(self):
for lanes in ("0", "-1", "two", "04"):
proc = self.run_script(list(PLATFORMS), MOLECULE_LANES=lanes)
self.assertEqual(proc.returncode, 2, lanes)
self.assertIn("MOLECULE_LANES must be a positive integer", proc.stderr)
self.assertEqual(self.log.read_text(), "")
def start_hung_run(self, count=4, **stubs):
"""A run in its own process group whose molecule stubs hang, and the pids they record."""
pids = self.tmp / "pids"
pids.touch()
env = {**self.env, "STUB_PIDS": str(pids), "MOLECULE_LANES": "2"}
env.update(stubs or {"STUB_alpha_default": "hang", "STUB_beta_default": "hang"})
proc = subprocess.Popen(
["bash", str(SCRIPT), str(self.tmp / "work")],
cwd=self.root, env=env, stdin=subprocess.PIPE, text=True,
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, start_new_session=True,
) # fmt: skip
self.addCleanup(lambda: proc.poll() is None and os.killpg(proc.pid, 9))
self.addCleanup(lambda: [os.kill(p, 9) for p in self.hung if alive(p)])
proc.stdin.write("".join(f"{s}\n" for s in PLATFORMS))
proc.stdin.close()
deadline = time.monotonic() + 10
while len(pids.read_text().split()) < count and time.monotonic() < deadline:
time.sleep(0.05)
self.hung = [int(p) for p in pids.read_text().split()]
self.assertEqual(len(self.hung), count)
return proc
def assert_all_gone(self, pids):
deadline = time.monotonic() + 5
while any(map(alive, pids)) and time.monotonic() < deadline:
time.sleep(0.05)
self.assertEqual([p for p in pids if alive(p)], [])
@unittest.skipUnless(pathlib.Path("/proc/self").exists(), "needs /proc")
def test_a_terminated_run_kills_its_lanes(self):
proc = self.start_hung_run()
proc.send_signal(signal.SIGTERM)
self.assertEqual(proc.wait(timeout=10), 143)
self.assert_all_gone(self.hung)
self.assertEqual(proc.stderr.read(), "")
@unittest.skipUnless(pathlib.Path("/proc/self").exists(), "needs /proc")
@unittest.skipUnless(shutil.which("setsid"), "needs setsid")
def test_a_terminated_run_kills_detached_process_groups(self):
proc = self.start_hung_run(count=2, STUB_alpha_default="detach")
proc.send_signal(signal.SIGTERM)
self.assertEqual(proc.wait(timeout=10), 143)
self.assert_all_gone(self.hung)
@unittest.skipUnless(pathlib.Path("/proc/self").exists(), "needs /proc")
def test_a_killed_process_group_takes_its_lanes(self):
# a runner may cancel a step by killing its process group, which the script cannot trap
proc = self.start_hung_run()
os.killpg(proc.pid, signal.SIGKILL)
proc.wait(timeout=10)
self.assert_all_gone(self.hung)
def test_an_empty_selection_runs_nothing(self):
proc = self.run_script(["", ""])
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
self.assertIn("Scenarios run: 0", proc.stdout)
self.assertEqual(self.log.read_text(), "")
def alive(pid):
"""Whether pid is a running process, not gone or a zombie."""
try:
stat = pathlib.Path(f"/proc/{pid}/stat").read_text()
except FileNotFoundError:
return False
return stat.rsplit(")", 1)[1].split()[0] != "Z"
def stale_filters():
"""The name filters of the workflow's stale-container cleanup, as docker matches /<name>."""
workflow = yaml.safe_load(WORKFLOW.read_text())
steps = [s for job in workflow["jobs"].values() for s in job.get("steps", [])]
run = next(s["run"] for s in steps if s.get("name") == "Run the scenarios")
stale = next(line for line in run.splitlines() if line.strip().startswith("stale="))
return re.findall(r"--filter 'name=([^']+)'", stale)
class ScenarioPlatformNamesTest(unittest.TestCase):
"""The run script removes containers by literal platform name, and scenarios run side by side."""
def test_platform_names_are_literal_unique_and_cleared_before_a_run(self):
files = sorted(REPO.glob("roles/*/molecule/*/molecule.yml"))
files += sorted(REPO.glob("extensions/molecule/*/molecule.yml"))
self.assertTrue(files)
seen = {}
stale = stale_filters()
self.assertTrue(stale)
for path in files:
data = yaml.safe_load(path.read_text())
for platform in data["platforms"]:
name = platform["name"]
where = path.relative_to(REPO)
self.assertTrue(
any(re.search(f, f"/{name}") for f in stale), f"{where}: {name}"
)
self.assertNotIn(
name, seen, f"{where} and {seen.get(name)} share {name}"
)
seen[name] = where
self.assertNotIn("destroy", data["scenario"]["test_sequence"], path)
if __name__ == "__main__":
unittest.main()
@@ -162,6 +162,39 @@ class SelectTest(unittest.TestCase):
chosen, _reason = sel.select(ALL, ["AGENTS.md"])
self.assertEqual(chosen, [])
def test_nested_agent_guidance_selects_nothing(self):
chosen, _reason = self.select(
[
".gitea/workflows/AGENTS.md",
"scripts/AGENTS.md",
"roles/docker/AGENTS.md",
],
)
self.assertEqual(chosen, [])
def test_agent_tool_settings_select_nothing(self):
# Claude Code reads .claude/ on a contributor's machine; no scenario reads it.
chosen, _reason = self.select(
[".claude/settings.json", ".claude/hooks/guard.sh"],
)
self.assertEqual(chosen, [])
def test_role_readme_selects_nothing(self):
# A role's README is documentation; its scenarios and its users' do not read it.
chosen, _reason = self.select(["roles/docker/README.md"])
self.assertEqual(chosen, [])
def test_selector_and_dev_python_select_nothing(self):
# Molecule runs the base copy of the selector and the runner's own venv.
chosen, _reason = self.select(
[
"scripts/select_molecule_scenarios.py",
"scripts/lock-requirements.sh",
".python-version",
],
)
self.assertEqual(chosen, [])
def test_issue_and_pull_request_templates_select_nothing(self):
# Gitea reads them for its web forms; no scenario does, and they are not shipped.
chosen, _reason = self.select(
@@ -182,9 +215,9 @@ class SelectTest(unittest.TestCase):
"galaxy.yml",
"meta/runtime.yml",
"plugins/modules/x.py",
"extensions/molecule/image-smoke/molecule.yml",
"extensions/molecule/requirements.yml",
"extensions/molecule/gone/molecule.yml",
".gitea/workflows/molecule.yml",
"scripts/select_molecule_scenarios.py",
"tests/unit/x.py",
"new_top_level_file",
"roles/README.md",
@@ -192,6 +225,25 @@ class SelectTest(unittest.TestCase):
chosen, _reason = self.select(["roles/docker/tasks/main.yml", path])
self.assertEqual(chosen, ALL, path)
def test_image_smoke_change_selects_only_that_scenario(self):
chosen, reason = self.select(
["extensions/molecule/image-smoke-2604/verify.yml"]
)
self.assertEqual(chosen, ["extensions/molecule/image-smoke-2604"])
self.assertIn("image-smoke-2604", reason)
def test_image_smoke_and_role_changes_combine(self):
chosen, _reason = self.select(
[
"extensions/molecule/image-smoke/converge.yml",
"roles/docker/tasks/main.yml",
]
)
self.assertEqual(
chosen,
["extensions/molecule/image-smoke", "roles/docker/molecule/default"],
)
def test_deleted_role_selects_nothing_of_its_own(self):
chosen, _reason = self.select(["roles/gone/tasks/main.yml"])
self.assertEqual(chosen, [])
@@ -470,7 +522,7 @@ class MainTest(unittest.TestCase):
finally:
os.chdir(cwd)
def test_every_tracked_file_is_ignored_or_selects_everything_or_is_a_role_file(
def test_every_tracked_file_is_ignored_or_selects_everything_or_its_own_scenario(
self,
):
tracked = subprocess.run(
@@ -487,7 +539,12 @@ class MainTest(unittest.TestCase):
if sel.is_ignored(path) or path.startswith("roles/"):
continue
chosen, _reason = sel.select(scenarios, [path], str(REPO))
self.assertEqual(chosen, scenarios, path)
own = "/".join(path.split("/")[:3])
if path.startswith("extensions/molecule/") and own in scenarios:
# A file of one image-smoke scenario selects that scenario only.
self.assertEqual(chosen, [own], path)
else:
self.assertEqual(chosen, scenarios, path)
def test_roles_call_each_other_by_full_name_only(self):
# The selection finds a role's users by the text mortis.kamino.<role> (users()). A use