14 Commits
Author SHA1 Message Date
DragonishandClaude Sonnet 5.5 dcdc9133f6 feat(system_baseline): optional tmux session on SSH login
Build / build (pull_request) Successful in 12s
Lint / lint (pull_request) Successful in 20s
Molecule / molecule (pull_request) Successful in 1m40s
Adds tmux to the ubuntu_lxc and ubuntu_vm profiles and an opt-in
/etc/profile.d snippet that attaches an interactive SSH login to a tmux
session, created with configurable windows when it does not exist.

- system_baseline_tmux_autostart (default false), _session (default main)
  and _windows ([{name, command}]); only ubuntu_lxc and ubuntu_vm install
  the snippet, pve never does, and false removes it.
- profile.d is read only by an interactive login shell, so scp, sftp,
  ssh host command and automation are unaffected. ~/.no-tmux opts a user
  out. ForceCommand is not used: it would affect every session type.
- Names and commands are validated and shell-quoted; the script is
  root-owned. Commands run as the logging-in user and are world-readable,
  so they must hold no secret.
- Molecule converge enables it, verify checks ownership, mode, the attach
  line, the quoting and sh -n.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q72rsMEKREGMfB9DH3T9mR
2026-11-14 14:26:19 +00:00
Defame1297 e4c9be903d Merge pull request 'ci(molecule): use molecule-ubuntu2404 0.1.6 and drop the docker prepare gnupg task' (#120) from ci/molecule-image-pin-0.1.6 into main
Build / build (push) Successful in 12s
Lint / lint (push) Successful in 19s
Molecule / molecule (push) Successful in 5m29s
Reviewed-on: #120
2026-11-14 12:56:51 +00:00
Defame1297andClaude Sonnet 5.5 db4ba8d5c8 ci(molecule): use molecule-ubuntu2404 0.1.6 and drop the docker prepare gnupg task
Build / build (pull_request) Successful in 12s
Lint / lint (pull_request) Successful in 20s
Molecule / molecule (pull_request) Successful in 6m7s
Moves the MOLECULE_IMAGE pin to 0.1.6, the build of #119 that carries gnupg, and
with it:

- removes the gnupg install (and its apt update) from the docker scenario's
  prepare, about 10 s of its 12 s; the role refreshes its own apt cache at
  install, so nothing relied on that update;
- adds gnupg to the image-smoke contract, so the image keeps providing it;
- drops gnupg from the docker README's list of what the scenario needs the
  Ubuntu mirrors for, with a trivial changelog fragment.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-14 12:47:37 +00:00
Defame1297 f7f5b7adf9 Merge pull request 'ci(images): preinstall gnupg in molecule-ubuntu2404' (#119) from ci/molecule-image-gnupg into main
Build / build (push) Successful in 11s
Images / image (Dockerfile, ubuntu:24.04@sha256:fe81560990fae86dc4743202b2cb4d3df98d0bcf949173cecef15ce1127ef852, molecule-ubuntu2404, images/molecule-ubuntu2404, 0.1.6) (push) Successful in 30s
Lint / lint (push) Successful in 20s
Images / image (Dockerfile, ubuntu:26.04@sha256:6a06111c3b0a8600feadb270aec771dc239bf407b25625f93f44ab00e11f4d3c, molecule-ubuntu2604, images/molecule-ubuntu2604, 0.1.3) (push) Successful in 12s
Images / image (images/ci/Dockerfile, ubuntu:26.04@sha256:6a06111c3b0a8600feadb270aec771dc239bf407b25625f93f44ab00e11f4d3c, ci, , 0.2.15) (push) Successful in 10s
Reviewed-on: #119
2026-11-14 12:45:05 +00:00
Defame1297andClaude Sonnet 5.5 0a3ff387d7 ci(images): preinstall gnupg in molecule-ubuntu2404
Build / build (pull_request) Successful in 11s
Lint / lint (pull_request) Successful in 21s
Molecule / molecule (pull_request) Successful in 1s
The docker scenario installs gnupg in prepare to sign its stand-in APT
repository, which costs an apt update and an install in every run (about 10 s of
its 12 s prepare); system_baseline installs it among its essential packages. It
is now part of the image, version 0.1.6.

Image input only: the consumers' pins, the docker prepare task and the
image-smoke contract move in the pin follow-up pull request, once the build on
main has printed the new digest.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-14 12:40:40 +00:00
Defame1297 ceeca66209 Merge pull request 'ci(molecule): cancel superseded runs, trim the test sequence, run nightly' (#117) from ci/molecule-cancel-and-trim into main
Build / build (push) Successful in 12s
Lint / lint (push) Successful in 21s
Molecule / molecule (push) Successful in 6m5s
Reviewed-on: #117
2026-11-14 11:56:00 +00:00
Defame1297andClaude Sonnet 5.5 676c950c08 Merge branch 'ci/molecule-changed-roles' into ci/molecule-cancel-and-trim
Build / build (pull_request) Successful in 11s
Lint / lint (pull_request) Successful in 24s
Molecule / molecule (pull_request) Successful in 6m50s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-14 11:34:25 +00:00
Defame1297andClaude Sonnet 5.5 a94bee8fd3 fix(lint): satisfy ansible-test pylint in the molecule selector
Build / build (pull_request) Successful in 11s
Lint / lint (pull_request) Successful in 24s
Molecule / molecule (pull_request) Successful in 7m0s
ansible-test sanity runs pylint over scripts/ and tests/scripts/ too and
rejects a mutable default argument (environ=os.environ) and `_` as a variable
name. main() now takes environ=None and reads os.environ itself, and the tests
name the values they ignore.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-14 11:34:13 +00:00
Defame1297 37420825a1 Merge branch 'main' into ci/molecule-cancel-and-trim
Build / build (pull_request) Failing after 11s
Lint / lint (pull_request) Successful in 20s
Molecule / molecule (pull_request) Canceled after 5m0s
2026-11-14 11:23:52 +00:00
Defame1297 fdab483109 Merge branch 'main' into ci/molecule-changed-roles
Build / build (pull_request) Failing after 12s
Lint / lint (pull_request) Successful in 21s
Molecule / molecule (pull_request) Successful in 7m19s
2026-11-14 11:23:46 +00:00
Defame1297andClaude Sonnet 5.5 25bca2ebff ci(molecule): run every scenario nightly
Build / build (pull_request) Canceled after 0s
Lint / lint (pull_request) Canceled after 0s
Molecule / molecule (pull_request) Canceled after 0s
A pull request runs only the scenarios of the roles it changes, so drift in the
others (a package mirror, the runner's molecule venv) would wait for the next
push to main. A nightly run of everything bounds that. It is scheduled after
Renovate's run, since the runner has a single slot.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-14 11:06:59 +00:00
Defame1297andClaude Sonnet 5.5 792b3414d3 ci(molecule): drop the leading destroy from every scenario's test sequence
The first destroy runs against a container that is not there and only waits out
the Docker driver's fixed 5 s poll, about 6 s per scenario and 42 s per full
run. The run step already removes what a killed run left, and molecule's state
file lives under the job's own ANSIBLE_HOME (Runtime(isolated=False)), which is
deleted with the checkout, so a cancelled run cannot make the next one skip
create or prepare. The rest of the sequence is molecule's default.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-14 11:06:18 +00:00
Defame1297andClaude Sonnet 5.5 db52adcb81 ci(molecule): cancel superseded pull request runs
A new commit on a pull request now cancels its running Molecule run, as for
Lint and Build; a run on main is never cancelled (its group is the commit SHA).

The old global concurrency group kept two runs off the runner's shared Docker
daemon, whose container names are fixed. That is now the runner's single slot
(gitea_runner_capacity: 1), as the workflow comment and CLAUDE.md say. A
cancelled run is killed before molecule can destroy its container, so the run
step first removes the containers of every scenario by their exact platform
names, whether or not this run selects that scenario.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-14 11:06:17 +00:00
Defame1297andClaude Sonnet 5.5 4d330d41c7 ci(molecule): run only the scenarios of the roles a pull request changes
Build / build (pull_request) Failing after 12s
Lint / lint (pull_request) Successful in 21s
Molecule / molecule (pull_request) Successful in 6m53s
A pull request now runs the scenarios of the roles it touches, none when it
touches only paths no scenario reads, and everything for any other file, for
every push to main and for manual dispatch. The job stays unconditional so
Molecule can remain a required check.

scripts/select_molecule_scenarios.py makes the choice and is run from the base
branch's copy, so a pull request cannot edit its own rules. A changed role
that exists but has no scenario fails instead of passing with nothing tested.

The scenario loop no longer gives molecule the list as stdin, which a child
could have drained, and fails when it ran fewer scenarios than were selected.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-14 11:05:46 +00:00
28 changed files with 807 additions and 42 deletions

No files matched your search

+1 -1
View File
@@ -76,7 +76,7 @@ jobs:
matrix: matrix:
include: include:
- name: molecule-ubuntu2404 - name: molecule-ubuntu2404
version: 0.1.5 version: 0.1.6
subpath: images/molecule-ubuntu2404 subpath: images/molecule-ubuntu2404
dockerfile: Dockerfile dockerfile: Dockerfile
job_image: ubuntu:24.04@sha256:fe81560990fae86dc4743202b2cb4d3df98d0bcf949173cecef15ce1127ef852 job_image: ubuntu:24.04@sha256:fe81560990fae86dc4743202b2cb4d3df98d0bcf949173cecef15ce1127ef852
+64 -22
View File
@@ -36,15 +36,25 @@ on: # yamllint disable-line rule:truthy
- 'meta/**' - 'meta/**'
- 'galaxy.yml' - 'galaxy.yml'
- '.gitea/workflows/molecule.yml' - '.gitea/workflows/molecule.yml'
# Every scenario, nightly: a pull request runs only the scenarios of the roles it changes, so
# drift in the others (a package mirror, the runner's molecule venv) would otherwise wait for
# the next push to main. After Renovate's 03:17 run, which can take 30 minutes of the one slot.
schedule:
- cron: "43 4 * * *"
workflow_dispatch: {} workflow_dispatch: {}
permissions: permissions:
contents: read contents: read
# Scenarios use fixed container names on the runner's shared Docker daemon. # 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 (gitea_runner_capacity: 1 in the maintainer's environment
# repository). Raise that capacity and this needs a lock or a shared group again.
concurrency: concurrency:
group: molecule group: molecule-${{ github.event_name == 'pull_request' && github.ref || github.sha }}
cancel-in-progress: false cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs: jobs:
molecule: molecule:
@@ -64,7 +74,7 @@ jobs:
# Used by the scenarios as `image: ${MOLECULE_IMAGE}`; set it the same way to run # Used by the scenarios as `image: ${MOLECULE_IMAGE}`; set it the same way to run
# one locally. # one locally.
MOLECULE_IMAGE: >- MOLECULE_IMAGE: >-
git.rkdr.net/mortis/molecule-ubuntu2404:0.1.5@sha256:57123de013ad0ca0c4c64723f7f86636de07a1d6a40a7bc4f064ec664cd463f9 git.rkdr.net/mortis/molecule-ubuntu2404:0.1.6@sha256:f1bf4d208aa8f1626f797348a120541af3d4445cb2da0b948d94425df1741909
# The same for Ubuntu 26.04, the release the hosts are moving to; used by # The same for Ubuntu 26.04, the release the hosts are moving to; used by
# `image: ${MOLECULE_IMAGE_2604}` in extensions/molecule/image-smoke-2604. # `image: ${MOLECULE_IMAGE_2604}` in extensions/molecule/image-smoke-2604.
MOLECULE_IMAGE_2604: >- MOLECULE_IMAGE_2604: >-
@@ -98,10 +108,25 @@ jobs:
git checkout "$SHA" || { git fetch origin "$REF" && git checkout "$SHA"; } git checkout "$SHA" || { git fetch origin "$REF" && git checkout "$SHA"; }
echo "Checked out $(git rev-parse HEAD)" echo "Checked out $(git rev-parse HEAD)"
# molecule test destroys its instance on success and on failure. # 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.
- name: Run the scenarios - name: Run the scenarios
working-directory: ac/ansible_collections/mortis/kamino working-directory: ac/ansible_collections/mortis/kamino
env:
EVENT_NAME: ${{ github.event_name }}
# The workflow only runs for pull requests to main; lint.yml uses the same constant.
BASE_REF: origin/main
run: | run: |
# The platform names of every scenario, anchored: <role>-instance and image-smoke[-2604].
# Assigned first so that a failing `docker ps` fails the step instead of looking empty.
stale="$(docker ps -aq --filter 'name=^/[a-z0-9-]+-instance$' --filter 'name=^/image-smoke(-2604)?$')"
if [ -n "$stale" ]; then
# shellcheck disable=SC2086 # container ids, one word each
docker rm -f $stale
fi
# molecule calls ansible-config and ansible-playbook by name # molecule calls ansible-config and ansible-playbook by name
export PATH="$MOLECULE_VENV/bin:$PATH" export PATH="$MOLECULE_VENV/bin:$PATH"
# The collection under test first, then what the roles use. molecule also # The collection under test first, then what the roles use. molecule also
@@ -113,26 +138,43 @@ jobs:
export ANSIBLE_HOME="$ac_root/.ansible" export ANSIBLE_HOME="$ac_root/.ansible"
export ANSIBLE_COLLECTIONS_PATH="$ac_root:$MOLECULE_COLLECTIONS" export ANSIBLE_COLLECTIONS_PATH="$ac_root:$MOLECULE_COLLECTIONS"
rm -rf "$HOME/.ansible/collections/ansible_collections/mortis" 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
# judged by (lint.yml does the same for check_bot_pr_diff.py); the first pull request that
# adds it has no base copy yet and uses its own.
sel=scripts/select_molecule_scenarios.py
if git cat-file -e "$BASE_REF:$sel" 2>/dev/null; then
sel_dir="$(mktemp -d)"
trap 'rm -rf "$sel_dir"' EXIT
git show "$BASE_REF:$sel" > "$sel_dir/select.py"
sel="$sel_dir/select.py"
else
echo "::notice::no base copy of $sel; running this checkout's copy"
fi
selected="$(python3 -I "$sel" "$BASE_REF")" || exit 1
failed="" failed=""
ran=0 ran=0
for cfg in extensions/molecule/*/molecule.yml; do while IFS= read -r dir; do
[ -e "$cfg" ] || continue [ -n "$dir" ] || continue
name="$(basename "$(dirname "$cfg")")" name="$(basename "$dir")"
echo "::group::molecule test: $name" case "$dir" in
molecule test -s "$name" || failed="$failed $name" 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)) ran=$((ran + 1))
echo "::endgroup::" echo "::endgroup::"
done done <<< "$selected"
for cfg in roles/*/molecule/*/molecule.yml; do
[ -e "$cfg" ] || continue
role="${cfg#roles/}"
role="${role%%/*}"
name="$(basename "$(dirname "$cfg")")"
echo "::group::molecule test: $role/$name"
(cd "roles/$role" && molecule test -s "$name") || failed="$failed $role/$name"
ran=$((ran + 1))
echo "::endgroup::"
done
echo "Scenarios run: $ran" echo "Scenarios run: $ran"
test "$ran" -gt 0 || { echo "::error::no molecule scenario found"; exit 1; } # 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; } test -z "$failed" || { echo "::error::Failed:$failed"; exit 1; }
+11 -1
View File
@@ -59,7 +59,17 @@ Single-context: `GLOSSARY.md` and `docs/adr/` at the root, both created lazily.
checksums baked into the image: a PR that changes `requirements-dev.txt` or checksums baked into the image: a PR that changes `requirements-dev.txt` or
`.pre-commit-config.yaml` takes the slower path that installs the pinned tools. `.pre-commit-config.yaml` takes the slower path that installs the pinned tools.
- Molecule runs on every same-repo pull request, Renovate's included (a new image is tested by its own pin - Molecule runs on every same-repo pull request, Renovate's included (a new image is tested by its own pin
pull request), with no path filter, so that it can be a required check. Fork pull requests are skipped. pull request), with no workflow path filter, so that it can be a required check. Fork pull requests are skipped.
What a pull request runs is chosen by `scripts/select_molecule_scenarios.py`, run from the base branch's copy
(a pull request cannot edit its own rules): only the scenarios of the roles it changes, none for a diff of
only its IGNORED paths, a failure for a changed role with no scenario, and every scenario for any other file,
for every push to `main`, for manual dispatch and for the nightly run (04:43 UTC, after Renovate's). A new file outside `roles/<role>/` runs everything until it
is added to IGNORED, which is right only when no scenario reads it. A new commit cancels the pull request's
running Molecule run, and the step first removes containers a cancelled run left; two runs never overlap
because the runner has a single slot, so raising its capacity needs a lock or a shared concurrency group.
- Every scenario sets `scenario.test_sequence` to molecule's default minus the leading `destroy` (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); copy it into a new scenario.
- Molecule discovers `extensions/molecule/*/` and `roles/*/molecule/*/`. The `image-smoke` - Molecule discovers `extensions/molecule/*/` and `roles/*/molecule/*/`. The `image-smoke`
and `image-smoke-2604` scenarios test the molecule images themselves (24.04 and 26.04); a role scenario that and `image-smoke-2604` scenarios test the molecule images themselves (24.04 and 26.04); a role scenario that
must pass on both takes `image: ${MOLECULE_IMAGE}` or `${MOLECULE_IMAGE_2604}` per platform. must pass on both takes `image: ${MOLECULE_IMAGE}` or `${MOLECULE_IMAGE_2604}` per platform.
+3 -2
View File
@@ -53,8 +53,9 @@ outside contributions:
- Protect the `v*` tags so only maintainers can create them. A tag run uses the - Protect the `v*` tags so only maintainers can create them. A tag run uses the
workflow files of the tagged commit and may receive organisation secrets. workflow files of the tagged commit and may receive organisation secrets.
- Protect `main`: pull request required, with the `Lint` and `Build` checks. Molecule is not a required - Protect `main`: pull request required, with the `Lint` and `Build` checks. Molecule has no path filter
check: its path filter would leave the check pending forever on a pull request that touches no role. on pull requests (the job always starts and chooses its scenarios itself), so it can be made a required
check as well; that is the operator's decision.
- The image workflow (`.gitea/workflows/image.yml`) tries the Actions job token first; - The image workflow (`.gitea/workflows/image.yml`) tries the Actions job token first;
Gitea 28 refuses it for an organisation's packages, so it pushes with the organisation secrets Gitea 28 refuses it for an organisation's packages, so it pushes with the organisation secrets
`PACKAGE_PUSH_USER` and `PACKAGE_PUSH_TOKEN` (a bot user with write access to the `PACKAGE_PUSH_USER` and `PACKAGE_PUSH_TOKEN` (a bot user with write access to the
@@ -0,0 +1,3 @@
---
trivial:
- docker - the molecule scenario takes gnupg from the molecule image, so the README no longer lists it among what the scenario needs the Ubuntu mirrors for.
@@ -0,0 +1,6 @@
---
minor_changes:
- >-
system_baseline - add an optional tmux session on SSH login for the ``ubuntu_lxc`` and ``ubuntu_vm`` profiles
(``system_baseline_tmux_autostart``, ``system_baseline_tmux_session``, ``system_baseline_tmux_windows``).
It is off by default. The two profiles now install ``tmux``.
+2 -1
View File
@@ -12,7 +12,8 @@ It is the release of the home lab's LXC hosts today.
`ca-certificates`. `ca-certificates`.
- Python for Ansible on the target: `python3`, `python3-apt`, `python3-systemd`. - Python for Ansible on the target: `python3`, `python3-apt`, `python3-systemd`.
- The packages the roles manage, preinstalled so a converge makes no network calls: - The packages the roles manage, preinstalled so a converge makes no network calls:
`iptables`, `ufw`, `fail2ban`, `openssh-server` (the `ssh` unit is enabled). `iptables`, `ufw`, `fail2ban`, `openssh-server` (the `ssh` unit is enabled), and `gnupg`
(the docker scenario signs its stand-in APT repository with it).
- Throwaway SSH host keys and a machine-id generated at build time. They are not secrets and the - Throwaway SSH host keys and a machine-id generated at build time. They are not secrets and the
image is a test target that must never be exposed to a network. image is a test target that must never be exposed to a network.
@@ -25,3 +25,20 @@ provisioner:
name: ansible name: ansible
verifier: verifier:
name: ansible name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
- destroy
@@ -25,3 +25,20 @@ provisioner:
name: ansible name: ansible
verifier: verifier:
name: ansible name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
- destroy
@@ -33,6 +33,7 @@
- ufw - ufw
- fail2ban - fail2ban
- openssh-server - openssh-server
- gnupg
- name: Query the units a role scenario relies on - name: Query the units a role scenario relies on
ansible.builtin.systemd: ansible.builtin.systemd:
+6 -3
View File
@@ -17,7 +17,7 @@
# One RUN layer: about 30 MB compressed on top of the 29.8 MB base (estimated from # One RUN layer: about 30 MB compressed on top of the 29.8 MB base (estimated from
# the real .debs, with the .pyc files the postinst scripts compile), far below # the real .debs, with the .pyc files the postinst scripts compile), far below
# Cloudflare's 100 MB request-body limit on git.rkdr.net (kaniko pushes a layer as # Cloudflare's 100 MB request-body limit on git.rkdr.net (kaniko pushes a layer as
# one request). apt packages are not version-pinned, as in the original image; the # one request; gnupg adds a few MB, not measured). apt packages are not version-pinned, as in the original image; the
# base image is pinned by digest and a rebuild is a reviewed digest bump downstream. # base image is pinned by digest and a rebuild is a reviewed digest bump downstream.
# #
# The image carries SSH host keys and a machine-id generated at build time (the # The image carries SSH host keys and a machine-id generated at build time (the
@@ -36,7 +36,7 @@ LABEL org.opencontainers.image.title="molecule-ubuntu2404" \
org.opencontainers.image.authors="Defame1297 and contributors" \ org.opencontainers.image.authors="Defame1297 and contributors" \
org.opencontainers.image.base.name="ubuntu:24.04" \ org.opencontainers.image.base.name="ubuntu:24.04" \
net.rkdr.mortis.purpose="Disposable Ubuntu 24.04 test target for the molecule scenarios of the mortis.kamino Ansible Collection." \ net.rkdr.mortis.purpose="Disposable Ubuntu 24.04 test target for the molecule scenarios of the mortis.kamino Ansible Collection." \
net.rkdr.mortis.contents="Ubuntu 24.04, systemd, systemd-sysv, dbus, sudo, iproute2, ca-certificates, python3, python3-apt, python3-systemd, iptables, ufw, fail2ban, openssh-server (ssh enabled)" \ net.rkdr.mortis.contents="Ubuntu 24.04, systemd, systemd-sysv, dbus, sudo, iproute2, ca-certificates, python3, python3-apt, python3-systemd, iptables, ufw, fail2ban, openssh-server (ssh enabled), gnupg" \
net.rkdr.mortis.usage="Molecule docker-driver platform with pre_build_image true, command /sbin/init, cgroupns_mode host, /sys/fs/cgroup mounted rw, tmpfs on /run and /run/lock, capability NET_ADMIN, security_opts apparmor=unconfined (not privileged). Pin git.rkdr.net/mortis/name:version@sha256:digest. See the documentation label." net.rkdr.mortis.usage="Molecule docker-driver platform with pre_build_image true, command /sbin/init, cgroupns_mode host, /sys/fs/cgroup mounted rw, tmpfs on /run and /run/lock, capability NET_ADMIN, security_opts apparmor=unconfined (not privileged). Pin git.rkdr.net/mortis/name:version@sha256:digest. See the documentation label."
ENV DEBIAN_FRONTEND=noninteractive ENV DEBIAN_FRONTEND=noninteractive
@@ -44,13 +44,16 @@ ENV DEBIAN_FRONTEND=noninteractive
# systemd as PID 1 with D-Bus, sudo and networking tools; the Python Ansible needs on # systemd as PID 1 with D-Bus, sudo and networking tools; the Python Ansible needs on
# the target (python3-apt for the apt module); the firewall and intrusion-prevention # the target (python3-apt for the apt module); the firewall and intrusion-prevention
# packages the roles manage (python3-systemd is a dependency of fail2ban's systemd # packages the roles manage (python3-systemd is a dependency of fail2ban's systemd
# backend); sshd, enabled so a converge can test it under systemd. # backend); sshd, enabled so a converge can test it under systemd; gnupg, which the docker
# scenario signs its stand-in APT repository with and which would otherwise cost it an
# apt update and install in every run.
RUN apt-get update \ RUN apt-get update \
&& apt-get install -y --no-install-recommends \ && apt-get install -y --no-install-recommends \
systemd systemd-sysv dbus sudo iproute2 ca-certificates \ systemd systemd-sysv dbus sudo iproute2 ca-certificates \
python3 python3-apt python3-systemd \ python3 python3-apt python3-systemd \
iptables ufw fail2ban \ iptables ufw fail2ban \
openssh-server \ openssh-server \
gnupg \
&& rm -rf /var/lib/apt/lists/* \ && rm -rf /var/lib/apt/lists/* \
&& systemctl enable ssh && systemctl enable ssh
+1 -1
View File
@@ -59,7 +59,7 @@ What it shows, with the role's tasks running unchanged:
- The argument check refuses a mapping for `docker_users` and a non-boolean `docker_remove`. - The argument check refuses a mapping for `docker_users` and a non-boolean `docker_remove`.
- A second run changes nothing (molecule's idempotence check). - A second run changes nothing (molecule's idempotence check).
What it does not show: that the upstream repository and key at `download.docker.com` are reachable and valid, that the real packages install, that `dockerd` starts, anything about container networking or iptables, the `docker_update` path (`tasks/update.yml`), and removal without `docker_remove_data` (the removal stops the unit first, so it can run only once per install). It needs the Ubuntu mirrors, for `gnupg` in `prepare.yml` and the `curl` the role installs. These gaps are a known residual risk of the role. What it does not show: that the upstream repository and key at `download.docker.com` are reachable and valid, that the real packages install, that `dockerd` starts, anything about container networking or iptables, the `docker_update` path (`tasks/update.yml`), and removal without `docker_remove_data` (the removal stops the unit first, so it can run only once per install). It needs the Ubuntu mirrors, for the `curl` the role installs. These gaps are a known residual risk of the role.
## Notes ## Notes
@@ -26,3 +26,20 @@ provisioner:
name: ansible name: ansible
verifier: verifier:
name: ansible name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
- destroy
+3 -8
View File
@@ -3,20 +3,15 @@
# bridge, iptables and a delegated cgroup), so the role installs stand-in packages from a # bridge, iptables and a delegated cgroup), so the role installs stand-in packages from a
# local APT repository. The repository is built and signed here, with a throwaway key, so the # local APT repository. The repository is built and signed here, with a throwaway key, so the
# role's own tasks run unchanged: fetch the key, write the source line, install, enable and # role's own tasks run unchanged: fetch the key, write the source line, install, enable and
# start the unit, join the group. Like the pihole and system_baseline scenarios, this needs # start the unit, join the group. gnupg, which signs the repository, is part of the molecule
# the Ubuntu mirrors for gnupg and for the curl the role installs. # image. Like the pihole and system_baseline scenarios, this needs the Ubuntu mirrors for the
# curl the role installs.
- name: Prepare - name: Prepare
hosts: all hosts: all
vars: vars:
docker_molecule_repo: /srv/docker-stub-repo docker_molecule_repo: /srv/docker-stub-repo
docker_molecule_work: /var/tmp/docker-stub-work docker_molecule_work: /var/tmp/docker-stub-work
tasks: tasks:
- name: Install gnupg, which signs the stand-in repository
ansible.builtin.apt:
name: gnupg
state: present
update_cache: true
- name: Copy the repository builder - name: Copy the repository builder
ansible.builtin.copy: ansible.builtin.copy:
src: build-stub-repo.sh src: build-stub-repo.sh
@@ -24,3 +24,20 @@ provisioner:
name: ansible name: ansible
verifier: verifier:
name: ansible name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
- destroy
@@ -24,3 +24,20 @@ provisioner:
name: ansible name: ansible
verifier: verifier:
name: ansible name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
- destroy
+21 -2
View File
@@ -1,6 +1,6 @@
# system_baseline # system_baseline
Applies an OS baseline chosen by `system_baseline_system_type`: apt upgrade, package install and removal, unattended-upgrades, locale, timezone, a journal size cap, sysctl hardening, tmpfs mounts and an optional reboot. Variables and their types are defined in [`meta/argument_specs.yml`](meta/argument_specs.yml), which is the source of truth. Applies an OS baseline chosen by `system_baseline_system_type`: apt upgrade, package install and removal, unattended-upgrades, locale, timezone, a journal size cap, sysctl hardening, tmpfs mounts, an optional tmux session on SSH login and an optional reboot. Variables and their types are defined in [`meta/argument_specs.yml`](meta/argument_specs.yml), which is the source of truth.
## Supported platforms ## Supported platforms
@@ -36,6 +36,9 @@ templating error instead of the role's own message.
| `system_baseline_sysctl_hardening` | from profile | no | List of `name` and `value` sysctl pairs | | `system_baseline_sysctl_hardening` | from profile | no | List of `name` and `value` sysctl pairs |
| `system_baseline_secure_tmp_mounts` | from profile | no | Paths remounted as tmpfs with `noexec,nosuid,nodev` | | `system_baseline_secure_tmp_mounts` | from profile | no | Paths remounted as tmpfs with `noexec,nosuid,nodev` |
| `system_baseline_journal_max_use` | `200M` | no | Upper bound of the persistent journal (journald `SystemMaxUse`). | | `system_baseline_journal_max_use` | `200M` | no | Upper bound of the persistent journal (journald `SystemMaxUse`). |
| `system_baseline_tmux_autostart` | `false` | no | Attach interactive SSH logins to a tmux session (`ubuntu_lxc` and `ubuntu_vm` only) |
| `system_baseline_tmux_session` | `main` | no | Session name, `A-Za-z0-9_-`, up to 32 characters |
| `system_baseline_tmux_windows` | `[]` | no | `{name, command}` windows made when the session is created |
| `system_baseline_timezone` | `Etc/UTC` | no | Timezone | | `system_baseline_timezone` | `Etc/UTC` | no | Timezone |
| `system_baseline_locale` | `en_US.UTF-8` | no | Locale | | `system_baseline_locale` | `en_US.UTF-8` | no | Locale |
| `system_baseline_reboot_if_required` | `true` | no | Reboot when `/var/run/reboot-required` exists | | `system_baseline_reboot_if_required` | `true` | no | Reboot when `/var/run/reboot-required` exists |
@@ -78,7 +81,7 @@ Besides `main`, two task files are a supported interface, for a caller that driv
## Tags ## Tags
`always` (validation), `update` (apt upgrade and the reboot), `packages`, `unattended-upgrades`, `locale`, `timezone`, `journald`, `sysctl`, `secure_tmp`. `always` (validation), `update` (apt upgrade and the reboot), `packages`, `unattended-upgrades`, `locale`, `timezone`, `journald`, `sysctl`, `secure_tmp`, `tmux`.
## Example play ## Example play
@@ -92,6 +95,22 @@ Besides `main`, two task files are a supported interface, for a caller that driv
- role: mortis.kamino.system_baseline - role: mortis.kamino.system_baseline
``` ```
## tmux on SSH login
With `system_baseline_tmux_autostart: true` an interactive SSH login attaches to the session `system_baseline_tmux_session` (created when missing), so a dropped connection loses nothing. The `ubuntu_lxc` and `ubuntu_vm` profiles install `tmux`; `pve` never gets the snippet.
```yaml
system_baseline_tmux_autostart: true
system_baseline_tmux_session: ops
system_baseline_tmux_windows:
- { name: logs, command: "journalctl -f" }
```
- It is `/etc/profile.d/tmux-autostart.sh`, read only by an interactive login shell, so `scp`, `sftp`, `ssh host command` and Ansible never trigger it. sshd's `ForceCommand` is not used: it applies to every session type and a broken tmux would lock all of them out. It only acts for an SSH login with a terminal, outside tmux, and without `~/.no-tmux`.
- Turn it off for one login with `ssh -t host bash` (a non-login shell does not read `/etc/profile.d`), for one user with `touch ~/.no-tmux`, and for the host by setting the variable to `false` and running the role (it removes the snippet).
- The windows are made when the session is created; a login that re-attaches adds none, so a change applies from the next new session. A window closes when its command exits.
- Security: the name and commands are validated (`A-Za-z0-9_-`, one line) and shell-quoted, and come from the inventory, never from a user. The file is root-owned and not writable by its users. The commands run as the user who logs in, are readable by every user and show in `ps`: no secrets in a command. A session outlives the SSH connection, so a root session stays open until it is closed.
## Notes ## Notes
- The `pve` profile has no `ufw`; the `ubuntu_*` profiles install it and `fail2ban`. - The `pve` profile has no `ufw`; the `ubuntu_*` profiles install it and `fail2ban`.
+9
View File
@@ -6,6 +6,13 @@ system_baseline_locale: "en_US.UTF-8"
system_baseline_reboot_if_required: true system_baseline_reboot_if_required: true
# Upper bound of the persistent journal (journald SystemMaxUse); older archived files are removed above it. # Upper bound of the persistent journal (journald SystemMaxUse); older archived files are removed above it.
system_baseline_journal_max_use: 200M system_baseline_journal_max_use: 200M
# Attach an interactive SSH login to a tmux session (see tasks/tmux.yml). Off by default: it changes what every login does.
# Only the ubuntu_lxc and ubuntu_vm profiles honour it; pve never installs the snippet.
system_baseline_tmux_autostart: false
# Name of the session an SSH login attaches to.
system_baseline_tmux_session: main
# Windows created, as extra entries next to a plain shell, when the session is created: a list of {name, command}.
system_baseline_tmux_windows: []
# Per-system_type policy. Everything below is a role default, so group_vars and host_vars # Per-system_type policy. Everything below is a role default, so group_vars and host_vars
# override it with normal Ansible precedence. # override it with normal Ansible precedence.
@@ -83,6 +90,7 @@ system_baseline_profiles:
essential_packages: essential_packages:
- logrotate - logrotate
- vim - vim
- tmux
- curl - curl
- wget - wget
- git - git
@@ -137,6 +145,7 @@ system_baseline_profiles:
- qemu-guest-agent - qemu-guest-agent
- logrotate - logrotate
- vim - vim
- tmux
- curl - curl
- wget - wget
- git - git
+34 -1
View File
@@ -5,7 +5,7 @@ argument_specs:
description: description:
- >- - >-
Validates C(system_baseline_system_type), then runs the update, packages, unattended-upgrades, locale, timezone, journald, Validates C(system_baseline_system_type), then runs the update, packages, unattended-upgrades, locale, timezone, journald,
sysctl, tmpfs and reboot task files, in that order. sysctl, tmpfs, tmux and reboot task files, in that order.
- Needs gathered facts, because the reboot check reads C(ansible_os_family). - Needs gathered facts, because the reboot check reads C(ansible_os_family).
- >- - >-
The resolved inputs C(system_baseline_profile), C(system_baseline_essential_packages), The resolved inputs C(system_baseline_profile), C(system_baseline_essential_packages),
@@ -42,6 +42,39 @@ argument_specs:
description: description:
- Upper bound of the persistent systemd journal (journald C(SystemMaxUse), for example C(200M)). - Upper bound of the persistent systemd journal (journald C(SystemMaxUse), for example C(200M)).
- Written to a drop-in under C(/etc/systemd/journald.conf.d). - Written to a drop-in under C(/etc/systemd/journald.conf.d).
system_baseline_tmux_autostart:
type: bool
default: false
description:
- >-
Attach an interactive SSH login to a tmux session, creating it when it does not exist. Installs C(/etc/profile.d/tmux-autostart.sh),
read only by an interactive login shell, so scp, sftp, C(ssh host command) and automation are unaffected. A user opts out with
C(~/.no-tmux). Only the C(ubuntu_lxc) and C(ubuntu_vm) profiles install it; with false, or on C(pve), the file is removed.
system_baseline_tmux_session:
type: str
default: main
description:
- Name of the session, 1 to 32 characters of C(A-Za-z0-9_-). Checked only when C(system_baseline_tmux_autostart) is true.
system_baseline_tmux_windows:
type: list
elements: dict
default: []
description:
- >-
Windows made when the session is created (a login that only re-attaches adds none), next to a plain shell. A window closes when its
command exits. The commands come from the inventory and are shell-quoted, but they run as the user who logs in, are readable by
every user on the host and show in C(ps): put no secret in one.
options:
name:
type: str
required: true
description:
- Window name, 1 to 32 characters of C(A-Za-z0-9_-).
command:
type: str
required: true
description:
- One-line shell command (no line break) run in the window.
system_baseline_timezone: system_baseline_timezone:
type: str type: str
default: Etc/UTC default: Etc/UTC
@@ -24,6 +24,10 @@
gather_facts: true gather_facts: true
vars: vars:
system_baseline_system_type: ubuntu_lxc system_baseline_system_type: ubuntu_lxc
system_baseline_tmux_autostart: true
system_baseline_tmux_session: molecule
system_baseline_tmux_windows:
- { name: logs, command: "echo 'a b'; true" }
roles: roles:
- role: mortis.kamino.system_baseline - role: mortis.kamino.system_baseline
@@ -44,6 +48,8 @@
ansible.builtin.assert: ansible.builtin.assert:
that: that:
- "'ufw' not in system_baseline_essential_packages" - "'ufw' not in system_baseline_essential_packages"
- "'tmux' not in system_baseline_essential_packages"
- not system_baseline_tmux_autostart
- "'unattended-upgrades' in system_baseline_essential_packages" - "'unattended-upgrades' in system_baseline_essential_packages"
- system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot'] == false - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot'] == false
- system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '03:00' - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '03:00'
@@ -65,6 +71,7 @@
ansible.builtin.assert: ansible.builtin.assert:
that: that:
- "'qemu-guest-agent' in system_baseline_essential_packages" - "'qemu-guest-agent' in system_baseline_essential_packages"
- "'tmux' in system_baseline_essential_packages"
- system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot'] == false - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot'] == false
- system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '04:00' - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '04:00'
- system_baseline_sysctl_hardening | selectattr('name', 'equalto', 'net.ipv4.conf.all.log_martians') | list | length == 1 - system_baseline_sysctl_hardening | selectattr('name', 'equalto', 'net.ipv4.conf.all.log_martians') | list | length == 1
@@ -31,3 +31,20 @@ provisioner:
skip-tags: molecule-notest,notest,sysctl,secure_tmp,update,timezone skip-tags: molecule-notest,notest,sysctl,secure_tmp,update,timezone
verifier: verifier:
name: ansible name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
- destroy
@@ -13,6 +13,7 @@
- "'ufw' in ansible_facts.packages" - "'ufw' in ansible_facts.packages"
- "'fail2ban' in ansible_facts.packages" - "'fail2ban' in ansible_facts.packages"
- "'unattended-upgrades' in ansible_facts.packages" - "'unattended-upgrades' in ansible_facts.packages"
- "'tmux' in ansible_facts.packages"
- "'telnet' not in ansible_facts.packages" - "'telnet' not in ansible_facts.packages"
quiet: true quiet: true
@@ -27,6 +28,29 @@
- system_baseline_verify_journald.content | b64decode is search('(?m)^SystemMaxUse=200M$') - system_baseline_verify_journald.content | b64decode is search('(?m)^SystemMaxUse=200M$')
quiet: true quiet: true
- name: Read the tmux auto-start snippet
ansible.builtin.slurp:
src: /etc/profile.d/tmux-autostart.sh
register: system_baseline_verify_tmux
- name: Stat the tmux auto-start snippet
ansible.builtin.stat:
path: /etc/profile.d/tmux-autostart.sh
register: system_baseline_verify_tmux_stat
- name: The snippet is root-owned, attaches to the session, and quotes the window command as one argument
ansible.builtin.assert:
that:
- system_baseline_verify_tmux_stat.stat.pw_name == 'root'
- system_baseline_verify_tmux_stat.stat.mode == '0644'
- system_baseline_verify_tmux.content | b64decode is search('tmux attach-session -t =molecule')
- system_baseline_verify_tmux.content | b64decode is search("-n logs 'echo '\"'\"'a b'\"'\"'; true'")
quiet: true
- name: The snippet is valid shell
ansible.builtin.command: /bin/sh -n /etc/profile.d/tmux-autostart.sh
changed_when: false
- name: Read the apt configuration the role writes - name: Read the apt configuration the role writes
ansible.builtin.slurp: ansible.builtin.slurp:
src: "{{ item }}" src: "{{ item }}"
+4
View File
@@ -36,6 +36,10 @@
ansible.builtin.import_tasks: secure_tmp.yml ansible.builtin.import_tasks: secure_tmp.yml
tags: secure_tmp tags: secure_tmp
- name: Start tmux on SSH login
ansible.builtin.import_tasks: tmux.yml
tags: tmux
- name: Reboot if required - name: Reboot if required
ansible.builtin.import_tasks: reboot.yml ansible.builtin.import_tasks: reboot.yml
tags: update tags: update
+42
View File
@@ -0,0 +1,42 @@
---
# Attach an interactive SSH login to a tmux session, created with the configured windows when it does not exist.
# /etc/profile.d is read only by an interactive login shell, so scp, sftp, `ssh host command` and automation never trigger it.
# sshd's ForceCommand is deliberately not used: it applies to every session type and a broken tmux would lock out all of them.
#
# Security: the session name, window names and commands are role inputs (inventory), never read from a user or a fact. They are
# validated here and shell-quoted in the template. The script is root-owned and not writable by the users it runs for. It is
# world-readable and the commands show in `ps`, so a command must hold no secret. Commands run as the user who logs in.
- name: Check the tmux inputs
ansible.builtin.assert:
that:
- system_baseline_tmux_session is match('^[A-Za-z0-9_-]{1,32}$')
- system_baseline_tmux_windows is sequence and system_baseline_tmux_windows is not string
- system_baseline_tmux_windows | map(attribute='name', default='') | map('regex_search', '^[A-Za-z0-9_-]{1,32}$') | select | list | length
== system_baseline_tmux_windows | length
- system_baseline_tmux_windows | map(attribute='command', default='') | select('match', '^[^\n\r]+$') | list | length
== system_baseline_tmux_windows | length
fail_msg: >-
system_baseline_tmux_session must be 1-32 characters of A-Z a-z 0-9 _ - ; every system_baseline_tmux_windows entry needs
a name (same characters) and a one-line command.
quiet: true
when: system_baseline_tmux_autostart | bool
- name: Install the tmux auto-start snippet
ansible.builtin.template:
src: tmux-autostart.sh.j2
dest: /etc/profile.d/tmux-autostart.sh
owner: root
group: root
mode: "0644"
validate: /bin/sh -n %s
when:
- system_baseline_tmux_autostart | bool
- system_baseline_system_type in ['ubuntu_lxc', 'ubuntu_vm']
become: true
- name: Remove the tmux auto-start snippet
ansible.builtin.file:
path: /etc/profile.d/tmux-autostart.sh
state: absent
when: not (system_baseline_tmux_autostart | bool and system_baseline_system_type in ['ubuntu_lxc', 'ubuntu_vm'])
become: true
@@ -0,0 +1,14 @@
# Managed by Ansible (mortis.kamino.system_baseline, tasks/tmux.yml). Do not edit: the next run overwrites it.
# Interactive SSH logins only (profile.d is not read by scp, sftp, `ssh host command` or Ansible).
# Off for one user: touch ~/.no-tmux
if [ -n "$SSH_CONNECTION" ] && [ -z "$TMUX" ] && [ -t 0 ] && [ ! -e "$HOME/.no-tmux" ] && command -v tmux >/dev/null 2>&1; then
# new-session -d fails when the session exists, so the windows below are made only when this login creates it (once, even
# for two logins at the same moment). Windows close when their command exits; window 0 is always a plain shell.
if tmux new-session -d -s {{ system_baseline_tmux_session | quote }} 2>/dev/null; then
:
{% for window in system_baseline_tmux_windows %}
tmux new-window -d -t {{ ('=' ~ system_baseline_tmux_session ~ ':') | quote }} -n {{ window.name | quote }} {{ window.command | quote }}
{% endfor %}
fi
exec tmux attach-session -t {{ ('=' ~ system_baseline_tmux_session) | quote }}
fi
@@ -24,3 +24,20 @@ provisioner:
name: ansible name: ansible
verifier: verifier:
name: ansible name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
- destroy
+184
View File
@@ -0,0 +1,184 @@
# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Choose the molecule scenarios a run needs.
python3 -I scripts/select_molecule_scenarios.py [<base-ref>]
Prints one scenario directory per line (`extensions/molecule/<name>` or
`roles/<role>/molecule/<name>`), extensions first, then roles, each sorted. The molecule
workflow runs `molecule test` in each.
Only a pull request is narrowed, and only when <base-ref> is given and EVENT_NAME is
`pull_request`. Then the diff of <base-ref>...HEAD decides:
* a file under roles/<role>/ selects that role's scenarios, and nothing else;
* a file on the IGNORED list (documentation, changelog, repository tooling that no
scenario reads) selects nothing;
* any other file selects every scenario.
The roles do not depend on one another, so a change inside one role cannot alter another
role's result. If one ever does (a role calling another, a shared plugin), the shared file
sits outside roles/<role>/ and so already selects everything; only an explicit role-to-role
dependency would need a rule here.
Every other case runs everything: a push, a manual dispatch, a scheduled run, no <base-ref>, a git
failure.
Narrowing is an optimisation, so any doubt resolves to the full set. The scenarios the
selection skips are not skipped on `main`: the push run after the merge runs them all.
A changed role that exists but has no scenario is an error, not an empty selection: a new role
without a molecule scenario, or a deleted or renamed scenario, must not pass Molecule with
nothing tested. A role whose directory is gone (the role was deleted) selects nothing.
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.
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
control characters in paths escaped so a crafted file name cannot inject a log command.
"""
import fnmatch
import os
import subprocess
import sys
# Paths no scenario reads. A match is by fnmatch on the repository-relative path, where `*`
# also crosses `/`. Keep this list short and literal: anything not listed runs everything.
IGNORED = (
"docs/*",
"changelogs/*",
"LICENSES/*",
"README.md",
"CONTRIBUTING.md",
"SECURITY.md",
"GLOSSARY.md",
"CLAUDE.md",
"CHANGELOG.rst",
"COPYING",
"NOTICE",
"REUSE.toml",
"renovate.json",
".gitignore",
".yamllint",
".ansible-lint",
".pre-commit-config.yaml",
"requirements-dev.txt",
"apm.yml",
"apm.lock.yaml",
"tests/sanity/*",
"tests/scripts/*",
"images/*",
".gitea/actionlint.yaml",
".gitea/workflows/lint.yml",
".gitea/workflows/build.yml",
".gitea/workflows/image.yml",
".gitea/workflows/renovate.yml",
"scripts/bump_image_versions.py",
"scripts/check_bot_pr_diff.py",
"scripts/check_image_versions.py",
"scripts/check_tarball.py",
"scripts/dev-setup.sh",
"scripts/reuse_lint.py",
)
def printable(text):
"""`text` with control characters (a newline in a file name) escaped, for a log line."""
return "".join(c if c.isprintable() else c.encode("unicode_escape").decode("ascii") for c in text)
def discover(root="."):
"""Every scenario directory, extensions first, each group sorted."""
found = []
ext = os.path.join(root, "extensions", "molecule")
if os.path.isdir(ext):
for name in sorted(os.listdir(ext)):
if name.isprintable() and os.path.isfile(os.path.join(ext, name, "molecule.yml")):
found.append(f"extensions/molecule/{name}")
roles = os.path.join(root, "roles")
if os.path.isdir(roles):
for role in sorted(os.listdir(roles)):
mol = os.path.join(roles, role, "molecule")
if not os.path.isdir(mol):
continue
for name in sorted(os.listdir(mol)):
if role.isprintable() and name.isprintable() and os.path.isfile(os.path.join(mol, name, "molecule.yml")):
found.append(f"roles/{role}/molecule/{name}")
return found
def is_ignored(path):
return any(fnmatch.fnmatchcase(path, pattern) for pattern in IGNORED)
def select(all_scenarios, changed, root="."):
"""The scenarios `changed` (repository-relative paths) needs, and a one-line reason.
Raises ValueError when a changed role still exists but has no scenario.
"""
roles = set()
for path in changed:
if is_ignored(path):
continue
parts = path.split("/")
if len(parts) > 2 and parts[0] == "roles":
roles.add(parts[1])
continue
return list(all_scenarios), f"{printable(path)} can affect every scenario"
chosen = [s for s in all_scenarios if s.startswith("roles/") and s.split("/")[1] in roles]
covered = {s.split("/")[1] for s in chosen}
bare = sorted(r for r in roles - covered if os.path.isdir(os.path.join(root, "roles", r)))
if bare:
raise ValueError("changed role without a molecule scenario: " + ", ".join(printable(r) for r in bare))
if roles:
reason = "only roles changed: " + ", ".join(printable(r) for r in sorted(roles))
else:
reason = "no change that a scenario reads"
return chosen, reason
def changed_paths(base_ref):
"""Paths changed in base_ref...HEAD; a rename counts as a delete plus an add."""
out = subprocess.run(
["git", "diff", "--name-only", "--no-renames", "-z", f"{base_ref}...HEAD", "--"],
check=True, capture_output=True,
).stdout
return [os.fsdecode(p) for p in out.split(b"\0") if p]
def main(argv, environ=None):
environ = os.environ if environ is None else environ
if len(argv) > 2:
print("usage: select_molecule_scenarios.py [<base-ref>]", file=sys.stderr)
return 2
base_ref = argv[1] if len(argv) == 2 else ""
scenarios = discover()
if not scenarios:
print("::error::no molecule scenario found", file=sys.stderr)
return 1
if environ.get("EVENT_NAME") != "pull_request" or not base_ref:
print(f"::notice::Running all {len(scenarios)} scenarios (not a pull request)", file=sys.stderr)
chosen = scenarios
else:
try:
changed = changed_paths(base_ref)
except (subprocess.CalledProcessError, OSError, UnicodeError) as exc:
print(f"::warning::cannot diff against {printable(base_ref)} ({printable(str(exc))}); running all scenarios",
file=sys.stderr)
chosen = scenarios
else:
try:
chosen, reason = select(scenarios, changed)
except ValueError as exc:
print(f"::error::{exc}", file=sys.stderr)
return 1
print(f"::notice::Running {len(chosen)} of {len(scenarios)} scenarios: {reason}", file=sys.stderr)
for scenario in chosen:
print(scenario)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
@@ -0,0 +1,248 @@
# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run with: python3 -m unittest discover -s tests/scripts"""
import contextlib
import io
import os
import pathlib
import subprocess
import sys
import tempfile
import unittest
from unittest import mock
import yaml
REPO = pathlib.Path(__file__).resolve().parents[2]
sys.path.insert(0, str(REPO / "scripts"))
import select_molecule_scenarios as sel # noqa: E402
ALL = [
"extensions/molecule/image-smoke",
"extensions/molecule/image-smoke-2604",
"roles/docker/molecule/default",
"roles/fail2ban/molecule/default",
"roles/system_baseline/molecule/default",
]
class SelectTest(unittest.TestCase):
def test_role_change_selects_only_that_role(self):
chosen, _reason = sel.select(ALL, ["roles/docker/tasks/main.yml", "roles/docker/molecule/default/verify.yml"])
self.assertEqual(chosen, ["roles/docker/molecule/default"])
def test_two_roles(self):
chosen, _reason = sel.select(ALL, ["roles/fail2ban/defaults/main.yml", "roles/docker/meta/main.yml"])
self.assertEqual(chosen, ["roles/docker/molecule/default", "roles/fail2ban/molecule/default"])
def test_ignored_only_selects_nothing(self):
chosen, _reason = sel.select(ALL, ["docs/x.md", "changelogs/fragments/a.yml", "README.md", "images/ci/Dockerfile"])
self.assertEqual(chosen, [])
def test_ignored_does_not_mask_a_role(self):
chosen, _reason = sel.select(ALL, ["docs/x.md", "roles/docker/tasks/main.yml"])
self.assertEqual(chosen, ["roles/docker/molecule/default"])
def test_anything_else_selects_everything(self):
for path in ("galaxy.yml", "meta/runtime.yml", "plugins/modules/x.py", "extensions/molecule/image-smoke/molecule.yml",
".gitea/workflows/molecule.yml", "scripts/select_molecule_scenarios.py",
"tests/unit/x.py",
"new_top_level_file", "roles/README.md"):
chosen, _reason = sel.select(ALL, ["roles/docker/tasks/main.yml", path])
self.assertEqual(chosen, ALL, path)
def test_deleted_role_selects_nothing_of_its_own(self):
chosen, _reason = sel.select(ALL, ["roles/gone/tasks/main.yml"])
self.assertEqual(chosen, [])
def test_ignored_patterns_are_not_prefix_tricks(self):
chosen, _reason = sel.select(ALL, ["docsx/y"])
self.assertEqual(chosen, ALL)
class MainTest(unittest.TestCase):
def setUp(self):
# main() runs git in the current directory: a hook's GIT_DIR must not redirect it.
patcher = mock.patch.dict(os.environ)
patcher.start()
self.addCleanup(patcher.stop)
for key in [k for k in os.environ if k.startswith("GIT_")]:
del os.environ[key]
def run_main(self, argv, env):
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = sel.main(["x"] + argv, env)
return code, out.getvalue().split(), err.getvalue()
def make_repo(self, root):
for rel in ("extensions/molecule/image-smoke", "roles/docker/molecule/default", "roles/fail2ban/molecule/default"):
d = pathlib.Path(root, rel)
d.mkdir(parents=True)
(d / "molecule.yml").write_text("---\n")
def git(self, root, *args):
# No GIT_* from the caller (a hook exports GIT_DIR), no user or system config.
env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
env.update(GIT_CONFIG_GLOBAL="/dev/null", GIT_CONFIG_NOSYSTEM="1")
subprocess.run(["git", "-C", root, "-c", "user.name=t", "-c", "[email protected]",
"-c", "commit.gpgsign=false", *args], check=True, capture_output=True, env=env)
def topic_repo(self, root, files):
"""A repo on `topic` whose one commit over `main` adds `files` (relative path -> text)."""
self.make_repo(root)
self.git(root, "init", "-q", "-b", "main")
self.git(root, "add", "-A")
self.git(root, "commit", "-qm", "base")
self.git(root, "switch", "-qc", "topic")
for rel, text in files.items():
f = pathlib.Path(root, rel)
f.parent.mkdir(parents=True, exist_ok=True)
f.write_text(text)
self.git(root, "add", "-A")
self.git(root, "commit", "-q", "--allow-empty", "-m", "change")
def in_dir(self, root):
cwd = os.getcwd()
os.chdir(root)
self.addCleanup(os.chdir, cwd)
def test_pull_request_is_narrowed_and_push_is_not(self):
with tempfile.TemporaryDirectory() as root:
self.make_repo(root)
self.git(root, "init", "-q", "-b", "main")
self.git(root, "add", "-A")
self.git(root, "commit", "-qm", "base")
self.git(root, "switch", "-qc", "topic")
pathlib.Path(root, "roles/docker/tasks").mkdir()
pathlib.Path(root, "roles/docker/tasks/main.yml").write_text("---\n")
self.git(root, "add", "-A")
self.git(root, "commit", "-q", "--allow-empty", "-m", "change")
cwd = os.getcwd()
os.chdir(root)
try:
code, out, _err = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, out), (0, ["roles/docker/molecule/default"]))
code, out, _err = self.run_main(["main"], {"EVENT_NAME": "push"})
self.assertEqual(len(out), 3)
code, out, _err = self.run_main([], {"EVENT_NAME": "pull_request"})
self.assertEqual(len(out), 3)
code, out, err = self.run_main(["no-such-ref"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, len(out)), (0, 3))
self.assertIn("::warning::", err)
finally:
os.chdir(cwd)
def test_empty_base_ref_argument_runs_all(self):
with tempfile.TemporaryDirectory() as root:
self.make_repo(root)
self.in_dir(root)
code, out, _err = self.run_main([""], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, len(out)), (0, 3))
def test_changed_role_without_a_scenario_fails(self):
with tempfile.TemporaryDirectory() as root:
self.topic_repo(root, {"roles/newrole/tasks/main.yml": "---\n"})
self.in_dir(root)
code, out, err = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, out), (1, []))
self.assertIn("::error::changed role without a molecule scenario: newrole", err)
def test_deleted_role_is_not_an_error(self):
with tempfile.TemporaryDirectory() as root:
self.topic_repo(root, {})
self.git(root, "rm", "-rq", "roles/fail2ban")
self.git(root, "commit", "-qm", "drop")
self.in_dir(root)
code, out, _err = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, out), (0, []))
def test_ignored_only_diff_passes_empty(self):
with tempfile.TemporaryDirectory() as root:
self.topic_repo(root, {"docs/a.md": "x\n"})
self.in_dir(root)
code, out, _err = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, out), (0, []))
def test_non_utf8_path_does_not_crash(self):
with tempfile.TemporaryDirectory() as root:
self.topic_repo(root, {})
broot = os.fsencode(root)
os.makedirs(os.path.join(broot, b"docs"))
with open(os.path.join(broot, b"docs", b"\xff.md"), "wb") as f:
f.write(b"x\n")
self.git(root, "add", "-A")
self.git(root, "commit", "-qm", "odd")
self.in_dir(root)
code, out, _err = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, out), (0, [])) # docs/* is ignored whatever the bytes
with open(os.path.join(broot, b"top\xff"), "wb") as f:
f.write(b"x")
self.git(root, "add", "-A")
self.git(root, "commit", "-qm", "odd2")
code, out, _err = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, len(out)), (0, 3)) # not ignored: everything
def test_too_many_arguments_is_usage(self):
code, out, err = self.run_main(["a", "b"], {})
self.assertEqual((code, out), (2, []))
self.assertIn("usage:", err)
def test_control_characters_are_escaped_in_notices(self):
self.assertEqual(sel.printable("a\n::add-mask::b"), "a\\n::add-mask::b")
_chosen, reason = sel.select(ALL, ["zz\n::add-mask::foo"])
self.assertNotIn("\n", reason)
def test_no_scenario_at_all_fails(self):
with tempfile.TemporaryDirectory() as root:
cwd = os.getcwd()
os.chdir(root)
try:
code, out, _err = self.run_main([], {})
self.assertEqual((code, out), (1, []))
finally:
os.chdir(cwd)
def test_every_tracked_file_is_ignored_or_selects_everything_or_is_a_role_file(self):
tracked = subprocess.run(["git", "-C", str(REPO), "ls-files", "-z"], capture_output=True, check=True,
env={k: v for k, v in os.environ.items() if not k.startswith("GIT_")}).stdout
scenarios = sel.discover(str(REPO))
for raw in tracked.split(b"\0"):
if not raw:
continue
path = os.fsdecode(raw)
if sel.is_ignored(path) or path.startswith("roles/"):
continue
chosen, _reason = sel.select(scenarios, [path], str(REPO))
self.assertEqual(chosen, scenarios, path)
def test_no_role_refers_to_another_role(self):
# The selection assumes roles are independent: a role that includes another would need a
# dependency rule in select(). Fail here instead of silently skipping the other's scenario.
roles = sorted(p.name for p in (REPO / "roles").iterdir() if p.is_dir())
for role in roles:
others = [r for r in roles if r != role]
for path in (REPO / "roles" / role).rglob("*"):
if not path.is_file():
continue
text = path.read_text(errors="ignore")
for other in others:
self.assertNotIn(f"mortis.kamino.{other}", text, f"{path.relative_to(REPO)} refers to {other}")
meta = REPO / "roles" / role / "meta" / "main.yml"
if meta.is_file():
data = yaml.safe_load(meta.read_text()) or {}
self.assertEqual(data.get("dependencies") or [], [], f"{role} declares role dependencies")
def test_literal_ignored_entries_exist(self):
for pattern in sel.IGNORED:
if "*" not in pattern:
self.assertTrue((REPO / pattern).exists(), f"{pattern} is on IGNORED but is not in the repository")
def test_discover_matches_the_repository(self):
found = sel.discover(str(REPO))
self.assertIn("extensions/molecule/image-smoke", found)
self.assertTrue(all((REPO / d / "molecule.yml").is_file() for d in found))
if __name__ == "__main__":
unittest.main()