Author SHA1 Message Date
renovate-bot bafea133d0 chore(deps): update lint tooling
renovate/stability-days Updates have met minimum release age requirement
Build / build (pull_request) Successful in 54s
Lint / lint (pull_request) Successful in 5m18s
Molecule / molecule (pull_request) Successful in 1m20s
2026-11-30 03:18:33 +00:00
72 changed files with 300 additions and 2024 deletions

No files matched your search

+1 -1
View File
@@ -16,7 +16,7 @@ provisioner:
defaults:
# Gather each host's facts once per playbook run, not in every play.
gathering: smart
# Per-task timings, to see what a scenario's time goes to; ansible.posix is in the molecule-controller image
# Per-task timings, to see what a scenario's time goes to; ansible.posix is in the ci image
# and in requirements.yml, so the controller always has these callbacks.
callbacks_enabled: ansible.posix.profile_tasks, ansible.posix.timer
callback_profile_tasks:
+11 -29
View File
@@ -53,8 +53,8 @@ issue.
- **Lint and Build run in the pinned `ci` image and compare the pin files with the checksums
baked into it (`/opt/ci-pins.sha256`).** A pull request that changes `requirements-dev.txt`,
`requirements-dev.lock`, `requirements.yml` or `.pre-commit-config.yaml` takes the slow path,
which installs the pinned tools and collections.
`requirements-dev.lock`, `requirements.yml`, `extensions/molecule/requirements.yml` or
`.pre-commit-config.yaml` takes the slow path, which installs the pinned tools and collections.
*Why:* a pull request is tested on its own pins, and an unchanged one starts in seconds.
*Held:* control: the "Check the baked tooling against the pins" step.
- **On the fast path the network is cut by environment**: `PIP_NO_INDEX=1`, the proxy variables
@@ -72,33 +72,19 @@ issue.
## Molecule
- **Molecule runs on every same-repository pull request, Renovate's included, with no path
filter.** A fork pull request is skipped by the jobs' shared `if:` guard, which is a convenience, not a
filter.** A fork pull request is skipped by the job's `if:`, which is a convenience, not a
boundary: a fork controls its own workflow file. Gitea's approval gate keeps a fork's runs from
starting, and the fork rule in [reviewing.md](../../docs/contributing/reviewing.md) keeps it
shut. *Why:* a check that always reports can be required, and a new image is tested by its own
pin pull request. *Held:* review.
- **Molecule has three jobs: `select`, `scenarios` and `result`.** `select` runs the selector in
a job container on `kamino-docker`, in the `molecule-controller` pin (never the `ci` pin, whose
bumps would then select every scenario), and outputs the selected directories, or `none`.
`scenarios` runs them on `kamino-molecule` and is skipped for `none` or an empty output.
`result` (check `Molecule / Result (pull_request)`) is the required check: it runs
`if: always()` and fails unless `select` passed and `scenarios` passed or was skipped for
`none`, so a lost output fails it. The
controller pin is written in all three jobs, because `container.image` cannot read `env`.
*Why:* a pull request that selects nothing takes no Molecule runner slot, and a skipped job
counts as passing in Gitea, so only a job that always runs can be required. *Held:* control:
`WorkflowJobsTest` in `tests/scripts/test_run_molecule_scenarios.py` for the jobs, runners,
guard and result logic, and `test_every_controller_pin_is_the_same` in
`tests/scripts/test_select_molecule_scenarios.py` for the pin copies.
- **What a pull request runs is chosen by `scripts/select_molecule_scenarios.py`:** the scenarios
of the roles it changes and of the roles that use them (any file naming
`mortis.kamino.<role>`, transitively), none for a diff of only IGNORED paths, a failure for a
changed role with no scenario, for a `.gitea/workflows/molecule.yml` diff of only comments
(outside `run:` scripts) or image pins the scenarios that name a changed `MOLECULE_IMAGE*` pin
(every scenario for `CONTROLLER_IMAGE`, or when a shared molecule file names the pin), and every
scenario for any other file, `requirements-molecule.*` included; `requirements-dev.*`, and
`lint.yml` and `build.yml` with their `ci` pins, are on IGNORED. *Why:* a full run takes the
single runner slot for a long time. *Held:* control: the selector and its tests.
(every scenario for `CI_IMAGE`, or when a shared molecule file names the pin), and every
scenario for any other file. *Why:* a full run takes
the single runner slot for a long time. *Held:* control: the selector and its tests.
- **A role named in an include, import, play `roles:` entry or meta dependency is written out in
full**, never bare or templated. *Why:* the selector finds dependent roles by their FQCN.
*Held:* control: a selector test fails a bare or templated name.
@@ -109,7 +95,7 @@ issue.
(release versions, `build_ignore`) do not change what a scenario runs, and the Build check
proves the collection builds; they had caused about a third of full pull request runs and their
minutes (#338). *Held:* control: `scripts/check_scenarios_load_checkout.py`, which
`run_molecule_in_controller.sh` runs on the selected scenarios before they start, fails the run
`run_molecule_in_ci_image.sh` runs on the selected scenarios before they start, fails the run
when the environment molecule gives `ansible-playbook` resolves `mortis.kamino` anywhere else,
or when `prerun` is not off once the base config is merged as molecule's CLI merges it (a
scenario turns it on, or the base config is moved or turns it on).
@@ -141,14 +127,10 @@ issue.
`test_a_scenario_past_its_time_limit_fails_alone` and
`test_the_default_time_limit_is_inside_the_job_timeout`, in the same file.
- **Molecule tests the pull request's pins, as Lint and Build do.** It runs molecule in the pinned
`molecule-controller` image ([ADR 0003](../../docs/adr/0003-molecule-controller-image.md)) and,
when a pin file differs from `/opt/molecule-pins.sha256`, installs the pull request's tools from
`requirements-molecule.lock` and the collections of `requirements.yml` and
`extensions/molecule/requirements.yml` first. A change to `requirements-molecule.txt` or
`requirements-molecule.lock` selects every scenario; `requirements-dev.*` pins only Lint's tools
and selects none. *Why:* a pull request that bumps ansible-core or molecule must run its
scenarios on them before it automerges. *Held:* control: the pin comparison in
`run_molecule_in_controller.sh`, and the selector's tests for which pin files select what.
`ci` image and, when a pin file differs from `/opt/ci-pins.sha256`, installs the pull request's
tools and the collections of `requirements.yml` and `extensions/molecule/requirements.yml` first.
*Why:* a pull request that raises the ansible-core floor must run its scenarios on the new core
before it automerges. *Held:* control: the pin comparison in `molecule.yml`.
- **Every scenario sets `scenario.test_sequence` to molecule's default minus both `destroy`
steps, with a role scenario's `check` right before and right after `converge`, names each
platform `${KAMINO_RUN_ID:-local}-<name>` and labels it
+3 -3
View File
@@ -28,7 +28,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.51@sha256:376e6319e1304f9fa9da1142e7884e39def496a1467528ccb4fe2d04017822db
image: git.rkdr.net/mortis/ci:0.2.48@sha256:d1c6653255abf366462c0265d9372626d5b59095084fe74ae95b9ebe7414007d
env:
PIP_DISABLE_PIP_VERSION_CHECK: "1"
steps:
@@ -66,8 +66,8 @@ jobs:
HTTP_PROXY=http://127.0.0.1:9 HTTPS_PROXY=http://127.0.0.1:9 no_proxy= NO_PROXY= >> "$GITHUB_ENV"
echo "::notice::Later steps run with a dead proxy; a download fails the job (bake it into images/ci)."
else
echo "::warning::requirements-dev.txt, requirements-dev.lock, requirements.yml" \
"or .pre-commit-config.yaml differ from the ci image;" \
echo "::warning::requirements-dev.txt, requirements-dev.lock, requirements.yml," \
"extensions/molecule/requirements.yml or .pre-commit-config.yaml differ from the ci image;" \
"installing the pinned tools for this run."
/opt/venv/bin/pip install --quiet --require-hashes -r requirements-dev.lock -r requirements-dev.txt
fi
+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.51@sha256:376e6319e1304f9fa9da1142e7884e39def496a1467528ccb4fe2d04017822db
image: git.rkdr.net/mortis/ci:0.2.48@sha256:d1c6653255abf366462c0265d9372626d5b59095084fe74ae95b9ebe7414007d
steps:
# The container has no Node, so JavaScript actions such as actions/checkout
# cannot run; clone with git and the job token.
+3 -3
View File
@@ -39,15 +39,15 @@ on: # yamllint disable-line rule:truthy
- main
paths:
- 'images/**'
# The ci image bakes these files' contents in (images/ci/Dockerfile); requirements.yml too.
# The ci image bakes these files' contents in (images/ci/Dockerfile).
- 'requirements-dev.txt'
- 'requirements-dev.lock'
- 'requirements.yml'
- 'extensions/molecule/requirements.yml'
- '.pre-commit-config.yaml'
# The molecule-controller image bakes these, and requirements.yml (its Dockerfile).
# The molecule-controller image bakes these (images/molecule-controller/Dockerfile).
- 'requirements-molecule.txt'
- 'requirements-molecule.lock'
- 'extensions/molecule/requirements.yml'
- '.gitea/workflows/image.yml'
workflow_dispatch: {}
+5 -5
View File
@@ -6,8 +6,8 @@ name: Lint
# The tools come from the ci image (images/ci, built by image.yml): the pinned Python
# tools of requirements-dev.txt, the collections of requirements.yml and the hook
# environments of .pre-commit-config.yaml are baked in. When a PR changes one of those
# files the checksum check below fails and the job installs the pinned tools and
# collections itself for this run (slower, same result).
# files or extensions/molecule/requirements.yml the checksum check below fails and the
# job installs the pinned tools and collections itself for this run (slower, same result).
on: # yamllint disable-line rule:truthy
pull_request:
branches:
@@ -31,7 +31,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.51@sha256:376e6319e1304f9fa9da1142e7884e39def496a1467528ccb4fe2d04017822db
image: git.rkdr.net/mortis/ci:0.2.48@sha256:d1c6653255abf366462c0265d9372626d5b59095084fe74ae95b9ebe7414007d
env:
PIP_DISABLE_PIP_VERSION_CHECK: "1"
PRE_COMMIT_HOME: /opt/pre-commit
@@ -65,8 +65,8 @@ jobs:
HTTP_PROXY=http://127.0.0.1:9 HTTPS_PROXY=http://127.0.0.1:9 no_proxy= NO_PROXY= >> "$GITHUB_ENV"
echo "::notice::Later steps run with a dead proxy; a download fails the job (bake it into images/ci)."
else
echo "::warning::requirements-dev.txt, requirements-dev.lock, requirements.yml" \
"or .pre-commit-config.yaml differ from the ci image;" \
echo "::warning::requirements-dev.txt, requirements-dev.lock, requirements.yml," \
"extensions/molecule/requirements.yml or .pre-commit-config.yaml differ from the ci image;" \
"installing the pinned tools and collections for this run."
/opt/venv/bin/pip install --quiet --require-hashes -r requirements-dev.lock -r requirements-dev.txt
# --force: the baked copy of a changed pin is replaced, not kept as "already installed".
+34 -124
View File
@@ -4,25 +4,18 @@ name: Molecule
# extensions/molecule/*/ and roles/*/molecule/*/. extensions/molecule/image-smoke and
# image-smoke-2604 test the test images themselves, so they run even before any role exists.
#
# Three jobs, so that a pull request that selects no scenario takes no Molecule runner slot:
# `select` chooses the scenarios in a job container on `kamino-docker`; `scenarios` runs them on
# `kamino-molecule`, and is skipped when none is selected; `result` is the required check and
# passes only when `select` passed and `scenarios` passed or was skipped for an empty selection.
#
# The scenarios job runs on the `kamino-molecule` label, a host executor that uses the runner's
# own Docker daemon; no job container is given the Docker socket. That makes the job
# It runs on the `kamino-molecule` label, a host executor that uses the runner's own
# Docker daemon; no job container is given the Docker socket. That makes the job
# root-equivalent on the runner, which is disposable and holds no secret from outside
# this repository. The `if:` guard is a convenience filter, not a boundary: a fork controls its
# own workflow file. The boundaries are write access, which only trusted people have, and Gitea's
# approval gate on fork runs, which the fork rule in docs/contributing/reviewing.md keeps shut.
#
# molecule runs in the pinned molecule-controller image via `docker run` with the runner's Docker
# socket, so the scenario containers start beside it on the runner's daemon; the job tree is mounted
# at the same path, so the paths molecule hands the daemon resolve. Like Lint and Build, it installs
# the pull request's pins when they differ from the image's. The images are pinned by tag and
# digest: bump them here when image.yml publishes a new molecule-controller, molecule-ubuntu2404 or
# molecule-ubuntu2604 version. The molecule-controller pin is written three times, because
# `container.image` cannot read `env`; a script test holds the copies equal.
# molecule runs in the pinned ci image via `docker run` with the runner's Docker socket, so the
# scenario containers start beside it on the runner's daemon; the job tree is mounted at the same
# path, so the paths molecule hands the daemon resolve. Like Lint and Build, it installs the pull
# request's pins when they differ from the image's. The images are pinned by tag and digest: bump
# them here when image.yml publishes a new ci, molecule-ubuntu2404 or molecule-ubuntu2604 version.
on: # yamllint disable-line rule:truthy
pull_request:
branches:
@@ -50,91 +43,23 @@ concurrency:
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
select:
molecule:
# Same-repo branches only (bot branches included: a Renovate pin pull request is what tests a new
# image); the nightly run and a manual dispatch always run. No paths filter on pull requests, so
# that Molecule can be a required check: a required check that a pull request never starts would
# block it. A fork pull request is skipped by the guard below, which all three jobs share.
# block it. A fork pull request is skipped by the guard below.
if: >-
github.repository == 'mortis/kamino' &&
(github.event_name != 'pull_request' ||
github.event.pull_request.head.repo.full_name == github.repository)
runs-on: kamino-docker
timeout-minutes: 10
# The molecule-controller pin, as CONTROLLER_IMAGE below: a ci pin here would make every ci
# bump select every scenario (ADR 0003).
container:
image: git.rkdr.net/mortis/molecule-controller:0.1.3@sha256:4fa8a653e7af673f8e9921068dd504700679cc5bdefbfd55369e9cbca3fa9b44
outputs:
scenarios: ${{ steps.select.outputs.scenarios }}
steps:
# The selector's diff needs origin/main and the full history, so a clone, not a fetch of HEAD.
- name: Checkout the commit under test
env:
GIT_CONFIG_COUNT: "1"
GIT_CONFIG_KEY_0: http.extraheader
GIT_CONFIG_VALUE_0: "AUTHORIZATION: bearer ${{ secrets.GITHUB_TOKEN }}"
SHA: ${{ github.event.pull_request.head.sha || github.sha }}
REF: ${{ github.ref }}
REPO_URL: ${{ github.server_url }}/${{ github.repository }}
run: |
rm -rf ac
mkdir -p ac/ansible_collections/mortis
git clone "$REPO_URL" ac/ansible_collections/mortis/kamino
cd ac/ansible_collections/mortis/kamino
# A clone has no refs/pull/*: fetch the run's ref when the sha is not on a branch.
git checkout "$SHA" || { git fetch origin "$REF" && git checkout "$SHA"; }
echo "Checked out $(git rev-parse HEAD)"
# A pull request runs only the scenarios of the roles it changes (scripts/select_molecule_scenarios.py
# explains the rules); the nightly run and a manual dispatch run all of them, because the
# selector narrows only when EVENT_NAME is pull_request.
- name: Select the scenarios
id: select
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: |
# 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
# `none` marks an empty selection, so a lost or empty output fails result, never passes.
if [ -z "$selected" ]; then selected=none; fi
# One directory per line; a random delimiter, so no line of the list can end the value.
delim="scenarios-$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')"
printf 'scenarios<<%s\n%s\n%s\n' "$delim" "$selected" "$delim" >> "$GITHUB_OUTPUT"
scenarios:
needs: select
# Skipped, not failed, when select fails, selects nothing (`none`) or loses its output (empty);
# result passes only the second.
if: >-
needs.select.outputs.scenarios != 'none' &&
needs.select.outputs.scenarios != '' &&
github.repository == 'mortis/kamino' &&
(github.event_name != 'pull_request' ||
github.event.pull_request.head.repo.full_name == github.repository)
runs-on: [kamino-molecule]
# A full run under load takes about 45 minutes (PR #405: 44m53s), so 45 left no margin. Also the
# age past which the sweep step removes a run's containers; a script test holds the two equal.
timeout-minutes: 90
env:
# The tools and collections molecule runs with, apart from Lint's (ADR 0003), so a tool
# bump only Lint uses selects no scenario.
CONTROLLER_IMAGE: >-
git.rkdr.net/mortis/molecule-controller:0.1.3@sha256:4fa8a653e7af673f8e9921068dd504700679cc5bdefbfd55369e9cbca3fa9b44
# The tools and collections molecule runs with: the image Lint and Build use.
CI_IMAGE: >-
git.rkdr.net/mortis/ci:0.2.48@sha256:d1c6653255abf366462c0265d9372626d5b59095084fe74ae95b9ebe7414007d
# Used by the scenarios as `image: ${MOLECULE_IMAGE}`; set it the same way to run
# one locally.
MOLECULE_IMAGE: >-
@@ -194,15 +119,33 @@ jobs:
for id in $old; do left="$left$(docker ps -aq --filter "id=$id")"; done
if [ -n "$left" ]; then echo "::error::could not remove ${left//$'\n'/ }"; exit 1; fi
# scripts/run_molecule_scenarios.sh runs the selected scenarios, a few at a time, and removes
# each scenario's containers as soon as it ends.
# A pull request runs only the scenarios of the roles it changes (scripts/select_molecule_scenarios.py
# explains the rules); the nightly run 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.
- name: Run the scenarios
working-directory: ac/ansible_collections/mortis/kamino
env:
SELECTED: ${{ needs.select.outputs.scenarios }}
EVENT_NAME: ${{ github.event_name }}
# The workflow only runs for pull requests to main; lint.yml uses the same constant.
BASE_REF: origin/main
# Empty outside a dispatch, which the run script reads as its default.
MOLECULE_LANES: ${{ inputs.lanes }}
run: |
# 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
# As the runner user, with the socket's group, so nothing in the job tree is left root-owned.
# HOME (ansible's temp and caches) is in the job tree; a mounted passwd entry points the user
# at it, because ansible's temp path is `~<user>/.ansible/tmp`. The driver's connection plugin
@@ -220,7 +163,7 @@ jobs:
-v "$ac_root:$ac_root" -v "$ac_root/passwd:/etc/passwd:ro" -w "$PWD" \
-e "AC_ROOT=$ac_root" -e "HOME=$ac_root/home" -e "USER=$(id -un)" \
-e MOLECULE_IMAGE -e MOLECULE_IMAGE_2604 -e KAMINO_RUN_ID -e MOLECULE_LANES \
"$CONTROLLER_IMAGE" scripts/run_molecule_in_controller.sh <<< "$SELECTED"
"$CI_IMAGE" scripts/run_molecule_in_ci_image.sh <<< "$selected"
# A cancelled run can leave its containers running when the docker client is killed.
- name: Remove this run's containers
@@ -233,36 +176,3 @@ jobs:
for id in $ids; do docker rm -f "$id" >/dev/null || true; done
left="$(docker ps -aq --filter "label=net.rkdr.mortis.molecule-run=$KAMINO_RUN_ID")"
if [ -n "$left" ]; then echo "::error::could not remove ${left//$'\n'/ }"; exit 1; fi
result:
name: Result
needs: [select, scenarios]
# always(): otherwise a failed select would skip this job, and Gitea counts a skipped job as
# passing. The guard is select's, so a fork pull request skips all three jobs alike and the run
# step below never sees a select skipped by it.
if: >-
always() &&
github.repository == 'mortis/kamino' &&
(github.event_name != 'pull_request' ||
github.event.pull_request.head.repo.full_name == github.repository)
runs-on: kamino-docker
timeout-minutes: 5
# The controller pin again, so this job adds no pin of its own to bump.
container:
image: git.rkdr.net/mortis/molecule-controller:0.1.3@sha256:4fa8a653e7af673f8e9921068dd504700679cc5bdefbfd55369e9cbca3fa9b44
steps:
- name: Check the select and scenarios jobs
env:
SELECT_RESULT: ${{ needs.select.result }}
SCENARIOS_RESULT: ${{ needs.scenarios.result }}
SELECTED: ${{ needs.select.outputs.scenarios }}
run: |
if [ "$SELECT_RESULT" != success ]; then
echo "::error::select ended as $SELECT_RESULT"; exit 1
fi
# A skip is a pass only for select's `none`: an empty output means it was lost.
if [ "$SCENARIOS_RESULT" = skipped ] && [ "$SELECTED" = none ]; then
echo "No scenario selected."
elif [ "$SCENARIOS_RESULT" != success ]; then
echo "::error::scenarios ended as $SCENARIOS_RESULT"; exit 1
fi
-17
View File
@@ -4,23 +4,6 @@ mortis.kamino Release Notes
.. contents:: Topics
v3.3.0
======
Minor Changes
-------------
- docker - New input ``docker_keyring_checksum``: the Docker APT key is verified against a pinned sha256, and a changed key fails the install until a person has checked it and updated the hash. Set ``docker_keyring_checksum`` too when ``docker_gpg_url`` is overridden.
- nfs_client - New role. Installs ``nfs-common`` and manages NFS mount entries in ``/etc/fstab`` from ``nfs_client_mounts`` (``src``, ``path``, optional ``opts`` and ``state`` ``present`` or ``absent``), with ``nfs_client_default_opts`` (default ``_netdev,nofail``) for an entry that sets none. It creates each mount point without owner, group or mode, writes only the fstab line, never mounts or unmounts, and reloads systemd after a change. An ``absent`` entry loses its line and nothing else. Declares Ubuntu noble and resolute; the molecule scenario never mounts a share.
- pve_vm - New role. Clones a Proxmox VE QEMU VM from a template through the Proxmox API (``community.proxmox``), sets its cloud-init user, SSH keys and network, updates an existing VM only on detected drift, grows its boot disk, applies the power state, waits for SSH and cloud-init and (with ``pve_vm_allow_destroy``) deletes it. It never sets a cloud-init password and deletes one stored on the VM. Only ``pve_vm_exists`` is set for later plays. The input checks run under ``tags: always``, so a tag-filtered run also needs ``pve_vm_api_user`` and ``pve_vm_api_token_secret`` (and ``pve_vm_disk_size`` while ``pve_vm_manage_disk`` is true). Declares Ubuntu noble and resolute guests; the molecule scenario covers the input validation and the drift detection, not the API lifecycle.
- traefik - The prerequisites install refreshes the APT cache only when it is older than an hour; before, every run refreshed it. A consumer who adds an APT source just before the role must refresh the cache first.
Bugfixes
--------
- fail2ban - ``--check`` no longer fails on a host where fail2ban is not installed yet, through either entry point; the preview reports the install and skips the configuration, service and jail tasks.
- ufw - ``--check`` no longer fails on a host where ufw is not installed yet; the preview reports the install and skips the tasks that need the ``ufw`` binary.
v3.2.0
======
+6 -4
View File
@@ -2,10 +2,10 @@
An Ansible Collection of reusable, hardened roles for a self-hosted home lab:
`cloudflared`, `docker`, `fail2ban`, `gitea`, `gitea_runner`, `network_interfaces`,
`nfs_client`, `pihole`, `pve_lxc`, `pve_vm`, `sshd`, `system_baseline`, `systemd_hardening`, `tailscale`, `traefik`,
`ufw` and `user_management`, plus the internal `_binary_update`. Roles still to come are listed under [Roadmap](#roadmap).
`nfs_client`, `pihole`, `pve_lxc`, `sshd`, `system_baseline`, `systemd_hardening`, `tailscale`, `traefik`, `ufw` and
`user_management`, plus the internal `_binary_update`. Roles still to come are listed under [Roadmap](#roadmap).
Status: roles arrive in waves. Release 3.3.0 holds the `cloudflared`, `docker`, `fail2ban`, `gitea`, `gitea_runner`, `network_interfaces`, `nfs_client`, `pihole`, `pve_lxc`, `pve_vm`, `sshd`, `system_baseline`, `systemd_hardening`, `tailscale`, `traefik`, `ufw` and `user_management` roles (and the internal `_binary_update`, which `cloudflared`, `gitea`, `gitea_runner` and `traefik` call).
Status: roles arrive in waves. Release 3.2.0 holds the `cloudflared`, `docker`, `fail2ban`, `gitea`, `gitea_runner`, `network_interfaces`, `pihole`, `pve_lxc`, `sshd`, `system_baseline`, `systemd_hardening`, `tailscale`, `traefik`, `ufw` and `user_management` roles (and the internal `_binary_update`, which `cloudflared`, `gitea`, `gitea_runner` and `traefik` call).
## Consuming
@@ -17,7 +17,7 @@ name (FQCN) only, `mortis.kamino.<role>`:
collections:
- name: https://git.rkdr.net/mortis/kamino.git
type: git
version: v3.3.0
version: v3.2.0
```
Its dependencies (`community.general`, `ansible.posix`, `community.proxmox`) are declared in `galaxy.yml`, so
@@ -41,7 +41,9 @@ when its own prerequisites (tests, a safe cutover wherever the role already runs
Still to come:
- Wave 2: `pve_vm`.
- Wave 3: `rke2`, `proxmox_host`.
- Later, wave not yet assigned: `opnsense`, `proxmox_firewall`.
Will not be extracted (they serve one lab or install that lab's own tool pins):
`k8s_manage`, `k8s_localhost`, `k8s_lint_tools`, `minecraft_server`, `dragonwilds_server`,
+9 -12
View File
@@ -113,16 +113,13 @@ reduction. A later decision that accepts a risk adds an entry here.
### Pin bumps first behaviour-tested after they merge
- **Risk:** Lint, Build and Molecule install a pull request's pins when they differ from their
image, and a change to `requirements-molecule.*`, `requirements.yml` or
`extensions/molecule/requirements.yml` selects every Molecule scenario, so Molecule's own tools
and collections are tested before they merge. A change to the `molecule-controller` Dockerfile
(its base image, uv or Python) selects none, because `images/` is on the selector's IGNORED
list; it is first behaviour-tested after it has merged, by the pull request that moves
`molecule.yml` to the new `molecule-controller` version. `requirements-dev.*` pins only Lint's
and Build's tools, which no scenario runs.
- **Why accepted:** that pull request runs every scenario before the new image is used, and the
Dockerfile's self-checks fail the build on `main` before any pin moves.
- **Trigger:** the pull request that moves `molecule.yml` to a new `molecule-controller` image
fails Molecule because of a changed image input.
- **Risk:** Lint, Build and Molecule install a pull request's pins when they differ from the
image, so a pull request that changes an image input is tested on its own pins. But most pin
bumps select no Molecule scenario: every Python pin except an ansible-core minor bump, which
edits `meta/runtime.yml`. Such a bump is first behaviour-tested after it has merged, by the
pull request that moves the workflows to the new `ci` image.
- **Why accepted:** that pull request runs every scenario before the new image is used,
and running every scenario on every Python pin bump would cost about 10 minutes each.
- **Trigger:** the pull request that moves the workflows to a new `ci` image fails Molecule
because of a bumped pin.
- **Planned reduction:** none for now.
+1 -9
View File
@@ -31,10 +31,6 @@ objects:
description: Manage /etc/network/interfaces
name: network_interfaces
version_added: null
nfs_client:
description: Install the NFS client and manage NFS entries in /etc/fstab
name: nfs_client
version_added: null
pihole:
description: Install and configure Pi-hole from the upstream repository
name: pihole
@@ -43,10 +39,6 @@ objects:
description: Manage a Proxmox LXC container
name: pve_lxc
version_added: null
pve_vm:
description: Manage a Proxmox VE QEMU VM cloned from a template
name: pve_vm
version_added: null
sshd:
description: Write a hardened sshd drop-in
name: sshd
@@ -93,4 +85,4 @@ plugins:
strategy: {}
test: {}
vars: {}
version: 3.3.0
version: 3.2.0
-44
View File
@@ -532,47 +532,3 @@ releases:
- refusals-in-verify.yml
- traefik-release-url.yml
release_date: '2026-11-27'
3.3.0:
changes:
bugfixes:
- fail2ban - ``--check`` no longer fails on a host where fail2ban is not installed
yet, through either entry point; the preview reports the install and skips
the configuration, service and jail tasks.
- ufw - ``--check`` no longer fails on a host where ufw is not installed yet;
the preview reports the install and skips the tasks that need the ``ufw``
binary.
minor_changes:
- 'docker - New input ``docker_keyring_checksum``: the Docker APT key is verified
against a pinned sha256, and a changed key fails the install until a person
has checked it and updated the hash. Set ``docker_keyring_checksum`` too when
``docker_gpg_url`` is overridden.'
- nfs_client - New role. Installs ``nfs-common`` and manages NFS mount entries
in ``/etc/fstab`` from ``nfs_client_mounts`` (``src``, ``path``, optional
``opts`` and ``state`` ``present`` or ``absent``), with ``nfs_client_default_opts``
(default ``_netdev,nofail``) for an entry that sets none. It creates each
mount point without owner, group or mode, writes only the fstab line, never
mounts or unmounts, and reloads systemd after a change. An ``absent`` entry
loses its line and nothing else. Declares Ubuntu noble and resolute; the molecule
scenario never mounts a share.
- 'pve_vm - New role. Clones a Proxmox VE QEMU VM from a template through the
Proxmox API (``community.proxmox``), sets its cloud-init user, SSH keys and
network, updates an existing VM only on detected drift, grows its boot disk,
applies the power state, waits for SSH and cloud-init and (with ``pve_vm_allow_destroy``)
deletes it. It never sets a cloud-init password and deletes one stored on
the VM. Only ``pve_vm_exists`` is set for later plays. The input checks run
under ``tags: always``, so a tag-filtered run also needs ``pve_vm_api_user``
and ``pve_vm_api_token_secret`` (and ``pve_vm_disk_size`` while ``pve_vm_manage_disk``
is true). Declares Ubuntu noble and resolute guests; the molecule scenario
covers the input validation and the drift detection, not the API lifecycle.'
- traefik - The prerequisites install refreshes the APT cache only when it is
older than an hour; before, every run refreshed it. A consumer who adds an
APT source just before the role must refresh the cache first.
fragments:
- 402-nfs-client.yml
- 448-docker-keyring-checksum.yml
- 456-system-baseline-purge-batch.yml
- 458-traefik-apt-cache-valid-time.yml
- 478-ufw-fail2ban-check-mode.yml
- 482-pve-vm.yml
- system-baseline-internal-registers.yml
release_date: '2026-12-01'
+8
View File
@@ -0,0 +1,8 @@
---
minor_changes:
- >-
nfs_client - New role. Installs ``nfs-common`` and manages NFS mount entries in ``/etc/fstab`` from ``nfs_client_mounts``
(``src``, ``path``, optional ``opts`` and ``state`` ``present`` or ``absent``), with ``nfs_client_default_opts``
(default ``_netdev,nofail``) for an entry that sets none. It creates each mount point without owner, group or mode,
writes only the fstab line, never mounts or unmounts, and reloads systemd after a change. An ``absent`` entry loses its
line and nothing else. Declares Ubuntu noble and resolute; the molecule scenario never mounts a share.
@@ -0,0 +1,6 @@
---
minor_changes:
- >-
docker - New input ``docker_keyring_checksum``: the Docker APT key is verified against a pinned
sha256, and a changed key fails the install until a person has checked it and updated the hash.
Set ``docker_keyring_checksum`` too when ``docker_gpg_url`` is overridden.
@@ -0,0 +1,4 @@
---
trivial:
- >-
system_baseline - Purge the unwanted packages that are installed in one apt call instead of one call per package.
@@ -0,0 +1,6 @@
---
minor_changes:
- >-
traefik - The prerequisites install refreshes the APT cache only when it is older than an hour;
before, every run refreshed it. A consumer who adds an APT source just before the role must
refresh the cache first.
@@ -0,0 +1,9 @@
---
bugfixes:
- >-
ufw - ``--check`` no longer fails on a host where ufw is not installed yet; the preview reports
the install and skips the tasks that need the ``ufw`` binary.
- >-
fail2ban - ``--check`` no longer fails on a host where fail2ban is not installed yet, through
either entry point; the preview reports the install and skips the configuration, service and
jail tasks.
@@ -1,5 +0,0 @@
---
trivial:
- >-
ufw - The check-mode probes read whether a command ran instead of whether it was skipped, which
ansible-core 2.25 stops reporting for a command in check mode.
@@ -0,0 +1,5 @@
---
trivial:
- >-
system_baseline - The registered results of the unattended-upgrades check and the reboot-required
check carry the internal ``__system_baseline_`` prefix.
+4 -4
View File
@@ -56,10 +56,10 @@ Every secret the workflows in [.gitea/workflows/](../../.gitea/workflows/) refer
A checklist, not rules: what the repository and organisation settings should be. The maintainer
applies them and checks them against this list after any change.
- Branch protection on `main`: required checks Lint, Build and `Molecule / Result (pull_request)`;
zero required approvals; "Require approval from code owners"; "Dismiss stale approvals"; block
on rejected and on official review requests; block on an outdated branch; administrators cannot
override; the approvals allowlist is the maintainer.
- Branch protection on `main`: required checks Lint, Build and Molecule; zero required approvals;
"Require approval from code owners"; "Dismiss stale approvals"; block on rejected and on official
review requests; block on an outdated branch; administrators cannot override; the approvals
allowlist is the maintainer.
- Merge allowlist on `main`: the maintainer, each trusted contributor and the Renovate bot.
- Push allowlist on `release/*`: the maintainer; no rule for `renovate/*`.
- Tag protection on `v*`, with the maintainer on its allowlist.
+18 -14
View File
@@ -1,21 +1,20 @@
# ci
The **CI tooling image** of the [`mortis.kamino`](https://git.rkdr.net/mortis/kamino) Collection: everything the Lint and Build
workflows used to install on each run is baked in, so a job only checks out the code and runs. The Molecule workflow
runs in the [`molecule-controller`](molecule-controller.md) image instead
([ADR 0003](../adr/0003-molecule-controller-image.md)), so a tool bump only Lint uses selects no Molecule scenario.
The **CI tooling image** of the [`mortis.kamino`](https://git.rkdr.net/mortis/kamino) Collection: everything the Lint, Build and
Molecule workflows used to install on each run is baked in, so a job only checks out the code and runs.
## What is in it
Ubuntu 26.04 with:
- **Python tools** in `/opt/venv` (on `PATH`; it runs on Python 3.14, the version of `.python-version`, from the baked copy and not from the distribution's `python3`), from `requirements-dev.lock` (the hashed lock of `requirements-dev.txt`, installed with `pip install --require-hashes`): `ansible-core`,
`ansible-lint`, `pre-commit`, `antsibull-changelog`, `galaxy-importer`, `reuse`, `molecule`
(without its Docker driver: Lint's "Test the repository scripts" step runs the tests that import it), and
`proxmoxer`, the controller-side library the modules of `community.proxmox` import.
`ansible-lint`, `pre-commit`, `antsibull-changelog`, `galaxy-importer`, `reuse`, `molecule` and
`molecule-plugins[docker]` (the Docker driver, with the `docker` Python SDK), and `proxmoxer`, the controller-side
library the modules of `community.proxmox` import.
- **The collections the roles call** in `/opt/collections` (`ANSIBLE_COLLECTIONS_PATH` is set to it), from
`requirements.yml`: `community.general`, `ansible.posix` and `community.proxmox` at the exact versions CI tests against, so
`ansible-lint --offline` resolves their modules instead of mocking them.
`ansible-lint --offline` resolves their modules instead of mocking them; and from
`extensions/molecule/requirements.yml`, `community.docker`, which the Molecule Docker driver's own playbooks call.
- **Every pre-commit hook environment** of `.pre-commit-config.yaml` in `/opt/pre-commit`
(`PRE_COMMIT_HOME`): conventional-pre-commit, gitleaks, yamllint, ruff, shellcheck-py, pre-commit-hooks, actionlint and zizmor. The Go
hooks are prebuilt; their toolchains, and the binaries of those repositories that no hook runs, are removed to
@@ -27,7 +26,7 @@ Ubuntu 26.04 with:
`python3`, so sanity runs its compile test for those interpreters instead of skipping it.
- `git`, `shellcheck` (actionlint runs it over `run:` blocks), `python3`, `python3-venv` and `ca-certificates`.
The image runs as root and sets no working directory.
- `/opt/ci-pins.sha256`: the checksums of the four pin files this image was built from.
- `/opt/ci-pins.sha256`: the checksums of the five pin files this image was built from.
It has no Node, so JavaScript actions (`actions/checkout`) cannot run in it: clone with `git`.
@@ -60,20 +59,25 @@ jobs:
pre-commit run --all-files --show-diff-on-failure
```
`/opt/ci-pins.sha256` lists the four pin files by their checkout-relative path, so `sha256sum -c` runs in the checkout root. When
the checkout's `requirements-dev.txt`, `requirements-dev.lock`, `requirements.yml` and `.pre-commit-config.yaml` match, the baked tools and
The Molecule job runs on the `kamino-molecule` runner, a host executor, so it starts the image itself with
`docker run`, as the runner user, with the Docker socket and the checkout mounted at the same path (molecule
hands the daemon paths in the checkout); `scripts/run_molecule_in_ci_image.sh` does the same pin check inside it.
Read `.gitea/workflows/molecule.yml` for the full command.
`/opt/ci-pins.sha256` lists the five pin files by their checkout-relative path, so `sha256sum -c` runs in the checkout root. When
the checkout's `requirements-dev.txt`, `requirements-dev.lock`, `requirements.yml`, `extensions/molecule/requirements.yml` and `.pre-commit-config.yaml` match, the baked tools and
collections are used as they are, and Lint and Build cut the network by environment (proxy variables and
`PIP_NO_INDEX`) for all but the script tests, so a tool that downloads at run time fails the job. When a pull request changes a pin the check fails and the job installs the pinned
tools and collections itself for that run
(slower, same result), until the image is rebuilt from `main`. `lint.yml`, `build.yml` and `gitea-release-key.yml`
(slower, same result), until the image is rebuilt from `main`. `lint.yml`, `build.yml`, `molecule.yml` and `gitea-release-key.yml`
are the real consumers.
## Tags and pinning
- `<version>` is semver, independent of the Collection's version. A published version is never moved or
rebuilt, so one digest belongs to exactly one version. `latest` is the newest version, for looking only.
- Pin `ci:<version>@sha256:<digest>`; the digest decides what is pulled. Consumers: `lint.yml`, `build.yml` and
`gitea-release-key.yml`.
- Pin `ci:<version>@sha256:<digest>`; the digest decides what is pulled. Consumers: `lint.yml`, `build.yml`,
`molecule.yml` and `gitea-release-key.yml`.
- Renovate is configured to move the pins to a new version after the image is built on `main` (the rule is in
`renovate.json`; the first pin of a brand-new image is made by hand).
+4 -4
View File
@@ -17,11 +17,11 @@ Ubuntu 26.04 with:
- **The collections the scenarios call** in `/opt/collections` (`ANSIBLE_COLLECTIONS_PATH` is set to it): those of
`requirements.yml` (`community.general`, `ansible.posix`, `community.proxmox`), which the roles call, and of
`extensions/molecule/requirements.yml` (`community.docker`), which the Docker driver's own playbooks call.
- `python3`, `python3-venv`, `ca-certificates` and `git` from the distribution. The image runs as root and sets no
- `python3`, `python3-venv` and `ca-certificates` from the distribution. The image runs as root and sets no
working directory.
- `/opt/molecule-pins.sha256`: the checksums of the four pin files this image was built from.
It has no Docker CLI: mount the host's Docker CLI and socket, and the checkout.
It has no Docker CLI and no `git`: mount the host's Docker CLI and socket, and the checkout.
## How to use it
@@ -32,8 +32,8 @@ checkout). In the checkout root, run `sha256sum --quiet -c /opt/molecule-pins.sh
`requirements-molecule.lock`, `requirements.yml` or `extensions/molecule/requirements.yml`, install the pinned tools
and collections for that run first (slower, same result), until the image is rebuilt from `main`.
`.gitea/workflows/molecule.yml` is its consumer: it pins the image as `CONTROLLER_IMAGE`, and
`scripts/run_molecule_in_controller.sh` runs the pin check inside it. Read the workflow for the full command.
No workflow consumes it yet; the Molecule workflow still runs in the [`ci`](ci.md) image until its first pin is made
by hand.
## Tags and pinning
+1 -1
View File
@@ -49,7 +49,7 @@ platforms:
systemd needs a writable cgroup (`cgroupns_mode: host`, the `/sys/fs/cgroup` mount and tmpfs on `/run`), the
firewall tools need `NET_ADMIN`, AppArmor is left unconfined for the container (`apparmor=unconfined`), and
nothing runs privileged. The docker driver needs molecule's docker plugin, which the molecule-controller image provides.
nothing runs privileged. The docker driver needs molecule's docker plugin, which the ci image provides.
The scenario `extensions/molecule/image-smoke` tests this image against that contract (release,
systemd, packages, the `dbus` and `ssh` units, the Python bindings, `NET_ADMIN`).
+1 -1
View File
@@ -50,7 +50,7 @@ platforms:
systemd needs a writable cgroup (`cgroupns_mode: host`, the `/sys/fs/cgroup` mount and tmpfs on `/run`), the
firewall tools need `NET_ADMIN`, AppArmor is left unconfined for the container (`apparmor=unconfined`), and
nothing runs privileged. The docker driver needs molecule's docker plugin, which the molecule-controller image provides.
nothing runs privileged. The docker driver needs molecule's docker plugin, which the ci image provides.
The scenario `extensions/molecule/image-smoke-2604` tests this image against that contract (release,
systemd, packages, the `dbus` and `ssh` units, the Python bindings, `NET_ADMIN`).
+2 -2
View File
@@ -2,8 +2,8 @@
# Collections the Molecule test harness itself calls, as opposed to the roles under test (those are
# in the requirements.yml at the repository root). The Docker driver of molecule-plugins runs
# community.docker modules in its own create and destroy playbooks, so every scenario needs it.
# The molecule-controller image (images/molecule-controller) bakes it into /opt/collections next to the
# root one; a pull request that changes it fails the image's pin check, so the Molecule job installs it itself.
# The ci image (images/ci) bakes it into /opt/collections next to the root one; a pull request that
# changes it fails the image's pin check, so the Molecule job installs it itself.
# Renovate (renovate.json, ansible-galaxy manager) bumps this pin.
collections:
- name: community.docker
+3 -3
View File
@@ -1,13 +1,13 @@
---
namespace: mortis
name: kamino
version: 3.3.0
version: 3.2.0
readme: README.md
authors:
- Defame1297
description: >-
Reusable, hardened Ansible roles for a self-hosted home lab (cloudflared, docker, fail2ban,
gitea, gitea_runner, network_interfaces, nfs_client, pihole, pve_lxc, pve_vm, sshd, system_baseline,
gitea, gitea_runner, network_interfaces, nfs_client, pihole, pve_lxc, sshd, system_baseline,
systemd_hardening, tailscale, traefik, ufw, user_management; _binary_update is internal).
license:
- GPL-3.0-or-later
@@ -22,7 +22,7 @@ homepage: https://git.rkdr.net/mortis/kamino
issues: https://git.rkdr.net/mortis/kamino/issues
# CI tests the versions pinned in requirements.yml; the lower bounds here are not tested.
# No upper bound, so a consumer's newer pin does not conflict. community.general is used by system_baseline and ufw,
# ansible.posix by nfs_client, system_baseline and user_management, community.proxmox by pve_lxc and pve_vm (Proxmox VE guest lifecycle).
# ansible.posix by nfs_client, system_baseline and user_management, community.proxmox by pve_lxc (Proxmox VE guest lifecycle).
# community.proxmox's modules import the Python library proxmoxer (2.3 or later) on the controller; galaxy.yml
# cannot declare a Python dependency, so the README says it and requirements-dev.txt pins it for CI.
dependencies:
+3 -3
View File
@@ -25,9 +25,9 @@ it to this repository's organisation in the Gitea registry as `<version>` and `l
publishes `<base>.N+1` when they differ. Edit `base:` by hand only for a minor or major.
*Why:* a version a person must remember to raise is a version someone forgets. *Held:*
control: the Images workflow assigns it (`next_image_version.py`, with its tests).
- **After the build pushes a new version, a second pull request moves its
`image:<version>@sha256:<digest>` pins to it:** `ci` in `lint.yml`, `build.yml` and
`gitea-release-key.yml`; `molecule-controller` and the `molecule-ubuntu*` images in `molecule.yml`. Renovate opens it within minutes: the Images run's successful
- **After the build pushes a new version, a second pull request moves the
`image:<version>@sha256:<digest>` pins in `lint.yml`, `build.yml`, `molecule.yml` and
`gitea-release-key.yml` to it.** Renovate opens it within minutes: the Images run's successful
completion starts a live Renovate run (`workflow_run` in `renovate.yml`). It changes no image
input, so it publishes nothing. A new image's first pin is a hand-made pull request, and a
major version is moved by hand. *Why:* consumers run exactly the digest a reviewer saw.
+20 -16
View File
@@ -1,6 +1,5 @@
# CI image for the Lint and Build workflows of this Collection: every tool they used to install
# on each run is baked in, so a job only checks out the code and runs. Molecule runs in the
# molecule-controller image (ADR 0003).
# CI image for the Lint, Build and Molecule workflows of this Collection: every tool they used
# to install on each run is baked in, so a job only checks out the code and runs.
#
# Built by .gitea/workflows/image.yml with kaniko (repository root as build context,
# because the pin files below are copied in) and pushed, never on pull requests, to
@@ -13,13 +12,12 @@
# - OS packages: git, shellcheck (actionlint runs it over run: blocks), the
# distribution's python3 and ca-certificates.
# - /opt/venv: requirements-dev.lock, the hashed lock of requirements-dev.txt (ansible-core, ansible-lint, pre-commit,
# antsibull-changelog, galaxy-importer, reuse, molecule, proxmoxer), on the Python of
# antsibull-changelog, galaxy-importer, reuse, molecule and its Docker driver, proxmoxer), on the Python of
# .python-version (PYTHON_VERSION below), the one the lock was resolved on and a clone's .venv uses.
# molecule is there for Lint's "Test the repository scripts" step, whose molecule tests import it; its
# Docker driver and community.docker are not: Molecule runs in the molecule-controller image.
# - /opt/collections: the collections of requirements.yml (the versions the roles are
# tested against), found through ANSIBLE_COLLECTIONS_PATH, so `ansible-lint --offline`
# resolves their modules without a mock list.
# resolves their modules without a mock list; and those of extensions/molecule/requirements.yml
# (community.docker), which the Molecule Docker driver's own playbooks call.
# - /opt/pre-commit: every hook environment of .pre-commit-config.yaml, installed by
# `pre-commit install-hooks` (gitleaks and actionlint are built from source by
# pre-commit, which downloads a Go toolchain: that is most of the time saved).
@@ -28,8 +26,8 @@
# - Python 3.11, 3.13 and PYTHON_VERSION as python<MINOR> on PATH, so that
# `ansible-test sanity` runs its compile test for them instead of skipping it.
# They come from python-build-standalone through uv, pinned by the uv version.
# - /opt/ci-pins.sha256: the checksums of requirements-dev.txt, requirements-dev.lock, requirements.yml
# and .pre-commit-config.yaml this image was built from. A job runs
# - /opt/ci-pins.sha256: the checksums of requirements-dev.txt, requirements-dev.lock, requirements.yml,
# extensions/molecule/requirements.yml and .pre-commit-config.yaml this image was built from. A job runs
# `sha256sum -c /opt/ci-pins.sha256` in its checkout; when a pull request changes a
# pin the check fails and the job installs the tools as before, until the image
# is rebuilt from main.
@@ -67,6 +65,8 @@ ENV PIP_DISABLE_PIP_VERSION_CHECK=1 \
WORKDIR /src
COPY requirements-dev.txt requirements-dev.lock requirements.yml .pre-commit-config.yaml ./
# Kept at its checkout path: its name matches the root requirements.yml.
COPY extensions/molecule/requirements.yml extensions/molecule/
# The interpreters come first: /opt/venv is built from the pinned one (PYTHON_VERSION, kept equal to
# .python-version and to the lock header by `check_image_versions.py pins`), not from the distribution's
@@ -98,11 +98,13 @@ RUN "$(echo /opt/python/cpython-${PYTHON_VERSION}.*/bin/python${PYTHON_VERSION})
&& /opt/venv/bin/python --version \
&& /opt/venv/bin/pip install --require-hashes -r requirements-dev.lock -r requirements-dev.txt
# The collections of requirements.yml. ANSIBLE_COLLECTIONS_PATH is set to the target for the
# The collections of requirements.yml and extensions/molecule/requirements.yml. ANSIBLE_COLLECTIONS_PATH is set to the target for the
# install only: a collection found anywhere else on the path would be skipped as "already
# installed" and not copied here.
RUN ANSIBLE_COLLECTIONS_PATH=/opt/collections \
/opt/venv/bin/ansible-galaxy collection install -r requirements.yml -p /opt/collections \
&& ANSIBLE_COLLECTIONS_PATH=/opt/collections \
/opt/venv/bin/ansible-galaxy collection install -r extensions/molecule/requirements.yml -p /opt/collections \
&& du -sh /opt/collections
# pre-commit needs a git repository to resolve a config. The hook repositories are
@@ -175,16 +177,16 @@ FROM os AS final
ARG PYTHON_VERSION=3.14
LABEL org.opencontainers.image.title="ci" \
org.opencontainers.image.description="CI tooling image for the mortis.kamino Ansible Collection: the Lint and Build workflows run in it, so a job only checks out the code and runs; Molecule runs in the molecule-controller image. It bakes in ansible-core, ansible-lint, pre-commit with every hook environment of the repository, antsibull-changelog, galaxy-importer, reuse, molecule (for the script tests), proxmoxer, the collections of requirements.yml, git, shellcheck, Python 3.11, 3.13 and the version of .python-version (the tools in /opt/venv run on it) next to the distribution python3 and primed ansible-test sanity virtualenvs. Pin it by tag and digest, as a job container or with docker run; it has no Node, so clone with git." \
org.opencontainers.image.description="CI tooling image for the mortis.kamino Ansible Collection: the Lint, Build and Molecule workflows run in it, so a job only checks out the code and runs. It bakes in ansible-core, ansible-lint, pre-commit with every hook environment of the repository, antsibull-changelog, galaxy-importer, reuse, molecule with its Docker driver, proxmoxer, the collections of requirements.yml and extensions/molecule/requirements.yml, git, shellcheck, Python 3.11, 3.13 and the version of .python-version (the tools in /opt/venv run on it) next to the distribution python3 and primed ansible-test sanity virtualenvs. Pin it by tag and digest, as a job container or with docker run; it has no Node, so clone with git." \
org.opencontainers.image.source="https://git.rkdr.net/mortis/kamino" \
org.opencontainers.image.url="https://git.rkdr.net/mortis/kamino" \
org.opencontainers.image.documentation="https://git.rkdr.net/mortis/kamino/src/branch/main/docs/images/ci.md" \
org.opencontainers.image.licenses="GPL-3.0-or-later" \
org.opencontainers.image.authors="Defame1297 and contributors" \
org.opencontainers.image.base.name="ubuntu:26.04" \
net.rkdr.mortis.purpose="CI tooling image for the mortis.kamino Ansible Collection: the Lint and Build workflows run in it, so a job only checks out the code and runs." \
net.rkdr.mortis.contents="Ubuntu 26.04, /opt/venv (ansible-core, ansible-lint, pre-commit, antsibull-changelog, galaxy-importer, reuse, molecule, proxmoxer), /opt/collections (community.general, ansible.posix, community.proxmox), /opt/pre-commit hook environments, ansible-test sanity venvs, python3 (distribution), python3.11, python3.13, python<PYTHON_VERSION> (the one of /opt/venv), git, shellcheck, /opt/ci-pins.sha256" \
net.rkdr.mortis.usage="Lint and Build: job container on the kamino-docker runner, git.rkdr.net/mortis/ci:version@sha256:digest with PRE_COMMIT_HOME set to /opt/pre-commit. Run sha256sum -c /opt/ci-pins.sha256 in the checkout root and install the pinned tools and collections when a pull request changed them, else use /opt/venv/bin and ANSIBLE_COLLECTIONS_PATH=/opt/collections. See the documentation label."
net.rkdr.mortis.purpose="CI tooling image for the mortis.kamino Ansible Collection: the Lint, Build and Molecule workflows run in it, so a job only checks out the code and runs." \
net.rkdr.mortis.contents="Ubuntu 26.04, /opt/venv (ansible-core, ansible-lint, pre-commit, antsibull-changelog, galaxy-importer, reuse, molecule, molecule-plugins[docker], proxmoxer), /opt/collections (community.general, ansible.posix, community.proxmox, community.docker), /opt/pre-commit hook environments, ansible-test sanity venvs, python3 (distribution), python3.11, python3.13, python<PYTHON_VERSION> (the one of /opt/venv), git, shellcheck, /opt/ci-pins.sha256" \
net.rkdr.mortis.usage="Lint and Build: job container on the kamino-docker runner, git.rkdr.net/mortis/ci:version@sha256:digest with PRE_COMMIT_HOME set to /opt/pre-commit. Molecule (host executor, kamino-molecule runner): docker run as the runner user, with the Docker socket and the checkout mounted at the same path. In both, run sha256sum -c /opt/ci-pins.sha256 in the checkout root and install the pinned tools and collections when a pull request changed them, else use /opt/venv/bin and ANSIBLE_COLLECTIONS_PATH=/opt/collections. See the documentation label."
ENV PIP_DISABLE_PIP_VERSION_CHECK=1 \
PRE_COMMIT_HOME=/opt/pre-commit \
@@ -200,14 +202,16 @@ COPY --from=build /root/.ansible/test /root/.ansible/test
# The target interpreters ansible-test looks for on PATH, and the pin record.
COPY --from=build /src/requirements-dev.txt /src/requirements-dev.lock /src/requirements.yml /src/.pre-commit-config.yaml /opt/ci-pins/
# Under its checkout path, so `sha256sum -c` in a checkout root finds it.
COPY --from=build /src/extensions/molecule/requirements.yml /opt/ci-pins/extensions/molecule/
RUN set -eu; \
for v in $(printf '%s\n' 3.11 3.13 "${PYTHON_VERSION}" | sort -u); do \
ln -sf "$(echo /opt/python/cpython-${v}.*/bin/python${v})" "/usr/local/bin/python${v}"; \
"python${v}" --version; \
done; \
cd /opt/ci-pins; \
sha256sum requirements-dev.txt requirements-dev.lock requirements.yml .pre-commit-config.yaml \
> /opt/ci-pins.sha256; \
sha256sum requirements-dev.txt requirements-dev.lock requirements.yml extensions/molecule/requirements.yml \
.pre-commit-config.yaml > /opt/ci-pins.sha256; \
ansible --version | head -n1; \
ansible-galaxy collection list; \
pre-commit --version; \
+3 -5
View File
@@ -29,10 +29,9 @@ FROM ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da0
ENV DEBIAN_FRONTEND=noninteractive
# python3 and python3-venv only bootstrap uv in the build stage; ca-certificates serve the
# install a job runs when a pull request changes a pin; git lets the selector diff the checkout.
# apt lists are removed in the same layer.
# install a job runs when a pull request changes a pin. apt lists are removed in the same layer.
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates git python3 python3-venv \
&& apt-get install -y --no-install-recommends ca-certificates python3 python3-venv \
&& rm -rf /var/lib/apt/lists/*
@@ -93,7 +92,7 @@ LABEL org.opencontainers.image.title="molecule-controller" \
org.opencontainers.image.authors="Defame1297 and contributors" \
org.opencontainers.image.base.name="ubuntu:26.04" \
net.rkdr.mortis.purpose="Molecule controller image for the mortis.kamino Ansible Collection: the Molecule workflow runs molecule in it, so a tool only Lint uses does not change it." \
net.rkdr.mortis.contents="Ubuntu 26.04, /opt/venv (ansible-core, molecule, molecule-plugins[docker]), /opt/collections (community.general, ansible.posix, community.proxmox, community.docker), python<PYTHON_VERSION> (the one of /opt/venv), python3 and git (distribution), /opt/molecule-pins.sha256" \
net.rkdr.mortis.contents="Ubuntu 26.04, /opt/venv (ansible-core, molecule, molecule-plugins[docker]), /opt/collections (community.general, ansible.posix, community.proxmox, community.docker), python<PYTHON_VERSION> (the one of /opt/venv), python3 (distribution), /opt/molecule-pins.sha256" \
net.rkdr.mortis.usage="Molecule (host executor, kamino-molecule runner): docker run as the runner user, with the Docker socket, the host Docker CLI and the checkout mounted at the same path. Run sha256sum -c /opt/molecule-pins.sha256 in the checkout root and install the pinned tools and collections when a pull request changed them, else use /opt/venv/bin and ANSIBLE_COLLECTIONS_PATH=/opt/collections. See the documentation label."
ENV PIP_DISABLE_PIP_VERSION_CHECK=1 \
@@ -123,7 +122,6 @@ RUN set -eu; \
molecule --version | grep -F "molecule ${mol}"; \
molecule drivers | grep -qw docker; \
python -c "import docker"; \
git --version; \
collections="$(ansible-galaxy collection list --format json)"; \
for c in $(sed -n 's/^ *- name: *//p' requirements.yml extensions/molecule/requirements.yml); do \
printf '%s' "$collections" | python -c "import json, sys; d = json.load(sys.stdin); sys.exit(0 if any('$c' in v for v in d.values()) else 1)" \
+3 -3
View File
@@ -79,12 +79,12 @@
},
{
"customType": "regex",
"description": "The CONTROLLER_IMAGE (molecule-controller), MOLECULE_IMAGE and MOLECULE_IMAGE_<release> values of molecule.yml are a multi-line `>-` scalar, which the github-actions manager does not read; matched here by its exact shape. Used by the pin-follow rule below.",
"description": "The CI_IMAGE, MOLECULE_IMAGE and MOLECULE_IMAGE_<release> values of molecule.yml are a multi-line `>-` scalar, which the github-actions manager does not read; matched here by its exact shape. Used by the pin-follow rule below.",
"managerFilePatterns": [
"/^\\.gitea/workflows/molecule\\.yml$/"
],
"matchStrings": [
"(?:CONTROLLER_IMAGE|MOLECULE_IMAGE(?:_[0-9]+)?):\\s*>-\\s*\\n\\s*(?<depName>git\\.rkdr\\.net/mortis/[a-z0-9._-]+):(?<currentValue>[^@\\s]+)@(?<currentDigest>sha256:[0-9a-f]{64})"
"(?:CI_IMAGE|MOLECULE_IMAGE(?:_[0-9]+)?):\\s*>-\\s*\\n\\s*(?<depName>git\\.rkdr\\.net/mortis/[a-z0-9._-]+):(?<currentValue>[^@\\s]+)@(?<currentDigest>sha256:[0-9a-f]{64})"
],
"datasourceTemplate": "docker",
"versioningTemplate": "semver"
@@ -168,7 +168,7 @@
"automerge": false
},
{
"description": "Pin follow-up for our own images (git.rkdr.net/mortis/*): moves the image:<version>@sha256:<digest> pins of lint.yml, build.yml, molecule.yml and gitea-release-key.yml to the newest published version and its digest, and automerges. The Images workflow's completion starts a Renovate run, so this pull request opens minutes after a new version is pushed. The pull request's own Lint and Build run in the new image before the merge, and scripts/check_bot_pr_diff.py allows only these pin lines. The registry lists tags and digests anonymously, so no hostRules are needed. A major version stays manual (rule above). One pull request moves every image an Images run published (ci, molecule-controller and both molecule target images), so one Molecule run tests them together. Exempt from the weekly schedule, so the pins on main catch up with a new image within minutes.",
"description": "Pin follow-up for our own images (git.rkdr.net/mortis/*): moves the image:<version>@sha256:<digest> pins of lint.yml, build.yml, molecule.yml and gitea-release-key.yml to the newest published version and its digest, and automerges. The Images workflow's completion starts a Renovate run, so this pull request opens minutes after a new version is pushed. The pull request's own Lint and Build run in the new image before the merge, and scripts/check_bot_pr_diff.py allows only these pin lines. The registry lists tags and digests anonymously, so no hostRules are needed. A major version stays manual (rule above). One pull request moves every image an Images run published (ci and both molecule images), so one Molecule run tests them together. Exempt from the weekly schedule, so the pins on main catch up with a new image within minutes.",
"matchPackageNames": [
"git.rkdr.net/mortis/**"
],
+59 -40
View File
@@ -193,9 +193,9 @@ ansible-builder==3.2.0 \
--hash=sha256:8cd8639011127aaa5046fd60e56ae753eb599061bf493eca2c6b75c54cfc6212 \
--hash=sha256:9cb948dbd221bdf6d0d48e80fa1575ca5f4336a569c05f510e2d406f01897673
# via galaxy-importer
ansible-compat==26.11.1 \
--hash=sha256:d22e0a48d8d79e727b0f56db3573b02bde2189b5bfbef067230a34c0bcbff94a \
--hash=sha256:ed9717fde1705a58678c1503e46316a36f7392229c2444d2b2f1b6de12be9f25
ansible-compat==26.11.0 \
--hash=sha256:35cbe829e0b5a9acb85d34b8d5da2eb45acaf767f6651f90e0ab2f3a96a060bb \
--hash=sha256:c06a486b39ced440f9f6fb9a99583c73d9239c94ece822a27ea2242173462dda
# via
# ansible-lint
# molecule
@@ -687,6 +687,11 @@ distro==1.9.0 \
# via
# ansible-lint
# bindep
# selinux
docker==7.2.0 \
--hash=sha256:a3f45fdeb9165e2d25d9a1d02ddf3bc70fb572cf5ebbf9b58558c22caf29b71f \
--hash=sha256:cebb93773d334f778e023a7ee352a8d6e13ab1bd3b863a4d4a59dec897df43ac
# via molecule-plugins
docutils==0.23 \
--hash=sha256:25d013af9bf23bc1c7b2b093dff4208166c53a94786c9e447808335ef1185fea \
--hash=sha256:746f5060322511280a1e50eb76846ed6bf2342984b2ac04dc42caa1a8d78799e
@@ -698,9 +703,9 @@ enrich==1.2.7 \
--hash=sha256:0a2ab0d2931dff8947012602d1234d2a3ee002d9a355b5d70be6bf5466008893 \
--hash=sha256:f29b2c8c124b4dbd7c975ab5c3568f6c7a47938ea3b7d2106c8a3bd346545e4f
# via molecule
filelock==4.3.2 \
--hash=sha256:02a8801bc6b2a80921bf3d7895c63084d53bae2a3c86783adce5ae2b89a1825b \
--hash=sha256:4f0a21c70447782453c06bb20a9863ee385ead1abaef22049af79289496851b3
filelock==4.3.0 \
--hash=sha256:143407310acf479e82d88068e3b9a6486f45fb410c0ed8729fe7359eaabeb6f1 \
--hash=sha256:f933f39f7e01249a4a49b9abab30edc6d4b874624c3de5dd0b0d137aa8adb979
# via
# ansible-lint
# apm-cli
@@ -844,9 +849,9 @@ frozenlist==1.8.0 \
# via
# aiohttp
# aiosignal
galaxy-importer==0.4.45 \
--hash=sha256:189204ab6ca8d4f1619ac8eae7bb9867088a48fc31ba13cf0d4b10ff4f4ad857 \
--hash=sha256:ec9d77f95d8e700ad0792fff0fc909e395af963dbd8aa862b1ab30c8bff6f53e
galaxy-importer==0.4.44 \
--hash=sha256:6c024fed7689f854bc8131d613a677f5929e34b01e2c9d63ac63ec69ae37004c \
--hash=sha256:c2261e6480cb71c445228233f2de906ef96fa5dc55b138a85e5e5a7c30902de7
# via -r requirements-dev.txt
gitdb==4.0.12 \
--hash=sha256:5ef71f855d191a3326fcfbc0d5da835f26b13fbcba60c32c21091c349ffdb571 \
@@ -1030,9 +1035,9 @@ llm-github-models==0.18.0 \
--hash=sha256:b0b702c563b6c2f581a707e9b809017c38f094a4d4fffc066e0b56bf209eb281 \
--hash=sha256:b778aa6fa43e53ecb3b868fcf9875bc0e760a774a1fad76ea907a269582a2043
# via apm-cli
markdown==3.11.4 \
--hash=sha256:2e30b19cead1968f391206e184ca67dfe6805c2eb8f383fb07b4dc90f8288075 \
--hash=sha256:c911a757f33d64a2578bed2d20c57e007b2aedd8a67bceabd593b31143d54ead
markdown==3.11.3 \
--hash=sha256:81eb91631dc97ad1efbc76019ef0f80fe90ca49ddf81546752d79989c3bfff3e \
--hash=sha256:e1a31a112232504d753e5c01bb8c2de90d3f0ba986b063e10770cf7695b09e73
# via galaxy-importer
markdown-it-py==4.3.0 \
--hash=sha256:7aa1511a46c39138de78d9eba92ce47e63124d8003fc98b3a351909e04239efa \
@@ -1199,9 +1204,15 @@ mdurl==0.1.2 \
--hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \
--hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba
# via markdown-it-py
molecule==26.11.1 \
--hash=sha256:34035f2852f1c0461539051ec1dd2398492c1e4f370ba507b81a781f322e4147 \
--hash=sha256:dcd147fb60bb66c060e0bf6a3eaa18f34433a18254a6f56f25ac254fb7980f64
molecule==26.11.0 \
--hash=sha256:5e48f66e97ce03ba1e9cfdf4a3667db499e960543c91bb62f530c6cd6337dd9b \
--hash=sha256:706bb3d9a34e1531cfe1cda294974aad4ccba70af3ecb2d434266e0df73b0c09
# via
# -r requirements-dev.txt
# molecule-plugins
molecule-plugins==26.11.0 \
--hash=sha256:194be2c43d950545cc699ab19f1a55b26853809e6e8c855ea1a42edacf5c7ee7 \
--hash=sha256:513808288b7027c465b124e66a2a31002c7c907b2fea9002f63ee90bb2d0ef84
# via -r requirements-dev.txt
multidict==7.2.1 \
--hash=sha256:02009b402129a73e1f3da68f48eb999afbacd29f25aef0d5052b84ff5c2786a2 \
@@ -1420,13 +1431,13 @@ nodeenv==1.12.0 \
--hash=sha256:4ea7f88339310afebc3253f2c7a91b94bacf97d73a36a5c108962abdfaca501e \
--hash=sha256:80644d65c10cc2be12e3e4b54b3367ff288c7ad24ae75c2dcc65454fc7449d4d
# via pre-commit
openai==3.60.0 \
--hash=sha256:077657587f7d2d55b943a135c3e183f87cf7dc66644caa3c0bbc2bde1fe65de9 \
--hash=sha256:476e79f256a4ce74848b7abae9f074352a69dca6e7e8987d565ee883a3b7e496
openai==3.57.0 \
--hash=sha256:5a0a89d6a542efc85e2a8cec701ca9265b795d578c777828e10fafdf80e333b6 \
--hash=sha256:f97bc74024c06ced8428b56c4a3594066709d3082779bf9d0b4b6092fbf587a8
# via llm
packaging==26.4 \
--hash=sha256:81383611a09c1bc0b08b76e0fd5829d7c6824c65b27a6aee339da133f4233ea2 \
--hash=sha256:c4b671c41ddb9bf26e543c37723610d28fb6bf7affc4da17cf048d419d2c062a
packaging==26.3 \
--hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \
--hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c
# via
# ansible-builder
# ansible-compat
@@ -1453,9 +1464,9 @@ pbr==7.1.3 \
--hash=sha256:6583e878a1d97cb135fdc509811f31b9235905cde8d4dacd3dbadf9efc45d745 \
--hash=sha256:9a4a85b84e906337708009af0b5f5cdabeeb72d4dc213c9e97974da54fd9acc5
# via bindep
platformdirs==4.14.9 \
--hash=sha256:c6b188e03ffd4dfe1bf8c4bcb47cd94711af244a9852dbff60297bd753684d5d \
--hash=sha256:d0d3a23e7ff282cfa94b77f5a22b81030dcb68ba0430f90c74f4bd8d090782ea
platformdirs==4.14.8 \
--hash=sha256:1e34af590de4d978631b751eb2202f2fee4497537a17c1720b12fcf57b331392 \
--hash=sha256:96893d686e84e9e6f358a9ea41a8de544df66dbf2ba6cda250e7dc73acf85b9b
# via
# black
# virtualenv
@@ -1795,9 +1806,9 @@ python-debian==1.1.1 \
--hash=sha256:f98ae013e8e5310e49041cc3860a7105df73af73d4ff1d8afb474770d328a6ad \
--hash=sha256:fe4fc3dc798dbf1f0ef5865e2b1b4f7cc0352b6a511b25ab7594906c64a73629
# via reuse
python-discovery==1.9.8 \
--hash=sha256:4e0c3349272923b6f58db8c5dad111b09dec9d3e2c97f9b79023f8b2e9acf7ab \
--hash=sha256:5d66dd004e6972687438a799fa0895b7a900c1b7324a525196f1826bf7cebb03
python-discovery==1.9.6 \
--hash=sha256:383aa67858d73a9585a843a37a4383c6be98e4d86a981a031328e393a6eb2632 \
--hash=sha256:93b10b90363d4151964cdeee2ec6601f3041b17fc2b253a1c3da7d6e7ddd8337
# via virtualenv
python-frontmatter==1.3.0 \
--hash=sha256:9f7dd9260bec99044219159a329f64f039087f9d1a2124c9442556f2fe6f82ec \
@@ -1958,7 +1969,9 @@ requests==2.34.2 \
# via
# apm-cli
# azure-core
# docker
# galaxy-importer
# molecule-plugins
resolvelib==1.2.1 \
--hash=sha256:7d08a2022f6e16ce405d60b68c390f054efcfd0477d4b9bd019cc941c28fad1c \
--hash=sha256:fb06b66c8da04172d9e72a21d7d06186d8919e32ae5ab5cdf5b9d920be805ac2
@@ -2126,6 +2139,10 @@ ruamel-yaml==0.19.1 \
# via
# ansible-lint
# apm-cli
selinux==0.3.0 \
--hash=sha256:2a88b337ac46ad0f06f557b2806c3df62421972f766673dd8bf26732fb75a9ea \
--hash=sha256:ecf7add45c939e9dda682c390a2cd0a845c94a4793a2cce9e8870d4ee9501f99
# via molecule-plugins
semantic-version==2.10.0 \
--hash=sha256:bdabb6d336998cbb378d4b9db3a4b56a1e3235701dc05ea2690d9a997ed5041c \
--hash=sha256:de78a3b8e0feda74cabc54aab2da702113e33ac9d9eb9d2389bcf1f58b7d9177
@@ -2148,9 +2165,9 @@ sqlite-fts4==1.0.3 \
--hash=sha256:0359edd8dea6fd73c848989e1e2b1f31a50fe5f9d7272299ff0e8dbaa62d035f \
--hash=sha256:78b05eeaf6680e9dbed8986bde011e9c086a06cb0c931b3cf7da94c214e8930c
# via sqlite-utils
sqlite-utils==4.2.2 \
--hash=sha256:5c54dc4d77260b44e8d0ccf4461c321c40ca1451dd6b6a63398ed058722aff13 \
--hash=sha256:e92aa6c2bcefa1877cbd56e8da6fe3924ca5b45954f98e7d738c49d19325fa0d
sqlite-utils==4.2.1 \
--hash=sha256:76114b6a5414714e6c70e5fa5c4781b301b590f6951b5da39c8cc60c21382ba1 \
--hash=sha256:7fbaee670713b25eceba05779b844f0895efaf680d9a226fa5ba7dfe165721c5
# via llm
subprocess-tee==0.4.2 \
--hash=sha256:21942e976715af4a19a526918adb03a8a27a8edab959f2d075b777e3d78f532d \
@@ -2166,9 +2183,9 @@ toml==0.10.2 \
--hash=sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b \
--hash=sha256:b3bda1d108d5dd99f4a20d24d9c348e91c4db7ab1b749200bded2f839ccbe68f
# via apm-cli
tomlkit==0.15.3 \
--hash=sha256:a83ce6de3b648e68dd9b50aabadad749ba823eb58b1d026f3c0a283c4767a9c1 \
--hash=sha256:b3c3020ec1a4bd469d12e31fb4da938e7f6ba758cdbec3fd9047db63120eaf81
tomlkit==0.15.2 \
--hash=sha256:05562412163a3037b94497385fb7f9204c637bc605af7a48199e41cf2272f437 \
--hash=sha256:83e32755ba1d20d9340bd069ee97e9f6232ba2346b63ffcba425de01f7e327a6
# via
# apm-cli
# reuse
@@ -2179,9 +2196,9 @@ truststore==0.10.5 \
# apm-cli
# httpcore2
# httpx2
typer==0.29.3 \
--hash=sha256:1fd37275046faecc86caa2e0e313978c10db71533fc0fe1a48f4e03a60efc23c \
--hash=sha256:8189a53bb9684dc551e0b61e71904b323214884f2eb14bfe71aa859ae980d10a
typer==0.29.2 \
--hash=sha256:b1998dc5f2c3dedafa1517a9521fa944cc4dc1fadcea085d81a3b10ebcaeb075 \
--hash=sha256:f30731f8ca758368b836b3714872e58e395cef8fcaff918c853b1969ed5274e7
# via rstcheck
typing-extensions==4.16.0 \
--hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \
@@ -2206,10 +2223,12 @@ tzdata==2026.6 \
urllib3==2.8.0 \
--hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 \
--hash=sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63
# via requests
virtualenv==21.15.14 \
--hash=sha256:6c6e7aaf88064767c75c32a9df92eaa425cee5db4cc21caf031a78d89375d57f \
--hash=sha256:816503d7826a2269abc03f7f0dd48ffd3b63db1958a7a3cbeea5a70dd7fe0ff1
# via
# docker
# requests
virtualenv==21.15.12 \
--hash=sha256:a3976f886eb6019fcb1d137b223d160adaeff524ab0ad785c729a43c31cc158c \
--hash=sha256:bbbf764388a18dee8c3532c77af7a29680cd8121911d6dcb3484335d76547323
# via pre-commit
watchdog==7.1.1 \
--hash=sha256:05e85c22dcd53f7152d1e03e785e241341d586b06a5115be7c0ea86436ccc1f6 \
+5 -6
View File
@@ -1,4 +1,4 @@
# Pinned tooling for Lint and Build, used by CI (.gitea/workflows) and locally:
# Pinned tooling for lint, build and Molecule, used by CI (.gitea/workflows) and locally:
# python3 -m venv .venv && . .venv/bin/activate && pip install --require-hashes -r requirements-dev.lock -r requirements-dev.txt
# This file holds the direct pins; requirements-dev.lock is their hashed lock (every transitive
# package too, with the sha256 of each release file) and is what gets installed; pip refuses an
@@ -10,13 +10,12 @@ ansible-core==2.22.0
ansible-lint==26.10.1
pre-commit==4.7.0
antsibull-changelog==0.38.0
galaxy-importer==0.4.45
galaxy-importer==0.4.44
reuse==6.3.0
# molecule without its Docker driver: Lint's "Test the repository scripts" step imports it in
# test_check_scenarios_load_checkout.py and test_run_molecule_scenarios.py, which skip without it.
molecule==26.11.1
molecule==26.11.0
molecule-plugins[docker]==26.11.0
# proxmoxer: the controller-side library community.proxmox's modules import (they refuse anything below 2.3),
# so lint runs where a consumer's controller would.
# so lint and Molecule run where a consumer's controller would.
proxmoxer==2.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.
+3 -3
View File
@@ -563,9 +563,9 @@ mdurl==0.1.2 \
--hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \
--hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba
# via markdown-it-py
molecule==26.11.1 \
--hash=sha256:34035f2852f1c0461539051ec1dd2398492c1e4f370ba507b81a781f322e4147 \
--hash=sha256:dcd147fb60bb66c060e0bf6a3eaa18f34433a18254a6f56f25ac254fb7980f64
molecule==26.11.0 \
--hash=sha256:5e48f66e97ce03ba1e9cfdf4a3667db499e960543c91bb62f530c6cd6337dd9b \
--hash=sha256:706bb3d9a34e1531cfe1cda294974aad4ccba70af3ecb2d434266e0df73b0c09
# via
# -r requirements-molecule.txt
# molecule-plugins
+1 -1
View File
@@ -6,6 +6,6 @@
# ansible-core equals the pin of requirements-dev.txt (check_image_versions.py pins fails otherwise), so
# Lint and Molecule judge the code with one ansible-core.
ansible-core==2.22.0
molecule==26.11.1
molecule==26.11.0
# The Docker driver, with the docker Python SDK it and the community.docker modules of its playbooks use.
molecule-plugins[docker]==26.11.0
+2 -3
View File
@@ -2,9 +2,8 @@
# Collections the roles of this Collection call (the dependencies of galaxy.yml, pinned exactly).
# galaxy.yml holds the lower bounds a consumer needs; this file holds the versions CI tests
# against. One file feeds every consumer, so they cannot drift apart:
# - the ci image (images/ci/Dockerfile) bakes it into /opt/collections for Lint;
# - the molecule-controller image (images/molecule-controller/Dockerfile) bakes it for Molecule,
# and scripts/run_molecule_in_controller.sh installs it itself when a pull request changes it;
# - the ci image (images/ci/Dockerfile) bakes it into /opt/collections for Lint and Molecule;
# - the Molecule job (.gitea/workflows/molecule.yml) installs it itself when a pull request changes it;
# - scripts/dev-setup.sh installs it into .ansible/collections for local lint.
# Renovate (renovate.json, ansible-galaxy manager) bumps these pins.
collections:
-133
View File
@@ -1,133 +0,0 @@
# pve_vm
Clones a Proxmox VE QEMU VM from a template through the Proxmox API and keeps its configuration, cloud-init settings, boot disk size and power state in line with the inputs. The configuration is updated only when drift is detected. 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) and 26.04 (resolute) guests, the platforms the molecule scenario runs on. The play runs for the VM's inventory host: the API calls run on the controller (`pve_vm_delegate`, default `localhost`), and only the cloud-init wait runs on the guest itself. The template the VM is cloned from must be a cloud-init image of one of these releases.
The guest-side cloud-init wait (`cloud-init status --wait`) is untested on both releases: the test images do not ship cloud-init.
The role targets the guests, not the Proxmox node, so it does not declare Debian trixie: the node is reached only through its API.
## Requirements and run order
- Use it by its fully qualified name, `mortis.kamino.pve_vm`, in a play over the VM hosts with `gather_facts: false`: the VM may not exist yet when the play starts.
- The controller needs the `community.proxmox` collection and the Python libraries `proxmoxer` 2.3 or later and `requests`.
- Role dependencies: none.
- `pve_vm_node` and `pve_vm_vmid` are required. `pve_vm_api_user` and `pve_vm_api_token_secret` have no usable default and are asserted non-empty before any change; `pve_vm_disk_size` too while `pve_vm_manage_disk` is true, unless `pve_vm_state` is `absent`.
- `pve_vm_api_host` defaults to the `ansible_host` of `pve_vm_node` from hostvars, so the node must then be an inventory host even when only the VM hosts are targeted. Set `pve_vm_api_host` explicitly when the node is not in the inventory.
- The VM's own `ansible_host` is the target of the SSH wait, and `inventory_hostname`, lowercased with underscores replaced by dashes, is its name in Proxmox.
- Run it before any role that configures the inside of the VM. Gate those on `pve_vm_exists` (below).
### API privileges
The API token needs, on the VM (or a pool or path above it), the template and the storage:
- `VM.Allocate`, `VM.Clone` (on the template), `VM.Audit` and `VM.Config.*` (`VM.Config.CDROM`, `VM.Config.CPU`, `VM.Config.Cloudinit`, `VM.Config.Disk`, `VM.Config.HWType`, `VM.Config.Memory`, `VM.Config.Network`, `VM.Config.Options`), and `VM.PowerMgmt` for the power state and restarts;
- `Datastore.AllocateSpace` on the storage that holds the disks;
- `SDN.Use` on the bridge or zone when `pve_vm_network` sets a network.
A token with privilege separation (the Proxmox default) gets the intersection of its own ACL and its user's: grant the role on both the user and the token.
## Role variables
| Variable | Default | Description |
|---|---|---|
| `pve_vm_node` | none (required) | Name of the Proxmox node that owns the VM. |
| `pve_vm_vmid` | none (required) | VM id; for a clone, the new id. |
| `pve_vm_state` | `present` | `present`, `started`, `stopped` or `absent`. `present` leaves the power state alone. |
| `pve_vm_allow_destroy` | `false` | Required before `absent` deletes the VM. |
| `pve_vm_clone_vmid` | none | Template id, read and asserted set only when the VM does not exist and is cloned. |
| `pve_vm_full_clone` | `true` | Full clone instead of a linked clone. |
| `pve_vm_delegate` | `localhost` | Host that runs the API module tasks. |
| `pve_vm_wait_for_guest` | `true` | Wait for SSH and cloud-init when `started`. |
| `pve_vm_agent` | `true` | QEMU guest agent. |
| `pve_vm_onboot` | `true` | Start on node boot. |
| `pve_vm_autostart` | `true` | Sent as `autostart` on update, never compared. |
| `pve_vm_memory`, `pve_vm_cores`, `pve_vm_sockets` | none | Sizing, omitted when undefined. |
| `pve_vm_network`, `pve_vm_ipconfig` | none | Mappings for `net` and `ipconfig`, see the spec. Omitted when undefined. |
| `pve_vm_nameservers` | none | List, or space or comma separated string. Omitted when undefined. |
| `pve_vm_sshkeys` | none | Cloud-init public keys, one per line. Omitted when undefined. |
| `pve_vm_ci_user` | `""` | Cloud-init user (`ciuser`). Left out of the update and of the drift check when empty. |
| `pve_vm_force_update` | `false` | Push the configuration and cloud-init settings without drift. |
| `pve_vm_manage_disk` | `true` | Grow the boot disk to `pve_vm_disk_size`. |
| `pve_vm_disk_size` | none (asserted) | Boot disk size, for example `32G`; only ever grown. |
| `pve_vm_boot_disk` | `scsi0` | Disk key whose size is read and resized. |
| `pve_vm_reboot_if_required` | `true` | Restart the VM after its boot disk was grown. |
| `pve_vm_api_user` | `""` (asserted) | API user without realm; `@<pve_vm_api_realm>` is appended. |
| `pve_vm_api_realm` | `pam` | Realm of the API user. |
| `pve_vm_api_token_id` | `<pve_vm_api_user>-token` | API token id. |
| `pve_vm_api_token_secret` | none (asserted) | API token secret, normally vaulted. No default. `no_log`. |
| `pve_vm_api_host` | `ansible_host` of `pve_vm_node`, empty without it | Proxmox API address (port 8006). |
The `pve_vm_api_*` inputs are applied through `module_defaults` inside the block that holds every API call of the role, and the REST lookup of the VM config sends the header `PVEAPIToken=<user>@<realm>!<token_id>=<secret>`, derived in `vars/main.yml`.
## Variables set by the role
- `pve_vm_exists`: the VM exists on the node.
## Tags
The input validation (`tasks/validate.yml`) carries `always`, so it runs whatever tags are selected. No other task is tagged, so only a play-level tag applies to them.
## Example play
```yaml
- name: Provision VMs
hosts: vms
gather_facts: false
roles:
- role: mortis.kamino.pve_vm
vars:
pve_vm_state: started
pve_vm_node: pve1
pve_vm_vmid: 210
pve_vm_clone_vmid: 9000
pve_vm_memory: 4096
pve_vm_cores: 2
pve_vm_disk_size: 32G
pve_vm_network:
net0:
model: virtio
bridge: vmbr0
tag: 20
pve_vm_ipconfig:
ipconfig0: "ip={{ ansible_host }}/24,gw=192.0.2.1"
pve_vm_ci_user: ubuntu
pve_vm_sshkeys: "{{ lookup('ansible.builtin.file', 'files/admin.pub') }}"
pve_vm_api_user: ansible
pve_vm_api_token_secret: "{{ vault_pve_api_token_secret }}"
- name: Configure the VMs
hosts: vms
tasks:
- name: Configure the guest
ansible.builtin.include_role:
name: mortis.kamino.user_management
when: pve_vm_exists | default(false)
```
## Tests
The `default` molecule scenario runs in CI on Ubuntu 24.04 (noble) and 26.04 (resolute), the `molecule-ubuntu2404` and `molecule-ubuntu2604` images, which stand in for the guest. It runs `check` before the converge (a fresh host) and after it. The converge includes the internal task files `validate` and `detect_drift`, with a seeded VM config in Proxmox's own forms standing in for the REST lookup.
- Positive: `validate` accepts the scenario inputs, an unmanaged disk without a size, and `absent` without a size.
- Negative: through `main`, a state outside the spec, a VM id that is not a number, a missing API user and a missing token secret; through `validate`, a missing token secret with `absent` and a managed disk without a size; through `create`, a clone without `pve_vm_clone_vmid`. Each asserts the expected message.
- Drift: `detect_drift` over seeded configs: a matching config; the cloud-init user (empty input with a different or missing live `ciuser`, a changed user, a missing `ciuser`); the SSH keys (missing, rotated, empty input); a forced update; Proxmox's other value forms; every compared dimension at once; a dropped VLAN tag.
- Static, over every task file under `tasks/` (subdirectories and nested `block`, `rescue` and `always` included): no task calling `proxmox_kvm` (as `community.proxmox.proxmox_kvm`, `community.general.proxmox_kvm`, `ansible.legacy.proxmox_kvm` or `proxmox_kvm`, by its key or through `action` or `local_action`, with its `args` merged) sends `cipassword`; no `module_defaults` entry of any task or block sets `cipassword`; exactly one such task deletes a stored `cipassword`, and it is `no_log`.
Not exercised: the API lifecycle (lookup, clone, update, the `cipassword` delete, resize, start, stop, restart and delete), as there is no Proxmox API in the scenario; and the guest-side cloud-init wait, as the test images do not ship cloud-init.
## Notes
- Idempotent: yes, as far as drift detection goes, which the scenario checks: the update runs only on drift. The API calls themselves rely on `community.proxmox`, which is not tested; the update and the `cipassword` delete report changed whenever they run.
- Check mode: `--check` is the supported preview; a play-level `check_mode: true` is not supported. `proxmox_kvm` and `proxmox_disk` have no check mode support, so under `--check` the two reads (the `proxmox_kvm` `state: current` lookup and the REST GET of the VM config) run for real with `check_mode: false`, and every write is skipped and previewed instead: `Preview VM creation` for a missing VM (nothing else runs for it), `Report configuration drift` names the drifted dimensions and a pending disk resize (changed when the update or resize would run; it also reports on a real run), `Preview deletion of the stored cloud-init password` and `Preview VM power state`. Delete and restart are skipped. Roles gated on `pve_vm_exists` therefore run in check mode against existing VMs.
- Drift is checked for name, CPU type (always `host`), memory, cores, sockets, cloud-init user, `ipconfig0`, nameservers, `onboot`, agent and `net0`. A missing `ciuser` or `sshkeys` key in the live config also counts, and so does the first run after a clone.
- Cloud-init `sshkeys` are stored URL-encoded by Proxmox and cannot be diffed. A rotated `pve_vm_sshkeys` reaches an existing VM only through other detected drift, a fresh clone or `pve_vm_force_update: true`.
- The role never sets a cloud-init password (`cipassword`): the first login is by SSH key. A `cipassword` stored on a VM is deleted on the next real run, by a `no_log` task.
- Disk: the boot disk only grows. Only the digits of `pve_vm_disk_size` are compared with the current size in GB. After a resize the VM is restarted when `pve_vm_reboot_if_required` is true.
- With `pve_vm_state: absent` and `pve_vm_allow_destroy` true the VM is stopped and deleted and the play ends for that host. Without `pve_vm_allow_destroy` the role only looks the VM up and changes nothing.
- A VM that does not exist is detected by the module's "does not exist in cluster" message. Any other lookup failure stops the run, re-raised with only the module message.
- TLS certificates of the API are not verified.
- `no_log` is set on every task that carries the API token.
-31
View File
@@ -1,31 +0,0 @@
---
pve_vm_state: present # present | started | stopped | absent
pve_vm_allow_destroy: false
pve_vm_full_clone: true
pve_vm_wait_for_guest: true
pve_vm_delegate: localhost
pve_vm_agent: true
pve_vm_onboot: true
# Sent on update only; Proxmox does not return it in the VM config, so it is never compared.
pve_vm_autostart: true
pve_vm_manage_disk: true
pve_vm_boot_disk: scsi0
# Restart the VM after its boot disk was grown.
pve_vm_reboot_if_required: true
# Cloud-init (ciuser, sshkeys) is pushed to an existing VM only on other drift, on the first run
# after a clone, or when this is true: Proxmox stores sshkeys URL-encoded, so a rotated key is not
# detected as drift.
pve_vm_force_update: false
# Cloud-init user (ciuser). Empty means not sent to Proxmox and not compared for drift.
pve_vm_ci_user: ""
# Proxmox API credentials, asserted in tasks/validate.yml before any change. The user is the bare
# name: the role appends @<pve_vm_api_realm>. The token secret, pve_vm_api_token_secret, is a secret
# input with no default, normally vaulted.
pve_vm_api_user: ""
pve_vm_api_realm: pam
pve_vm_api_token_id: "{{ pve_vm_api_user }}-token"
# The Proxmox node's address. Guarded so the default templates to '' (and the argument validation
# passes) on a host without pve_vm_node.
pve_vm_api_host: "{{ hostvars[pve_vm_node].ansible_host if pve_vm_node is defined else '' }}"
-197
View File
@@ -1,197 +0,0 @@
---
argument_specs:
main:
short_description: Manage a Proxmox VE QEMU VM cloned from a template
description:
- >-
Looks the VM up through the Proxmox API, deletes it when C(pve_vm_state) is absent and C(pve_vm_allow_destroy) is
true, otherwise clones it from the template C(pve_vm_clone_vmid) when it does not exist, compares the live
configuration with the desired one, updates it only on drift, grows the boot disk, applies the power state
and waits for SSH and cloud-init when the VM is started.
- >-
Every API call is delegated to C(pve_vm_delegate) (the REST lookup of the config to localhost) and authenticates
with C(pve_vm_api_user) (bare user name, C(@<pve_vm_api_realm>) is appended), C(pve_vm_api_token_id),
C(pve_vm_api_token_secret) and C(pve_vm_api_host), applied through C(module_defaults), and with the header
C(PVEAPIToken=<user>@<realm>!<token_id>=<secret>) for the REST lookup, which the role derives from them in
C(vars/main.yml) (internal, not an input). The user and the token secret have no usable default: they are
asserted non-empty in the input validation, before any change. C(community.proxmox) and, on the controller,
the Python libraries C(proxmoxer) 2.3 or later and C(requests) must be installed. TLS certificates are not
verified.
- >-
Also reads C(ansible_host) (SSH wait), C(inventory_hostname) (the VM name, lowercased with underscores replaced by
dashes) and C(ansible_check_mode). The role sets the fact C(pve_vm_exists) for later roles and plays.
- >-
Cloud-init sets C(ciuser) from C(pve_vm_ci_user); an empty user is left out of the update and not compared for
drift. The role never sets a cloud-init password (C(cipassword)) and deletes one stored on the VM on a real run.
options:
pve_vm_node:
type: str
required: true
description:
- >-
Name of the Proxmox node that owns the VM. When it is also an inventory host, its C(ansible_host) is the
default of C(pve_vm_api_host).
pve_vm_vmid:
type: int
required: true
description:
- VM id on the Proxmox node. For a clone it is the new id.
pve_vm_state:
type: str
default: present
choices: [present, started, stopped, absent]
description:
- >-
C(present) keeps the VM configured without touching its power state. C(started) and C(stopped) also apply the
power state, and C(started) additionally waits for SSH and cloud-init when C(pve_vm_wait_for_guest) is true.
C(absent) deletes the VM, but only when C(pve_vm_allow_destroy) is true. Without it the role only looks the
VM up and changes nothing, because creation, disk detection, update and power state are gated on a state
other than C(absent).
pve_vm_allow_destroy:
type: bool
default: false
description:
- Safety switch required before C(pve_vm_state=absent) deletes the VM.
pve_vm_clone_vmid:
type: raw
description:
- >-
Template VM id to clone. Only read when the VM does not exist and the play is not in check mode. The type is
not fixed, so it can be given as a Jinja expression that resolves to the id.
pve_vm_full_clone:
type: bool
default: true
description:
- Full clone instead of a linked clone.
pve_vm_delegate:
type: str
default: localhost
description:
- Host that executes the Proxmox API module tasks. The REST lookup of the VM config always runs on localhost.
pve_vm_wait_for_guest:
type: bool
default: true
description:
- >-
When true and C(pve_vm_state) is started, wait for SSH on port 22 of C(ansible_host) and then for
C(cloud-init status --wait) on the guest.
pve_vm_agent:
type: bool
default: true
description:
- Enable the QEMU guest agent. Compared with the live config for drift.
pve_vm_onboot:
type: bool
default: true
description:
- Start the VM when the node boots. Compared with the live config for drift.
pve_vm_autostart:
type: bool
default: true
description:
- >-
Passed to the module as C(autostart) on update. Not compared for drift, because Proxmox does not return it in
the VM config.
pve_vm_memory:
type: raw
description:
- Memory in MB. Omitted from the update when undefined. Compared as an integer for drift.
pve_vm_cores:
type: raw
description:
- CPU cores. Omitted from the update when undefined. Compared as an integer for drift.
pve_vm_sockets:
type: raw
description:
- CPU sockets. Omitted from the update when undefined. Compared as an integer for drift.
pve_vm_network:
type: raw
description:
- >-
Mapping passed to the module as C(net), for example C(net0) with C(model), C(bridge), C(tag) and C(firewall).
Omitted when undefined. Only C(net0) is compared for drift.
pve_vm_ipconfig:
type: raw
description:
- >-
Mapping passed to the module as C(ipconfig), for example C(ipconfig0) with a string such as
C(ip=<address>/24,gw=<gateway>). Omitted when undefined. Only C(ipconfig0) is compared for drift, token order
ignored.
pve_vm_nameservers:
type: raw
description:
- Nameservers as a list, or a space or comma separated string. Omitted when undefined.
pve_vm_sshkeys:
type: str
description:
- >-
Public keys written to the cloud-init C(sshkeys) field, one per line. Omitted when undefined. Proxmox stores
them URL-encoded, so a change is not detected as drift and is only applied on a fresh clone, on other drift
or with C(pve_vm_force_update).
pve_vm_ci_user:
type: str
default: ""
description:
- >-
Cloud-init user (C(ciuser)). Left out of the update and not compared for drift when empty. Compared with the
live C(ciuser) otherwise.
pve_vm_force_update:
type: bool
default: false
description:
- Push cloud-init settings (user, sshkeys) and the whole configuration even without detected drift.
pve_vm_manage_disk:
type: bool
default: true
description:
- >-
Grow the boot disk to C(pve_vm_disk_size). While true, C(pve_vm_disk_size) must be set; the input validation
asserts it unless C(pve_vm_state) is absent.
pve_vm_disk_size:
type: raw
description:
- >-
Desired boot disk size, for example C(32G). Only the digits are compared with the current size in GB, and the
disk is only ever grown.
pve_vm_boot_disk:
type: str
default: scsi0
description:
- Disk key whose size is read and resized.
pve_vm_reboot_if_required:
type: bool
default: true
description:
- Restart the VM after its boot disk was grown.
pve_vm_api_user:
type: str
default: ""
description:
- >-
Proxmox API user, the bare name without realm (C(@<pve_vm_api_realm>) is appended). Required: the role
asserts it is non-empty before any change.
pve_vm_api_realm:
type: str
default: pam
description:
- Authentication realm of C(pve_vm_api_user), appended as C(@<realm>) in C(module_defaults) and in the REST header.
pve_vm_api_token_id:
type: str
description:
- >-
API token id, without the user part. Role default C(<pve_vm_api_user>-token), a Jinja expression in
C(defaults/main.yml), so it is not repeated here.
pve_vm_api_token_secret:
type: str
no_log: true
description:
- >-
API token secret, normally vaulted. No default. Required: the role asserts it is set and non-empty before
any change. Every task that carries it is C(no_log).
pve_vm_api_host:
type: str
description:
- >-
Address of the Proxmox API (port 8006). Role default the C(ansible_host) of C(pve_vm_node) from hostvars, or
empty when C(pve_vm_node) is undefined; a Jinja expression in C(defaults/main.yml), so it is not repeated
here. Set it explicitly when the node is not an inventory host.
-19
View File
@@ -1,19 +0,0 @@
---
galaxy_info:
role_name: pve_vm
namespace: mortis
author: Defame1297
license: GPL-3.0-or-later
description: Clone, configure, resize, start, stop and delete Proxmox VE QEMU VMs through the Proxmox API, with cloud-init settings and drift detection.
min_ansible_version: "2.22"
platforms:
- name: Ubuntu
versions:
- noble
- resolute
galaxy_tags:
- proxmox
- vm
- cloudinit
- provisioning
dependencies: []
@@ -1,30 +0,0 @@
---
# The validation and the drift detection only: main.yml would also call the Proxmox API to look
# the VM up and fetch its config, which the scenario does not exercise (README, Tests). The fetched
# config is seeded instead, as the fact detect_disk.yml sets from the REST lookup.
- name: Converge
hosts: all
gather_facts: false
tasks:
- name: Validate the inputs
ansible.builtin.include_role:
name: mortis.kamino.pve_vm
tasks_from: validate
vars:
pve_vm_disk_size: 32G
- name: Seed the live VM config the REST lookup would return
ansible.builtin.set_fact:
__pve_vm_config: "{{ pve_vm_test_config }}"
- name: Detect configuration drift
ansible.builtin.include_role:
name: mortis.kamino.pve_vm
tasks_from: detect_drift
- name: Assert the seeded config matches the inputs
ansible.builtin.assert:
that:
- not (__pve_vm_needs_update | bool)
fail_msg: The seeded config, which matches every input, was reported as drift
quiet: true
-107
View File
@@ -1,107 +0,0 @@
---
# Runs on the repository's own runner (label kamino-molecule), in the molecule-ubuntu2404
# (MOLECULE_IMAGE) and molecule-ubuntu2604 (MOLECULE_IMAGE_2604) images, pinned in
# .gitea/workflows/molecule.yml. The containers stand in for the guest: the role's input
# validation and its drift detection over a seeded VM config run against them. Nothing calls the
# Proxmox API (README, Tests). The containers run systemd as PID 1 with a writable cgroup; no
# privileged mode.
driver:
name: docker
platforms:
- name: ${KAMINO_RUN_ID:-local}-pve-vm-instance
labels:
net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}"
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
- name: ${KAMINO_RUN_ID:-local}-pve-vm-2604-instance
labels:
net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}"
image: ${MOLECULE_IMAGE_2604}
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 the converge, the drift cases and the negative tests in
# verify.yml start from the same valid input, which matches the seeded VM config of converge.yml.
inventory:
group_vars:
all:
pve_vm_node: pve-node
pve_vm_vmid: 9200
# The node is not an inventory host, from which the role defaults the API address;
# argument validation templates that default, so main would fail on it instead.
pve_vm_api_host: 192.0.2.1
pve_vm_api_user: molecule
pve_vm_api_token_secret: not-a-secret
# pve_vm_disk_size is set where a case needs it, so the refusal case can leave it undefined.
pve_vm_state: started
pve_vm_memory: 2048
pve_vm_cores: 2
pve_vm_sockets: 1
pve_vm_ci_user: ubuntu
pve_vm_sshkeys: ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMoleculeTestKeyNotARealKey molecule
pve_vm_network:
net0:
model: virtio
bridge: vmbr0
tag: 20
firewall: true
pve_vm_ipconfig:
ipconfig0: ip=192.0.2.30/24,gw=192.0.2.1
pve_vm_nameservers:
- 192.0.2.53
- 198.51.100.53
# The live config the REST lookup would return, in Proxmox's own forms: agent with flags,
# ipconfig0 tokens reordered, sshkeys URL-encoded, nameservers space-separated.
pve_vm_test_config:
name: "{{ inventory_hostname | lower | replace('_', '-') }}"
cpu: host
memory: 2048
cores: 2
sockets: 1
ciuser: ubuntu
sshkeys: ssh-ed25519%20AAAAC3NzaC1lZDI1NTE5AAAAIMoleculeTestKeyNotARealKey%20molecule%0A
ipconfig0: gw=192.0.2.1,ip=192.0.2.30/24
nameserver: 192.0.2.53 198.51.100.53
onboot: 1
agent: fstrim_cloned_disks=1,enabled=1
net0: virtio=BC:24:11:00:00:01,bridge=vmbr0,firewall=1,tag=20
scsi0: local-lvm:vm-9200-disk-0,size=32G
verifier:
name: ansible
scenario:
# molecule's default sequence minus both destroys (scripts/run_molecule_scenarios.sh removes the
# containers as soon as this scenario ends; after a local run, run `molecule destroy` yourself),
# plus a check before the converge (fresh host) and one after it (converged host).
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- check
- converge
- check
- idempotence
- side_effect
- verify
- cleanup
@@ -1,24 +0,0 @@
---
# One drift case: seeds the live VM config the REST lookup would return, runs the role's drift
# detection with the inputs the caller sets on the include, and asserts each expected drift fact.
# Input: pve_vm_test_case (name, config, expect: a mapping of drift dimension to true or false,
# needs_update for the combined result).
- name: "Seed the live VM config, case {{ pve_vm_test_case.name }}"
ansible.builtin.set_fact:
__pve_vm_config: "{{ pve_vm_test_case.config }}"
- name: "Detect configuration drift, case {{ pve_vm_test_case.name }}"
ansible.builtin.include_role:
name: mortis.kamino.pve_vm
tasks_from: detect_drift
- name: "Assert the drift facts, case {{ pve_vm_test_case.name }}"
ansible.builtin.assert:
that: (lookup('ansible.builtin.vars', pve_vm_test_fact) | bool) == (item.value | bool)
fail_msg: "{{ pve_vm_test_fact }} is {{ lookup('ansible.builtin.vars', pve_vm_test_fact) }}, expected {{ item.value }}"
quiet: true
vars:
pve_vm_test_fact: "{{ '__pve_vm_needs_update' if item.key == 'needs_update' else '__pve_vm_drift_' ~ item.key }}"
loop: "{{ pve_vm_test_case.expect | dict2items }}"
loop_control:
label: "{{ item.key }}"
@@ -1,22 +0,0 @@
---
# One failing run: includes the role's task file named by the case, with the inputs the caller
# sets on the include, and asserts that the expected message, not something else, stopped it.
# Input: pve_vm_test_case (name, tasks_from, expect).
- name: "Run the role, case {{ pve_vm_test_case.name }}"
block:
- name: "Include the role, case {{ pve_vm_test_case.name }}"
ansible.builtin.include_role:
name: mortis.kamino.pve_vm
tasks_from: "{{ pve_vm_test_case.tasks_from }}"
# 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 {{ pve_vm_test_case.name }}"
ansible.builtin.fail:
msg: The role accepted the input
rescue:
- name: "The expected failure stopped the run, case {{ pve_vm_test_case.name }}"
ansible.builtin.assert:
that: pve_vm_test_case.expect in (ansible_failed_result.msg | default(''))
fail_msg: "Expected '{{ pve_vm_test_case.expect }}', got: {{ ansible_failed_result.msg | default('') }}"
quiet: true
@@ -1,15 +0,0 @@
---
# One level of the static check's flattening: moves the pending tasks into pve_vm_test_tasks and
# makes their block, rescue and always lists the next pending ones, then recurses until none is left.
# Both facts are templated from the values before this task.
- name: Flatten one level of blocks
ansible.builtin.set_fact:
pve_vm_test_tasks: "{{ [pve_vm_test_tasks, pve_vm_test_pending] | flatten(levels=1) }}"
pve_vm_test_pending: >-
{{ [pve_vm_test_pending | map(attribute='block', default=[]) | list,
pve_vm_test_pending | map(attribute='rescue', default=[]) | list,
pve_vm_test_pending | map(attribute='always', default=[]) | list] | flatten(levels=2) }}
- name: Flatten the next level
ansible.builtin.include_tasks: flatten_tasks.yml
when: pve_vm_test_pending | length > 0
-323
View File
@@ -1,323 +0,0 @@
---
# The refusal cases run first: each fails in the input validation, before any API call.
- name: Refuse invalid input
hosts: all
gather_facts: false
tasks:
- name: Refuse a state outside the argument spec choices
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
pve_vm_state: running
pve_vm_test_case:
name: state-choice
tasks_from: main
expect: pve_vm_state must be one of
- name: Refuse a run without an API user
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
pve_vm_api_user: ""
pve_vm_test_case:
name: no-api-user
tasks_from: main
expect: The Proxmox API calls need pve_vm_api_user
- name: Refuse a run without an API token secret
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
pve_vm_api_token_secret: ""
pve_vm_test_case:
name: no-token-secret
tasks_from: main
expect: The Proxmox API calls need pve_vm_api_user
- name: Refuse a deletion without an API token secret
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
pve_vm_state: absent
pve_vm_api_token_secret: ""
pve_vm_test_case:
name: absent-no-token-secret
tasks_from: validate
expect: The Proxmox API calls need pve_vm_api_user
- name: Refuse a managed disk without a size
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
pve_vm_test_case:
name: no-disk-size
tasks_from: validate
expect: pve_vm_disk_size (for example 32G) must be set
- name: Refuse a VM id that is not a number
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
pve_vm_vmid: not-a-number
pve_vm_test_case:
name: vmid-type
tasks_from: main
expect: pve_vm_vmid
# create.yml is reached only after the API lookup found no VM; its assert precedes the clone.
- name: Refuse a clone without a template id
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
pve_vm_test_case:
name: no-clone-vmid
tasks_from: create
expect: which needs pve_vm_clone_vmid
- name: Accept valid input
hosts: all
gather_facts: false
tasks:
- name: Accept an unmanaged disk without a size
ansible.builtin.include_role:
name: mortis.kamino.pve_vm
tasks_from: validate
vars:
pve_vm_manage_disk: false
- name: Accept a deletion without a disk size
ansible.builtin.include_role:
name: mortis.kamino.pve_vm
tasks_from: validate
vars:
pve_vm_state: absent
- name: Detect drift on a seeded VM config
hosts: all
gather_facts: false
vars:
pve_vm_test_no_drift:
forced: false
missing_keys: false
name: false
cpu: false
resources: false
ciuser: false
ipconfig: false
nameservers: false
onboot: false
agent: false
network: false
needs_update: false
tasks:
- name: Report no drift when the live config matches
ansible.builtin.include_tasks: tasks/drift_case.yml
vars:
pve_vm_test_case:
name: match
config: "{{ pve_vm_test_config }}"
expect: "{{ pve_vm_test_no_drift }}"
- name: Ignore the live ciuser while pve_vm_ci_user is empty
ansible.builtin.include_tasks: tasks/drift_case.yml
vars:
pve_vm_ci_user: ""
pve_vm_test_case:
name: ciuser-empty
config: "{{ pve_vm_test_config | combine({'ciuser': 'someone-else'}) }}"
expect: "{{ pve_vm_test_no_drift }}"
- name: Ignore a missing live ciuser while pve_vm_ci_user is empty
ansible.builtin.include_tasks: tasks/drift_case.yml
vars:
pve_vm_ci_user: ""
pve_vm_test_case:
name: ciuser-empty-unset
config: "{{ pve_vm_test_config | dict2items | rejectattr('key', 'eq', 'ciuser') | items2dict }}"
expect: "{{ pve_vm_test_no_drift }}"
- name: Report a live ciuser other than pve_vm_ci_user
ansible.builtin.include_tasks: tasks/drift_case.yml
vars:
pve_vm_ci_user: admin
pve_vm_test_case:
name: ciuser-changed
config: "{{ pve_vm_test_config }}"
expect: "{{ pve_vm_test_no_drift | combine({'ciuser': true, 'needs_update': true}) }}"
- name: Report a live config without ciuser
ansible.builtin.include_tasks: tasks/drift_case.yml
vars:
pve_vm_test_case:
name: ciuser-missing
config: "{{ pve_vm_test_config | dict2items | rejectattr('key', 'eq', 'ciuser') | items2dict }}"
expect: "{{ pve_vm_test_no_drift | combine({'missing_keys': true, 'ciuser': true, 'needs_update': true}) }}"
- name: Report a live config without sshkeys
ansible.builtin.include_tasks: tasks/drift_case.yml
vars:
pve_vm_test_case:
name: sshkeys-missing
config: "{{ pve_vm_test_config | dict2items | rejectattr('key', 'eq', 'sshkeys') | items2dict }}"
expect: "{{ pve_vm_test_no_drift | combine({'missing_keys': true, 'needs_update': true}) }}"
# Proxmox stores sshkeys URL-encoded, so a rotated key is not drift; pve_vm_force_update pushes it.
- name: Report no drift for rotated sshkeys
ansible.builtin.include_tasks: tasks/drift_case.yml
vars:
pve_vm_sshkeys: ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIRotatedTestKeyNotARealKey molecule
pve_vm_test_case:
name: sshkeys-rotated
config: "{{ pve_vm_test_config }}"
expect: "{{ pve_vm_test_no_drift }}"
- name: Expect no sshkeys in the live config while pve_vm_sshkeys is empty
ansible.builtin.include_tasks: tasks/drift_case.yml
vars:
pve_vm_sshkeys: ""
pve_vm_test_case:
name: sshkeys-empty
config: "{{ pve_vm_test_config | dict2items | rejectattr('key', 'eq', 'sshkeys') | items2dict }}"
expect: "{{ pve_vm_test_no_drift }}"
- name: Report forced drift with pve_vm_force_update
ansible.builtin.include_tasks: tasks/drift_case.yml
vars:
pve_vm_force_update: true
pve_vm_test_case:
name: forced
config: "{{ pve_vm_test_config }}"
expect: "{{ pve_vm_test_no_drift | combine({'forced': true, 'needs_update': true}) }}"
- name: Read Proxmox's other forms as no drift
ansible.builtin.include_tasks: tasks/drift_case.yml
vars:
pve_vm_nameservers: 192.0.2.53,198.51.100.53
pve_vm_test_case:
name: other-forms
config: "{{ pve_vm_test_config | combine({'cpu': 'cputype=host,flags=+aes', 'agent': '1'}) }}"
expect: "{{ pve_vm_test_no_drift }}"
- name: Report drift in each compared dimension
ansible.builtin.include_tasks: tasks/drift_case.yml
vars:
pve_vm_test_case:
name: all-dimensions
config: >-
{{ pve_vm_test_config | combine({'name': 'other-name', 'cpu': 'kvm64', 'memory': 1024,
'ipconfig0': 'ip=192.0.2.31/24,gw=192.0.2.1', 'nameserver': '192.0.2.53', 'onboot': 0,
'agent': 'enabled=0', 'net0': 'virtio=BC:24:11:00:00:01,bridge=vmbr1,tag=20'}) }}
expect:
forced: false
missing_keys: false
name: true
cpu: true
resources: true
ciuser: false
ipconfig: true
nameservers: true
onboot: true
agent: true
network: true
needs_update: true
- name: Report a live VLAN tag that the inputs drop
ansible.builtin.include_tasks: tasks/drift_case.yml
vars:
pve_vm_network:
net0:
model: virtio
bridge: vmbr0
firewall: true
pve_vm_test_case:
name: tag-dropped
config: "{{ pve_vm_test_config }}"
expect: "{{ pve_vm_test_no_drift | combine({'network': true, 'needs_update': true}) }}"
# Static: the role must never send a cloud-init password, and its delete of a stored one must not
# log the task, so these read the role's own task files on the controller.
- name: Verify the role's cloud-init password handling
hosts: localhost
gather_facts: false
vars:
pve_vm_test_task_dir: "{{ (playbook_dir ~ '/../../tasks') | realpath }}"
# Every name a task can call the module by.
pve_vm_test_kvm_names:
- community.proxmox.proxmox_kvm
- community.general.proxmox_kvm
- ansible.legacy.proxmox_kvm
- proxmox_kvm
tasks:
- name: Find the role's task files, subdirectories included
ansible.builtin.find:
paths: "{{ pve_vm_test_task_dir }}"
patterns: ["*.yml", "*.yaml"]
recurse: true
register: pve_vm_test_files
- name: Read the role's task files
ansible.builtin.set_fact:
pve_vm_test_pending: >-
{{ [pve_vm_test_pending | default([]),
lookup('ansible.builtin.file', item) | from_yaml] | flatten(levels=1) }}
loop: "{{ pve_vm_test_files.files | map(attribute='path') | sort }}"
- name: Start the flattened task list
ansible.builtin.set_fact:
pve_vm_test_tasks: []
# Recurses through block, rescue and always to any depth.
- name: Flatten the blocks
ansible.builtin.include_tasks: tasks/flatten_tasks.yml
# A task calls the module by its key, or through action or local_action, either a mapping
# with module or a string that starts with the module name. Its args are merged in.
- name: Summarise each proxmox_kvm task
ansible.builtin.set_fact:
pve_vm_test_kvm: >-
{{ pve_vm_test_kvm | default([]) + [{
'name': item.name | default('(unnamed)'),
'sends': ('cipassword' in pve_vm_test_args)
or (pve_vm_test_raw is string and 'cipassword=' in pve_vm_test_raw),
'deletes': ('cipassword' in (pve_vm_test_args.delete | default('') | string).split(','))
or (pve_vm_test_raw is string and pve_vm_test_raw is search('delete=\\S*cipassword')),
'no_log': item.no_log | default(false) | bool,
}] }}
vars:
pve_vm_test_key: "{{ pve_vm_test_kvm_names | select('in', item) | first | default('') }}"
pve_vm_test_action: "{{ item.action | default(item.local_action | default('')) }}"
pve_vm_test_action_kvm: >-
{{ (pve_vm_test_action is mapping and pve_vm_test_action.module | default('') in pve_vm_test_kvm_names)
or (pve_vm_test_action is string and (pve_vm_test_action.split() | first | default('')) in pve_vm_test_kvm_names) }}
pve_vm_test_raw: >-
{{ item[pve_vm_test_key] if pve_vm_test_key
else (pve_vm_test_action | dict2items | rejectattr('key', 'eq', 'module') | items2dict
if pve_vm_test_action is mapping else pve_vm_test_action) }}
pve_vm_test_args: >-
{{ (pve_vm_test_raw if pve_vm_test_raw is mapping else {}) | combine(item.args | default({})) }}
loop: "{{ pve_vm_test_tasks }}"
loop_control:
label: "{{ item.name | default('(unnamed)') }}"
when: pve_vm_test_key | length > 0 or pve_vm_test_action_kvm | bool
- name: Assert no proxmox_kvm task sends cipassword
ansible.builtin.assert:
that:
- pve_vm_test_kvm | default([]) | length > 0
- pve_vm_test_kvm | selectattr('sends') | list | length == 0
fail_msg: "proxmox_kvm tasks sending cipassword: {{ pve_vm_test_kvm | default([]) | selectattr('sends') | map(attribute='name') | list }}"
quiet: true
# Any module, any spelling or group: no default the role sets may carry cipassword.
- name: Assert no module_defaults sets cipassword
ansible.builtin.assert:
that:
- >-
[item.module_defaults] | flatten(levels=1) | map('dict2items') | flatten(levels=1)
| map(attribute='value') | select('contains', 'cipassword') | list | length == 0
fail_msg: "module_defaults with cipassword on '{{ item.name | default('(unnamed)') }}'"
quiet: true
loop: "{{ pve_vm_test_tasks | selectattr('module_defaults', 'defined') | list }}"
loop_control:
label: "{{ item.name | default('(unnamed)') }}"
- name: Assert the stored cipassword is deleted by one no_log task
ansible.builtin.assert:
that:
- pve_vm_test_kvm | selectattr('deletes') | list | length == 1
- pve_vm_test_kvm | selectattr('deletes') | selectattr('no_log') | list | length == 1
fail_msg: "Tasks deleting cipassword: {{ pve_vm_test_kvm | selectattr('deletes') | list }}"
quiet: true
-29
View File
@@ -1,29 +0,0 @@
---
# Here, not in validate.yml: whether a clone happens is known only after the API lookup.
- name: Assert the template to clone is set
ansible.builtin.assert:
that:
- pve_vm_clone_vmid is defined
fail_msg: >-
VM {{ pve_vm_vmid }} does not exist on {{ pve_vm_node }}, so it is cloned, which needs
pve_vm_clone_vmid, the VM id of the template. Set it, or create the VM by other means.
quiet: true
- name: Clone VM from template
no_log: true # carries the API token secret
delegate_to: "{{ pve_vm_delegate }}"
community.proxmox.proxmox_kvm:
node: "{{ pve_vm_node }}"
clone: template
vmid: "{{ pve_vm_clone_vmid }}"
newid: "{{ pve_vm_vmid }}"
name: "{{ inventory_hostname | lower | replace('_', '-') }}"
full: "{{ pve_vm_full_clone }}"
timeout: 600
state: present
register: __pve_vm_clone
- name: Record that the VM was just cloned
ansible.builtin.set_fact:
# Forces one cloud-init update (ciuser, sshkeys) in update.yml.
__pve_vm_created: "{{ __pve_vm_clone is changed }}"
-23
View File
@@ -1,23 +0,0 @@
---
- name: Stop VM before deletion (if running)
no_log: true # defence in depth: the module already masks the API token secret
delegate_to: "{{ pve_vm_delegate }}"
community.proxmox.proxmox_kvm:
node: "{{ pve_vm_node }}"
vmid: "{{ pve_vm_vmid }}"
state: stopped
when:
- pve_vm_exists
- not ansible_check_mode
- name: Delete VM
no_log: true # defence in depth: the module already masks the API token secret
delegate_to: "{{ pve_vm_delegate }}"
community.proxmox.proxmox_kvm:
node: "{{ pve_vm_node }}"
vmid: "{{ pve_vm_vmid }}"
state: absent
when:
- pve_vm_exists
- not ansible_check_mode
register: __pve_vm_delete
-37
View File
@@ -1,37 +0,0 @@
---
# no_log hides the whole failure of the lookup below, so the operator would only see "output hidden
# due to no_log". The rescue re-raises just the module's msg, which is safe to show: the module
# masks the token secret in everything it returns (its invocation echo is not used here).
- name: Look up the VM
block:
- name: Check if VM exists
no_log: true # defence in depth: the module already masks the API token secret
delegate_to: "{{ pve_vm_delegate }}"
community.proxmox.proxmox_kvm:
node: "{{ pve_vm_node }}"
vmid: "{{ pve_vm_vmid }}"
state: current
register: __pve_vm_info
# proxmox_kvm declares no check mode support, so --check would skip this lookup, leave
# pve_vm_exists false and skip everything after it. state=current only reads (GET of the VM
# and its status), so it runs for real under --check as well.
check_mode: false
# An absent VM is an expected answer here: for state=current the module fails with
# "VM with vmid <id> does not exist in cluster". Any other failure (API, auth, network) is
# real and must stop the run instead of being read as "VM absent", which would send
# create.yml after an existing VM.
failed_when:
- __pve_vm_info.failed | default(false)
- "'does not exist in cluster' not in (__pve_vm_info.msg | default(''))"
changed_when: false
rescue:
- name: Fail with the module message
ansible.builtin.fail:
msg: >-
Looking up VM {{ pve_vm_vmid }} on {{ pve_vm_node }} failed:
{{ ansible_failed_result.msg | default('no message') }}
- name: Set VM existence fact
ansible.builtin.set_fact:
pve_vm_exists: >-
{{ __pve_vm_info.vmid is defined or __pve_vm_info.status is defined }}
-47
View File
@@ -1,47 +0,0 @@
---
- name: Get current VM config via REST API
no_log: true # Authorization header carries the API token
delegate_to: localhost
ansible.builtin.uri:
url: "https://{{ pve_vm_api_host }}:8006/api2/json/nodes/{{ pve_vm_node }}/qemu/{{ pve_vm_vmid }}/config"
method: GET
headers:
Authorization: "{{ __pve_vm_api_auth_header }}"
register: __pve_vm_current_config
# uri has no check mode support; this is a GET, so it also runs under --check and drift
# detection sees the live config.
check_mode: false
- name: Set fact to the actual config dict
no_log: true # the config may hold a stored cipassword (update.yml deletes it)
ansible.builtin.set_fact:
__pve_vm_config: "{{ __pve_vm_current_config.json.data }}"
- name: Extract current disk string
ansible.builtin.set_fact:
__pve_vm_disk_string: "{{ __pve_vm_config[pve_vm_boot_disk] | default('') }}"
- name: Extract current disk number and unit properly
ansible.builtin.set_fact:
__pve_vm_disk_parts: "{{ __pve_vm_disk_string | regex_findall('size=(\\d+)([GM])') | first | default(['0', 'G']) | list }}"
- name: Extract current disk number
ansible.builtin.set_fact:
__pve_vm_current_disk_size_number: "{{ __pve_vm_disk_parts[0] | int }}"
__pve_vm_current_disk_size_unit: "{{ __pve_vm_disk_parts[1] }}"
- name: Convert disk size to GB
ansible.builtin.set_fact:
__pve_vm_current_disk: >-
{{
__pve_vm_current_disk_size_number if __pve_vm_current_disk_size_unit == 'G'
else (__pve_vm_current_disk_size_number / 1024)
}}
- name: Determine if disk resize is needed
ansible.builtin.set_fact:
__pve_vm_resize_disk: "{{ pve_vm_disk_size | regex_replace('[^0-9]', '') | int > __pve_vm_current_disk | int }}"
when:
- pve_vm_manage_disk | bool
- pve_vm_disk_size is defined
- pve_vm_exists
-97
View File
@@ -1,97 +0,0 @@
---
# community.proxmox.proxmox_kvm with `update: true` reports changed on every run: it does not diff
# against the live config. Compare the config already fetched in detect_disk.yml with the desired
# values and only call the module on real drift or while cloud-init is still unconfigured (first
# run after a clone, when ciuser and sshkeys have to be applied once). Proxmox stores sshkeys
# URL-encoded, so a change is not diffed: pve_vm_force_update pushes it to an existing VM.
- name: Normalise current QEMU guest agent setting
ansible.builtin.set_fact:
# PVE returns "1", "enabled=1" or e.g. "fstrim_cloned_disks=1,enabled=1"; enabled=1 may sit
# in any position.
__pve_vm_agent_current: >-
{{
'1' if ((__pve_vm_config.agent | default('0') | string).split(',')
| select('in', ['1', 'enabled=1']) | list | length > 0)
else '0'
}}
- name: Normalise desired and current values for drift comparison
ansible.builtin.set_fact:
# ciuser and sshkeys are only expected in the current config when the role sets them.
__pve_vm_required_config_keys: >-
{{
(['ciuser'] if (pve_vm_ci_user | string | length > 0) else [])
+ (['sshkeys'] if (pve_vm_sshkeys | default('') | string | length > 0) else [])
}}
# PVE returns nameserver space-separated; accept a list or a comma-separated string as well.
__pve_vm_nameservers_desired: >-
{{
((pve_vm_nameservers | join(' '))
if (pve_vm_nameservers | default('') is not string and pve_vm_nameservers | default('') is iterable)
else (pve_vm_nameservers | default('') | string))
| replace(',', ' ') | split | join(' ')
}}
# ipconfig0 tokens can come back from PVE in a different order.
__pve_vm_ipconfig0_current: "{{ (__pve_vm_config.ipconfig0 | default('') | string).split(',') | sort }}"
__pve_vm_ipconfig0_desired: "{{ (pve_vm_ipconfig.ipconfig0 | default('') | string).split(',') | sort }}"
__pve_vm_net0_current: "{{ (__pve_vm_config.net0 | default('') | string).split(',') }}"
# autostart is not compared: PVE has no such VM config key (the config API does not return it).
# One fact per drift dimension, combined in __pve_vm_needs_update below.
- name: Determine drift per configuration dimension
ansible.builtin.set_fact:
__pve_vm_drift_forced: >-
{{
(pve_vm_force_update | bool)
or (__pve_vm_created | default(false) | bool)
}}
__pve_vm_drift_missing_keys: "{{ __pve_vm_required_config_keys | reject('in', __pve_vm_config) | list | length > 0 }}"
__pve_vm_drift_name: "{{ (__pve_vm_config.name | default('')) != (inventory_hostname | lower | replace('_', '-')) }}"
# PVE may return "host" or "cputype=host" (optionally followed by flags).
__pve_vm_drift_cpu: >-
{{
(__pve_vm_config.cpu | default('') | string).split(',')[0] | regex_replace('^cputype=', '') != 'host'
}}
__pve_vm_drift_resources: >-
{{
(pve_vm_memory is defined and (__pve_vm_config.memory | default(0) | int) != (pve_vm_memory | int))
or (pve_vm_cores is defined and (__pve_vm_config.cores | default(1) | int) != (pve_vm_cores | int))
or (pve_vm_sockets is defined and (__pve_vm_config.sockets | default(1) | int) != (pve_vm_sockets | int))
}}
__pve_vm_drift_ciuser: "{{ (pve_vm_ci_user | string | length > 0) and __pve_vm_config.ciuser | default('') != pve_vm_ci_user }}"
__pve_vm_drift_ipconfig: "{{ pve_vm_ipconfig.ipconfig0 is defined and __pve_vm_ipconfig0_current != __pve_vm_ipconfig0_desired }}"
__pve_vm_drift_nameservers: >-
{{ pve_vm_nameservers is defined and (__pve_vm_config.nameserver | default('')) != __pve_vm_nameservers_desired }}
__pve_vm_drift_onboot: "{{ (__pve_vm_config.onboot | default(0) | int) != (pve_vm_onboot | bool | int) }}"
__pve_vm_drift_agent: "{{ __pve_vm_agent_current != ((pve_vm_agent | bool | int) | string) }}"
__pve_vm_drift_network: >-
{{
pve_vm_network.net0 is defined and (
not (__pve_vm_config.net0 | default('')).startswith(pve_vm_network.net0.model | default('virtio') ~ '=')
or (pve_vm_network.net0.bridge is defined
and ('bridge=' ~ pve_vm_network.net0.bridge) not in __pve_vm_net0_current)
or (pve_vm_network.net0.tag is defined
and ('tag=' ~ pve_vm_network.net0.tag) not in __pve_vm_net0_current)
or (pve_vm_network.net0.tag is not defined
and (__pve_vm_net0_current | select('match', '^tag=') | list | length > 0))
or (pve_vm_network.net0.firewall is defined
and (('firewall=1' in __pve_vm_net0_current) != (pve_vm_network.net0.firewall | bool)))
)
}}
- name: Determine if VM configuration needs updating
ansible.builtin.set_fact:
__pve_vm_needs_update: >-
{{
__pve_vm_drift_forced | bool
or __pve_vm_drift_missing_keys | bool
or __pve_vm_drift_name | bool
or __pve_vm_drift_cpu | bool
or __pve_vm_drift_resources | bool
or __pve_vm_drift_ciuser | bool
or __pve_vm_drift_ipconfig | bool
or __pve_vm_drift_nameservers | bool
or __pve_vm_drift_onboot | bool
or __pve_vm_drift_agent | bool
or __pve_vm_drift_network | bool
}}
-90
View File
@@ -1,90 +0,0 @@
---
# Validation first, under always, so a bad input fails before any change whatever tags the run
# selects.
- name: Validate the role inputs
ansible.builtin.import_tasks: validate.yml
tags: always
# Every Proxmox API call of the role is inside this block, so the credentials are set once here
# instead of on each task; module_defaults set on a block reach tasks run through include_tasks.
# They are templated per task and no secret is stored as a fact. The uri call (detect_disk) takes
# host and header explicitly.
- name: Manage Proxmox VM lifecycle
module_defaults:
community.proxmox.proxmox_kvm:
api_user: "{{ pve_vm_api_user }}@{{ pve_vm_api_realm }}"
api_token_id: "{{ pve_vm_api_token_id }}"
api_token_secret: "{{ pve_vm_api_token_secret }}"
api_host: "{{ pve_vm_api_host }}"
validate_certs: false
community.proxmox.proxmox_disk:
api_user: "{{ pve_vm_api_user }}@{{ pve_vm_api_realm }}"
api_token_id: "{{ pve_vm_api_token_id }}"
api_token_secret: "{{ pve_vm_api_token_secret }}"
api_host: "{{ pve_vm_api_host }}"
validate_certs: false
ansible.builtin.uri:
validate_certs: false
block:
- name: Gather current VM information
ansible.builtin.include_tasks: detect.yml
- name: Remove VM if destruction is requested
ansible.builtin.include_tasks: delete.yml
when:
- pve_vm_state == "absent"
- pve_vm_allow_destroy | bool
- pve_vm_exists
- name: Stop processing for deleted VM
ansible.builtin.meta: end_host
when:
- pve_vm_state == "absent"
- pve_vm_allow_destroy | bool
- name: Create VM if it does not exist
ansible.builtin.include_tasks: create.yml
when:
- pve_vm_state != "absent"
- not pve_vm_exists
- not ansible_check_mode
- name: Preview VM creation
ansible.builtin.debug:
msg: >-
VM {{ pve_vm_vmid }} does not exist on {{ pve_vm_node }}: a real run clones it from template
{{ pve_vm_clone_vmid | default('(unset)') }} and then configures it. Nothing after the lookup runs for it
in this check.
changed_when: true
when:
- pve_vm_state != "absent"
- not pve_vm_exists
- ansible_check_mode
- name: Refresh VM information after changes
ansible.builtin.include_tasks: detect.yml
- name: Gather current VM disk information
ansible.builtin.include_tasks: detect_disk.yml
when:
- pve_vm_exists
- pve_vm_state != "absent"
- name: Update existing VM configuration
ansible.builtin.include_tasks: update.yml
when:
- pve_vm_state != "absent"
- pve_vm_exists
- name: Ensure VM power state
ansible.builtin.include_tasks: state.yml
when:
- pve_vm_exists
- pve_vm_state in ["started", "stopped"]
- name: Wait for VM to become ready
ansible.builtin.include_tasks: wait.yml
when:
- pve_vm_exists
- pve_vm_state == "started"
- pve_vm_wait_for_guest | bool
-18
View File
@@ -1,18 +0,0 @@
---
# Under --check the module (no check mode support) does not run; the preview compares the status the
# lookup in detect.yml read with the desired state.
- name: Preview VM power state
ansible.builtin.debug:
msg: "VM {{ pve_vm_vmid }} is {{ __pve_vm_info.status | default('unknown') }}, desired {{ pve_vm_state }}"
changed_when: >-
(__pve_vm_info.status | default('unknown')) != ('running' if pve_vm_state == 'started' else 'stopped')
when: ansible_check_mode
- name: Ensure VM state
no_log: true # defence in depth: the module already masks the API token secret
delegate_to: "{{ pve_vm_delegate }}"
community.proxmox.proxmox_kvm:
node: "{{ pve_vm_node }}"
vmid: "{{ pve_vm_vmid }}"
state: "{{ pve_vm_state }}"
when: not ansible_check_mode
-126
View File
@@ -1,126 +0,0 @@
---
- name: Detect VM configuration drift
ansible.builtin.include_tasks: detect_drift.yml
# Names only, no values: the drift facts are booleans, and sshkeys are never compared.
# Under --check this is the preview of the update and resize below (changed when either would run).
- name: Report configuration drift
ansible.builtin.debug:
msg: >-
{{
'drift: ' ~ (__pve_vm_drift_dimensions | join(', ')) if __pve_vm_drift_dimensions | length > 0
else 'no drift'
}}{{
'; boot disk resize: ' ~ __pve_vm_current_disk ~ 'G -> ' ~ pve_vm_disk_size
if (pve_vm_manage_disk and __pve_vm_resize_disk | default(false) | bool) else ''
}}
vars:
__pve_vm_drift_dimensions: >-
{{
[
'forced' if __pve_vm_drift_forced | bool else '',
'missing_keys' if __pve_vm_drift_missing_keys | bool else '',
'name' if __pve_vm_drift_name | bool else '',
'cpu' if __pve_vm_drift_cpu | bool else '',
'resources' if __pve_vm_drift_resources | bool else '',
'ciuser' if __pve_vm_drift_ciuser | bool else '',
'ipconfig' if __pve_vm_drift_ipconfig | bool else '',
'nameservers' if __pve_vm_drift_nameservers | bool else '',
'onboot' if __pve_vm_drift_onboot | bool else '',
'agent' if __pve_vm_drift_agent | bool else '',
'network' if __pve_vm_drift_network | bool else '',
] | select | list
}}
changed_when: >-
ansible_check_mode and (__pve_vm_needs_update | bool
or (pve_vm_manage_disk and __pve_vm_resize_disk | default(false) | bool))
- name: Update VM configuration
no_log: true # carries the API token secret
delegate_to: "{{ pve_vm_delegate }}"
community.proxmox.proxmox_kvm:
node: "{{ pve_vm_node }}"
vmid: "{{ pve_vm_vmid }}"
name: "{{ inventory_hostname | lower | replace('_', '-') }}"
memory: "{{ pve_vm_memory | default(omit) }}"
cores: "{{ pve_vm_cores | default(omit) }}"
sockets: "{{ pve_vm_sockets | default(omit) }}"
cpu: host
net: "{{ pve_vm_network | default(omit) }}"
ciuser: "{{ pve_vm_ci_user if (pve_vm_ci_user | length > 0) else omit }}"
ipconfig: "{{ pve_vm_ipconfig | default(omit) }}"
sshkeys: "{{ pve_vm_sshkeys | default(omit) }}"
nameservers: "{{ pve_vm_nameservers | default(omit) }}"
agent: "{{ pve_vm_agent }}"
onboot: "{{ pve_vm_onboot }}"
autostart: "{{ pve_vm_autostart }}"
update: true
state: present
# Explicit: the module has no check mode support, so --check skips it anyway; the report above is the preview.
when:
- __pve_vm_needs_update | bool
- not ansible_check_mode
# The role never sets a cloud-init password; a VM configured by other means may still have one
# stored. The module cannot combine delete with update, has no check mode and always reports
# changed, hence a separate task, run only when the key is present, with the debug as its --check
# preview.
- name: Preview deletion of the stored cloud-init password
ansible.builtin.debug:
msg: "cipassword stored on VM {{ pve_vm_vmid }}: a real run deletes it"
changed_when: true
when:
- "'cipassword' in __pve_vm_config"
- ansible_check_mode
- name: Delete the stored cloud-init password
no_log: true # carries the API token secret
delegate_to: "{{ pve_vm_delegate }}"
community.proxmox.proxmox_kvm:
node: "{{ pve_vm_node }}"
vmid: "{{ pve_vm_vmid }}"
delete: cipassword
when:
- "'cipassword' in __pve_vm_config"
- not ansible_check_mode
# The marker has been consumed by drift detection and the update above; reset it so another
# pve_vm run for this host in the same play does not force a second update.
- name: Clear the just-cloned marker
ansible.builtin.set_fact:
__pve_vm_created: false
- name: Resize boot drive
no_log: true # defence in depth: the module already masks the API token secret
delegate_to: "{{ pve_vm_delegate }}"
community.proxmox.proxmox_disk:
vmid: "{{ pve_vm_vmid }}"
disk: "{{ pve_vm_boot_disk }}"
size: "{{ pve_vm_disk_size }}"
state: resized
when:
- pve_vm_manage_disk | bool
- __pve_vm_resize_disk
- not ansible_check_mode
register: __pve_vm_disk_resize
- name: Track disk resize result
ansible.builtin.set_fact:
__pve_vm_disk_resized: "{{ __pve_vm_disk_resize.changed | default(false) }}"
- name: Restart VM if disk was resized
no_log: true # defence in depth: the module already masks the API token secret
delegate_to: "{{ pve_vm_delegate }}"
community.proxmox.proxmox_kvm:
node: "{{ pve_vm_node }}"
vmid: "{{ pve_vm_vmid }}"
state: restarted
when:
- __pve_vm_disk_resized
- pve_vm_reboot_if_required | bool
- not ansible_check_mode
-28
View File
@@ -1,28 +0,0 @@
---
# The input rules the argument spec cannot express. main.yml imports this file under
# tags: always, before any change; each assert keeps the condition under which its input is read.
# Every run calls the API: even pve_vm_state absent without pve_vm_allow_destroy looks the VM up.
- name: Assert the Proxmox API credentials are set
ansible.builtin.assert:
that:
- pve_vm_api_user | length > 0
- pve_vm_api_token_secret is defined and pve_vm_api_token_secret | length > 0
fail_msg: >-
The Proxmox API calls need pve_vm_api_user (bare user name, the role appends
@<pve_vm_api_realm>) and pve_vm_api_token_secret (normally vaulted). Neither has a usable
default: set them in the inventory.
quiet: true
# The update reads the resize flag, which is only computed while pve_vm_disk_size is defined.
- name: Assert the boot disk size is set while the disk is managed
ansible.builtin.assert:
that:
- pve_vm_disk_size is defined
fail_msg: >-
pve_vm_disk_size (for example 32G) must be set while pve_vm_manage_disk is true, the default.
Set pve_vm_manage_disk to false to leave the boot disk alone.
quiet: true
when:
- pve_vm_manage_disk | bool
- pve_vm_state != "absent"
-16
View File
@@ -1,16 +0,0 @@
---
- name: Wait for SSH to become available
delegate_to: localhost
ansible.builtin.wait_for:
host: "{{ ansible_host }}"
port: 22
timeout: 3600
# Runs on the guest itself, over the connection the play uses for it.
- name: Wait for cloud-init to finish
ansible.builtin.command: cloud-init status --wait
register: __pve_vm_cloudinit_status
retries: 10
delay: 15
until: __pve_vm_cloudinit_status.rc == 0
changed_when: false
-4
View File
@@ -1,4 +0,0 @@
---
# Authorization header of the ansible.builtin.uri call in detect_disk.yml, derived from the
# pve_vm_api_* inputs.
__pve_vm_api_auth_header: "PVEAPIToken={{ pve_vm_api_user }}@{{ pve_vm_api_realm }}!{{ pve_vm_api_token_id }}={{ pve_vm_api_token_secret }}"
+1 -1
View File
@@ -45,7 +45,7 @@ There is no discovery by variable name, and a variable that looks like one fails
### `service_rules`
A service role that owns firewall rules calls the role with `include_role` and `tasks_from: service_rules` after the main entry has run, with `apply: {tags: [...]}` so `--tags <role>` reaches these tasks. The entry point installs nothing and touches no default policy, no `before.rules` and no base rule. Outside check mode (`--check` or the `check_mode` keyword; the role detects it with a probe command that does not run there, not `ansible_check_mode`) it fails when ufw is not installed and active. In check mode it skips the reconcile only when `ufw status` fails (ufw not installed yet, the main entry may not have reached the host); a host with ufw installed but inactive is reconciled as usual.
A service role that owns firewall rules calls the role with `include_role` and `tasks_from: service_rules` after the main entry has run, with `apply: {tags: [...]}` so `--tags <role>` reaches these tasks. The entry point installs nothing and touches no default policy, no `before.rules` and no base rule. Outside check mode (`--check` or the `check_mode` keyword; the role detects it with a skipped probe task, not `ansible_check_mode`) it fails when ufw is not installed and active. In check mode it skips the reconcile only when `ufw status` fails (ufw not installed yet, the main entry may not have reached the host); a host with ufw installed but inactive is reconciled as usual.
| Variable | Default | Required | Description |
|---|---|---|---|
+1 -1
View File
@@ -68,7 +68,7 @@
# 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
# orphans. The cases that must change nothing run first and the purge last, so the
# idempotence run finds nothing left to delete. Under --check the role's own check-mode probe
# idempotence run finds nothing left to delete. Under --check the role's own skipped probe
# keeps the purge from deleting, and orphan_check.yml skips its counts.
- name: Report and purge the rules of unmanaged owners
hosts: all
+2 -2
View File
@@ -474,8 +474,8 @@
# apply of community.general.ufw reports changed for the would-be rule, so molecule's
# idempotence run (a second converge) would fail on it. Verify runs once, outside that count.
# The play runs under the check_mode keyword, which does not set ansible_check_mode in the
# included role; the role detects check mode with a probe task instead (a command does
# not run under the keyword). A present call that would add a rule and an absent call for an
# included role; the role detects check mode with a probe task instead (a command task is
# skipped under the keyword). A present call that would add a rule and an absent call for an
# owner that holds rules must change nothing. The two reads of the rule list are forced to
# run (check_mode: false) and compared as a whole.
- name: Check mode of service_rules changes nothing
+4 -4
View File
@@ -6,10 +6,10 @@
state: present
register: __ufw_install
# Not ansible_check_mode, which the play-level `check_mode: true` keyword does not set in include_role
# tasks, nor `is skipped`, which ansible-core 2.25 drops: the probe's stdout is empty in check mode.
# ansible_check_mode is not used: the play-level `check_mode: true` keyword does not set it inside
# include_role tasks. A command task is skipped in both forms, the same probe as tasks/sysctl.yml.
- name: Probe whether the run is in check mode
ansible.builtin.command: echo ran
ansible.builtin.command: "true"
register: __ufw_install_probe
changed_when: false
@@ -17,4 +17,4 @@
# Undefined when this file's tags are skipped; the guards then default it to true.
- name: Remember whether ufw can be configured
ansible.builtin.set_fact:
__ufw_can_configure: "{{ __ufw_install is not changed or __ufw_install_probe.stdout == 'ran' }}"
__ufw_can_configure: "{{ __ufw_install is not changed or __ufw_install_probe is not skipped }}"
+5 -4
View File
@@ -63,16 +63,17 @@
the rule tags): {{ ufw_managed_owners }}
quiet: true
# Not ansible_check_mode, which the play-level `check_mode: true` keyword does not set in include_role
# tasks, nor `is skipped`, which ansible-core 2.25 drops: the probe's stdout is empty in check mode.
# ansible_check_mode is not used: the play-level `check_mode: true` keyword does not set
# that magic variable inside include_role tasks (only --check does). A command task is
# skipped in both forms and its result says so, which is the one signal that holds for both.
- name: Probe whether the run is in check mode
ansible.builtin.command: echo ran
ansible.builtin.command: "true"
register: ufw_oa_probe
changed_when: false
- name: Remember whether the run is in check mode
ansible.builtin.set_fact:
ufw_oa_check: "{{ ufw_oa_probe.stdout != 'ran' }}"
ufw_oa_check: "{{ ufw_oa_probe is skipped }}"
- name: Read the firewall status
become: true
+5 -4
View File
@@ -121,16 +121,17 @@
- ufw_manage_rules
tags: [ufw, ufw_service_rules]
block:
# Not ansible_check_mode, which the play-level `check_mode: true` keyword does not set in include_role
# tasks, nor `is skipped`, which ansible-core 2.25 drops: the probe's stdout is empty in check mode.
# ansible_check_mode is not used: the play-level `check_mode: true` keyword does not set
# that magic variable inside include_role tasks (only --check does). A command task is
# skipped in both forms and its result says so, which is the one signal that holds for both.
- name: Probe whether the run is in check mode
ansible.builtin.command: echo ran
ansible.builtin.command: "true"
register: ufw_sr_probe
changed_when: false
- name: Remember whether the run is in check mode
ansible.builtin.set_fact:
ufw_sr_check: "{{ ufw_sr_probe.stdout != 'ran' }}"
ufw_sr_check: "{{ ufw_sr_probe is skipped }}"
- name: Read the firewall status
become: true
+5 -4
View File
@@ -7,17 +7,18 @@
check_mode: false
when: ufw_enabled and ufw_sysctl_overrides | length > 0
# Not ansible_check_mode, which the play-level `check_mode: true` keyword does not set in include_role
# tasks, nor `is skipped`, which ansible-core 2.25 drops: the probe's stdout is empty in check mode.
# ansible_check_mode is not used: the play-level `check_mode: true` keyword does not set that
# magic variable inside include_role tasks (only --check does). A command task
# is skipped in both forms and its result says so, the same probe as tasks/service_rules.yml.
- name: Probe whether the run is in check mode
ansible.builtin.command: echo ran
ansible.builtin.command: "true"
register: ufw_sysctl_probe
changed_when: false
when: ufw_enabled and ufw_sysctl_overrides | length > 0
- name: Remember whether the run is in check mode
ansible.builtin.set_fact:
ufw_sysctl_check: "{{ ufw_sysctl_probe.stdout != 'ran' }}"
ufw_sysctl_check: "{{ ufw_sysctl_probe is skipped }}"
when: ufw_enabled and ufw_sysctl_overrides | length > 0
# In check mode on a fresh host ufw is not installed yet, so the file is absent.
+4 -16
View File
@@ -70,18 +70,9 @@ USER_AGENT = "kamino-next-image-version"
class RegistryError(Exception):
def __init__(self, url, status, text, challenge="", codes=()):
def __init__(self, url, status, text, challenge=""):
super().__init__(f"GET {url}: HTTP {status}: {text}")
self.status, self.challenge, self.codes = status, challenge, codes
def _error_codes(raw):
"""The OCI error codes of an error body (`{"errors": [{"code": ...}]}`), or () for any other body."""
try:
errors = json.loads(raw).get("errors") or []
return tuple(e.get("code") for e in errors if isinstance(e, dict))
except (ValueError, AttributeError, TypeError):
return ()
self.status, self.challenge = status, challenge
def _readable(raw):
@@ -101,9 +92,7 @@ def _fetch(url, headers):
except urllib.error.HTTPError as exc:
raw = exc.read(20000).decode("utf-8", errors="replace")
challenge = exc.headers.get("WWW-Authenticate", "")
raise RegistryError(
url, exc.code, _readable(raw), challenge, _error_codes(raw)
) from exc
raise RegistryError(url, exc.code, _readable(raw), challenge) from exc
class Registry:
@@ -150,8 +139,7 @@ class Registry:
body, headers = self._get(path)
except RegistryError as exc:
# A repository not pushed yet is 404 NAME_UNKNOWN (OCI distribution spec): no tags.
# Any other 404, such as a wrong registry path, must fail rather than restart at .0.
if exc.status == 404 and "NAME_UNKNOWN" in exc.codes and not tags:
if exc.status == 404 and not tags:
return []
raise
tags += body.get("tags") or []
@@ -2,23 +2,23 @@
# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
#
# The Molecule workflow's run inside the molecule-controller image, from the checkout root: when a
# pin file differs from the image's, install the pull request's pins into $AC_ROOT/pins (/opt is not
# writable for the runner user) and put them first, then check that the scenarios on stdin load this
# checkout and run them. CI_BASE_PYTHON is a test seam.
# The Molecule workflow's run inside the ci image, from the checkout root: when a pin file differs
# from the image's, install the pull request's pins into $AC_ROOT/pins (/opt is not writable for the
# runner user) and put them first, then check that the scenarios on stdin load this checkout and run
# them. CI_BASE_PYTHON is a test seam.
#
# AC_ROOT=<dir holding ansible_collections> scripts/run_molecule_in_controller.sh < scenario-dirs
# AC_ROOT=<dir holding ansible_collections> scripts/run_molecule_in_ci_image.sh < scenario-dirs
set -euo pipefail
selected="$(cat)"
pins="$AC_ROOT/pins"
extra_collections=""
if sha256sum --quiet -c /opt/molecule-pins.sha256; then
echo "The pin files match the molecule-controller image; using the baked tools."
if sha256sum --quiet -c /opt/ci-pins.sha256; then
echo "The pin files match the ci image; using the baked tools."
else
echo "::warning::a pin file differs from the molecule-controller image; installing the pinned tools and collections for this run."
echo "::warning::a pin file differs from the ci image; installing the pinned tools and collections for this run."
"${CI_BASE_PYTHON:-/opt/venv/bin/python}" -m venv "$pins/venv"
"$pins/venv/bin/pip" install --quiet --require-hashes -r requirements-molecule.lock -r requirements-molecule.txt
"$pins/venv/bin/pip" install --quiet --require-hashes -r requirements-dev.lock -r requirements-dev.txt
export PATH="$pins/venv/bin:$PATH"
# The target alone on the path, so a baked copy is not taken as already installed.
for req in requirements.yml extensions/molecule/requirements.yml; do
+1 -2
View File
@@ -39,7 +39,7 @@ label_of() {
# Removes the scenario's containers by the platform names in its molecule.yml, expanded by molecule's
# interpolator, 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. The controller image has no docker CLI: python3 is the one molecule runs on, with PyYAML
# 103 s a full run. The ci image has no docker CLI: python3 is the one molecule runs on, with PyYAML
# and the Docker SDK of molecule's Docker driver.
remove_instances() {
python3 -I - "$1/molecule.yml" <<'EOF'
@@ -116,7 +116,6 @@ declare -A last_seconds=(
[roles/user_management/molecule/default]=115
[roles/pihole/molecule/default]=112
[roles/sshd/molecule/default]=65
[roles/pve_vm/molecule/default]=60
[roles/pve_lxc/molecule/default]=44
[roles/_binary_update/molecule/check_mode]=42
[roles/network_interfaces/molecule/default]=36
+4 -4
View File
@@ -21,8 +21,8 @@ Only a pull request is narrowed, and only when <base-ref> is given and EVENT_NAM
* .gitea/workflows/molecule.yml, when only comments, blank lines (both outside a block
scalar such as `run: |`) or the image pins changed: nothing for comments; for
MOLECULE_IMAGE or MOLECULE_IMAGE_2604, every scenario whose directory names that variable,
or every scenario when a shared molecule file names it; for CONTROLLER_IMAGE (the tools
molecule runs with), every scenario. Any other change to it is "any other file";
or every scenario when a shared molecule file names it; for CI_IMAGE (the tools molecule
runs with), every scenario. Any other change to it is "any other file";
* any other file selects every scenario.
A role uses another when any file under its directory names it as `mortis.kamino.<other>`
@@ -120,7 +120,7 @@ IGNORED = (
WORKFLOW = ".gitea/workflows/molecule.yml"
# The image pins of WORKFLOW, each a `KEY: >-` line followed by its value line, in the shape
# Renovate writes.
PIN_KEY = re.compile(r"(\s+)(CONTROLLER_IMAGE|MOLECULE_IMAGE|MOLECULE_IMAGE_2604): >-")
PIN_KEY = re.compile(r"(\s+)(CI_IMAGE|MOLECULE_IMAGE|MOLECULE_IMAGE_2604): >-")
PIN_VALUE = re.compile(
r"(\s+)git\.rkdr\.net/mortis/[a-z0-9._-]+:[^@\s]+@sha256:[0-9a-f]{64}"
)
@@ -331,7 +331,7 @@ def select(all_scenarios, changed, root=".", pins=None):
for path in changed:
if is_ignored(path):
continue
if path == WORKFLOW and pins is not None and "CONTROLLER_IMAGE" not in pins:
if path == WORKFLOW and pins is not None and "CI_IMAGE" not in pins:
image_pins = pins
for pin in pins:
by_image.update(naming(all_scenarios, pin, root))
+2 -3
View File
@@ -511,12 +511,11 @@ class PureTest(unittest.TestCase):
)
self.assertEqual(civ.dockerfile_labels('FROM c\nLABEL a="unbalanced\n'), {})
def test_the_molecule_collections_are_not_an_input_of_the_ci_image(self):
# Lint uses no collection of them, so their bump must not publish a ci version.
def test_the_molecule_collections_are_an_input_of_the_ci_image(self):
root = pathlib.Path(__file__).resolve().parents[2]
entry = civ.matrix_of((root / civ.MATRIX_FILE).read_text())["ci"]
files = civ.inputs_of(entry, (root / entry["dockerfile"]).read_text())[1]
self.assertNotIn("extensions/molecule/requirements.yml", files)
self.assertIn("extensions/molecule/requirements.yml", files)
def test_the_controller_pins_are_inputs_of_the_controller_image(self):
root = pathlib.Path(__file__).resolve().parents[2]
-15
View File
@@ -105,7 +105,6 @@ class FakeRegistry(http.server.BaseHTTPRequestHandler):
no_realm = False
empty_token = False
unknown = False # the repository does not exist yet
not_found = None # a 404 body without NAME_UNKNOWN
agents = None # a fresh list per test, set in setUp
def do_GET(self):
@@ -129,8 +128,6 @@ class FakeRegistry(http.server.BaseHTTPRequestHandler):
b"{}",
extra={"WWW-Authenticate": f'Bearer realm="{realm}",service="reg"'},
)
elif self.not_found is not None:
self.reply(404, self.not_found, "text/plain")
elif self.unknown:
body = {"errors": [{"code": "NAME_UNKNOWN", "message": "unknown"}]}
self.reply(404, json.dumps(body).encode())
@@ -158,7 +155,6 @@ class RegistryClient(unittest.TestCase):
def setUp(self):
FakeRegistry.refuse = FakeRegistry.refuse_token = FakeRegistry.no_realm = False
FakeRegistry.empty_token = FakeRegistry.unknown = False
FakeRegistry.not_found = None
FakeRegistry.agents = []
server = QuietServer(("127.0.0.1", 0), FakeRegistry)
threading.Thread(target=server.serve_forever, daemon=True).start()
@@ -180,17 +176,6 @@ class RegistryClient(unittest.TestCase):
niv.next_version("0.1", self.registry.tags(), "c", no_label), "0.1.0"
)
def test_a_404_without_name_unknown_is_a_registry_error(self):
for body in (
b"404 page not found",
b'{"errors":[{"code":"NOT_FOUND","message":"no such route"}]}',
):
with self.subTest(body=body):
FakeRegistry.not_found = body
with self.assertRaises(niv.RegistryError) as caught:
self.registry.tags()
self.assertEqual(caught.exception.status, 404)
def test_a_missing_manifest_is_still_a_registry_error(self):
FakeRegistry.unknown = True
with self.assertRaises(niv.RegistryError) as caught:
@@ -1,7 +1,6 @@
# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Tests for scripts/run_molecule_in_controller.sh with stub tools in place of the molecule-controller
image's.
"""Tests for scripts/run_molecule_in_ci_image.sh with stub tools in place of the ci image's.
Run with: python3 -m unittest discover -s tests/scripts
"""
@@ -14,7 +13,7 @@ import tempfile
import unittest
REPO = pathlib.Path(__file__).resolve().parents[2]
SCRIPT = REPO / "scripts" / "run_molecule_in_controller.sh"
SCRIPT = REPO / "scripts" / "run_molecule_in_ci_image.sh"
# Each stub appends its name, arguments and the paths it saw to STUB_LOG; STUB_FAIL_<name> fails it.
STUB = """#!/usr/bin/env bash
@@ -50,7 +49,7 @@ echo "runner args=$* path=$PATH acp=$ANSIBLE_COLLECTIONS_PATH" \\
@unittest.skipUnless(shutil.which("bash"), "bash is required")
class RunMoleculeInControllerTest(unittest.TestCase):
class RunMoleculeInCiImageTest(unittest.TestCase):
def setUp(self):
self.tmp = pathlib.Path(tempfile.mkdtemp(prefix="kamino-runci-")).resolve()
self.addCleanup(shutil.rmtree, self.tmp, True)
@@ -106,7 +105,7 @@ class RunMoleculeInControllerTest(unittest.TestCase):
result = self.run_script()
self.assertEqual(result.returncode, 0, result.stderr)
(check,) = self.calls("sha256sum")
self.assertIn("args=--quiet -c /opt/molecule-pins.sha256 ", check)
self.assertIn("args=--quiet -c /opt/ci-pins.sha256 ", check)
self.assertEqual(self.calls("python"), [])
self.assertEqual(self.calls("ansible-galaxy"), [])
self.assertEqual(len(self.calls("ansible")), 1)
@@ -133,8 +132,8 @@ class RunMoleculeInControllerTest(unittest.TestCase):
)
(pip,) = self.calls("pip")
self.assertIn(
"args=install --quiet --require-hashes -r requirements-molecule.lock"
" -r requirements-molecule.txt ",
"args=install --quiet --require-hashes -r requirements-dev.lock"
" -r requirements-dev.txt ",
pip,
)
galaxy = self.calls("ansible-galaxy")
+3 -121
View File
@@ -355,7 +355,7 @@ class RunMoleculeScenariosTest(unittest.TestCase):
def test_the_default_time_limit_is_inside_the_job_timeout(self):
# a limit past the job's own would let a hang take the job and every log with it
timeout = yaml.safe_load(WORKFLOW.read_text())["jobs"]["scenarios"][
timeout = yaml.safe_load(WORKFLOW.read_text())["jobs"]["molecule"][
"timeout-minutes"
]
limit = re.findall(r"MOLECULE_SCENARIO_TIMEOUT:-(\d+)\}", SCRIPT.read_text())
@@ -502,7 +502,7 @@ class ScenarioPlatformsTest(unittest.TestCase):
def test_the_sweep_spares_containers_younger_than_the_job_timeout(self):
# a shorter bound would remove the containers of a run still going
timeout = yaml.safe_load(WORKFLOW.read_text())["jobs"]["scenarios"][
timeout = yaml.safe_load(WORKFLOW.read_text())["jobs"]["molecule"][
"timeout-minutes"
]
run = step_run("Remove the containers earlier runs left")
@@ -519,130 +519,12 @@ class LanesInputTest(unittest.TestCase):
# yaml reads the `on:` key as True
lanes = workflow[True]["workflow_dispatch"]["inputs"]["lanes"]
self.assertEqual((lanes["type"], lanes["default"]), ("string", ""))
steps = workflow["jobs"]["scenarios"]["steps"]
steps = workflow["jobs"]["molecule"]["steps"]
step = next(s for s in steps if s.get("name") == "Run the scenarios")
self.assertEqual(step["env"]["MOLECULE_LANES"], "${{ inputs.lanes }}")
self.assertRegex(step["run"], r"docker run [^<]*-e MOLECULE_LANES\b")
class WorkflowJobsTest(unittest.TestCase):
"""A pull request that selects no scenario takes no Molecule runner slot."""
JOBS = yaml.safe_load(WORKFLOW.read_text())["jobs"]
def result(self, select, scenarios, selected):
"""The exit code of the result job's check for those needs results and that selection."""
(step,) = self.JOBS["result"]["steps"]
env = dict(
os.environ,
SELECT_RESULT=select,
SCENARIOS_RESULT=scenarios,
SELECTED=selected,
)
return subprocess.run(
# act runs a job container's step with sh when the step sets no shell
["sh", "-e", "-c", step["run"]],
check=False,
env=env,
capture_output=True,
).returncode
def written_output(self, selected):
"""The `scenarios` output select's run step writes for that selector output."""
step = next(s for s in self.JOBS["select"]["steps"] if s.get("id") == "select")
block = step["run"].split("|| exit 1\n", 1)[1]
with tempfile.TemporaryDirectory() as tmp:
out = pathlib.Path(tmp, "output")
subprocess.run(
["sh", "-e", "-c", 'selected="$1"\n' + block, "sh", selected],
check=True,
env=dict(os.environ, GITHUB_OUTPUT=str(out)),
)
lines = out.read_text().splitlines()
# GITHUB_OUTPUT's `name<<delimiter` form: the value is every line up to the delimiter
name, delim = lines[0].split("<<", 1)
self.assertEqual((name, lines[-1]), ("scenarios", delim))
self.assertNotIn(delim, lines[1:-1])
return "\n".join(lines[1:-1])
def test_select_writes_none_for_an_empty_selection(self):
self.assertEqual(self.written_output(""), "none")
def test_select_writes_the_selection_one_directory_per_line(self):
selected = "extensions/molecule/image-smoke\nroles/a/molecule/default"
self.assertEqual(self.written_output(selected), selected)
def test_three_jobs_each_on_its_runner(self):
self.assertEqual(
{name: job["runs-on"] for name, job in self.JOBS.items()},
{
"select": "kamino-docker",
"scenarios": ["kamino-molecule"],
"result": "kamino-docker",
},
)
def test_only_the_scenarios_job_runs_on_the_host(self):
# select and result need no Docker daemon, so they take no Molecule runner slot
self.assertIn("container", self.JOBS["select"])
self.assertIn("container", self.JOBS["result"])
self.assertNotIn("container", self.JOBS["scenarios"])
def test_every_job_has_the_fork_guard(self):
guard = (
"github.repository == 'mortis/kamino' && "
"(github.event_name != 'pull_request' || "
"github.event.pull_request.head.repo.full_name == github.repository)"
)
self.assertEqual(self.JOBS["select"]["if"], guard)
for name, job in self.JOBS.items():
self.assertTrue(job["if"].endswith(guard), name)
def test_the_scenarios_run_only_for_a_selection(self):
job = self.JOBS["scenarios"]
self.assertEqual(job["needs"], "select")
# false for `none` and for an empty or missing output alike
self.assertTrue(
job["if"].startswith(
"needs.select.outputs.scenarios != 'none' && "
"needs.select.outputs.scenarios != '' &&"
)
)
self.assertEqual(
self.JOBS["select"]["outputs"]["scenarios"],
"${{ steps.select.outputs.scenarios }}",
)
step = next(s for s in job["steps"] if s.get("name") == "Run the scenarios")
self.assertEqual(
step["env"]["SELECTED"], "${{ needs.select.outputs.scenarios }}"
)
self.assertIn('run_molecule_in_controller.sh <<< "$SELECTED"', step["run"])
def test_the_result_runs_whatever_the_others_ended_as(self):
job = self.JOBS["result"]
self.assertEqual(job["needs"], ["select", "scenarios"])
self.assertTrue(job["if"].startswith("always() &&"))
def test_the_result_passes_a_run_or_a_none_selection_only(self):
self.assertEqual(
self.result("success", "success", "roles/a/molecule/default"), 0
)
self.assertEqual(self.result("success", "skipped", "none"), 0)
# an empty output was lost, not an empty selection
self.assertNotEqual(self.result("success", "skipped", ""), 0)
self.assertNotEqual(
self.result("success", "skipped", "roles/a/molecule/default"), 0
)
self.assertNotEqual(
self.result("success", "failure", "roles/a/molecule/default"), 0
)
self.assertNotEqual(
self.result("success", "cancelled", "roles/a/molecule/default"), 0
)
self.assertNotEqual(self.result("failure", "skipped", "none"), 0)
self.assertNotEqual(self.result("skipped", "skipped", "none"), 0)
class ScenarioSequenceTest(unittest.TestCase):
"""A role scenario previews the fresh host and the configured host with molecule's check step."""
@@ -206,23 +206,6 @@ class SelectTest(unittest.TestCase):
)
self.assertEqual(chosen, [])
def test_a_ci_pin_bump_in_lint_or_build_selects_nothing(self):
chosen, _reason = self.select(
[".gitea/workflows/lint.yml", ".gitea/workflows/build.yml"]
)
self.assertEqual(chosen, [])
def test_lint_requirements_select_nothing(self):
# requirements-dev.* pin Lint's tools; Molecule's come from requirements-molecule.*.
chosen, _reason = self.select(["requirements-dev.txt", "requirements-dev.lock"])
self.assertEqual(chosen, [])
def test_molecule_requirements_select_everything(self):
# An ansible-core or molecule bump there changes the tools every scenario runs with.
for path in ("requirements-molecule.txt", "requirements-molecule.lock"):
chosen, _reason = self.select([path])
self.assertEqual(chosen, ALL, path)
def test_ignored_does_not_mask_a_role(self):
chosen, _reason = self.select(["docs/x.md", "roles/docker/tasks/main.yml"])
self.assertEqual(chosen, ["roles/docker/molecule/default"])
@@ -677,31 +660,8 @@ class WorkflowPinsTest(unittest.TestCase):
return self.pin(key).split("@sha256:")[0] + "@sha256:" + "0" * 64
def test_the_workflow_has_each_pin_where_the_selector_looks(self):
for key in ("CONTROLLER_IMAGE", "MOLECULE_IMAGE", "MOLECULE_IMAGE_2604"):
old, new = (
f"{key}: >-\n {v}" for v in (self.pin(key), self.bumped(key))
)
self.assertEqual(self.edited(old, new), {key}, key)
def test_the_workflow_runs_in_the_controller_image_not_ci(self):
# A ci pin bump must touch only Lint and Build, which IGNORED lists (ADR 0003).
self.assertIn("/mortis/molecule-controller:", self.pin("CONTROLLER_IMAGE"))
self.assertNotIn("/mortis/ci:", self.WORKFLOW)
def test_every_controller_pin_is_the_same(self):
# container.image cannot read env, so the select and result jobs repeat CONTROLLER_IMAGE
jobs = yaml.safe_load(self.WORKFLOW)["jobs"]
pins = [
jobs["select"]["container"]["image"],
self.pin("CONTROLLER_IMAGE"),
jobs["result"]["container"]["image"],
]
self.assertEqual(len(set(pins)), 1, pins)
self.assertEqual(self.WORKFLOW.count("/mortis/molecule-controller:"), len(pins))
# Renovate moves all three, which the selector reads as "any other change": every
# scenario, as for CONTROLLER_IMAGE alone.
bumped = self.WORKFLOW.replace(pins[0], self.bumped("CONTROLLER_IMAGE"))
self.assertIsNone(sel.pin_changes(self.WORKFLOW, bumped))
for key in ("CI_IMAGE", "MOLECULE_IMAGE", "MOLECULE_IMAGE_2604"):
self.assertEqual(self.edited(self.pin(key), self.bumped(key)), {key}, key)
def test_comments_and_blank_lines_change_nothing(self):
self.assertEqual(self.edited("# Behavioural tests", "# Other words"), set())
@@ -812,9 +772,8 @@ class SelectByPinTest(unittest.TestCase):
def test_comments_only_select_nothing(self):
self.assertEqual(self.select(set()), [])
def test_the_controller_image_or_no_analysis_selects_everything(self):
self.assertEqual(self.select({"CONTROLLER_IMAGE"}), ALL)
self.assertEqual(self.select({"CONTROLLER_IMAGE", "MOLECULE_IMAGE"}), ALL)
def test_the_ci_image_or_no_analysis_selects_everything(self):
self.assertEqual(self.select({"CI_IMAGE", "MOLECULE_IMAGE"}), ALL)
self.assertEqual(self.select(None), ALL)
def test_pins_do_not_narrow_another_file(self):