1 Commits
Author SHA1 Message Date
renovate-bot ac3acfb059 chore(deps): update dependency ansible-core to v2.22.0
renovate/stability-days Updates have met minimum release age requirement
Build / build (pull_request) Successful in 22s
Lint / lint (pull_request) Successful in 15s
Molecule / molecule (pull_request) Successful in 1m0s
2026-11-06 03:17:47 +00:00
118 changed files with 167 additions and 6338 deletions

No files matched your search

-21
View File
@@ -6,26 +6,5 @@ profile: production
exclude_paths:
- .gitea
- .venv
- apm_modules
- apm.lock.yaml
- changelogs
- images
# The Collection is checked out outside an ansible_collections/mortis/kamino path (CI clones it
# into the workspace), so ansible-lint cannot resolve a role of this Collection by its FQCN in
# a scenario's converge play. List the roles the scenarios call by FQCN.
mock_roles:
- mortis.kamino.docker
- mortis.kamino.fail2ban
- mortis.kamino.network_interfaces
- mortis.kamino.system_baseline
- mortis.kamino.systemd_hardening
# Lint runs offline and the ci image bakes no collections, so modules from the dependencies
# declared in galaxy.yml cannot be resolved. Their arguments are exercised by molecule, which
# installs the collections.
mock_modules:
- ansible.posix.mount
- ansible.posix.sysctl
- community.general.locale_gen
- community.general.timezone
+2 -3
View File
@@ -1,8 +1,7 @@
name: Build
# Builds the Collection tarball and checks it. On a v* tag it also checks the release
# invariants of ADR 0004 (annotated tag, tag equals v + galaxy.yml version; the ADR is in the
# maintainer's environment repository). Nothing is
# invariants of ADR 0004 (annotated tag, tag equals v + galaxy.yml version). Nothing is
# uploaded: the tarball is built in a temporary directory and discarded. Releases are
# consumed by git tag, so there is no publish step. No org secret is used; the job token (secrets.GITHUB_TOKEN) clones the repository.
on: # yamllint disable-line rule:truthy
@@ -32,7 +31,7 @@ jobs:
timeout-minutes: 30
# The ci image (images/ci, built by image.yml): tag for the release, digest enforced.
container:
image: git.rkdr.net/mortis/ci:0.2.15@sha256:32b6b44640b0864266fdabb37f7c9d1c8e83834753e63f69af9c0c8a1cc67eb1
image: git.rkdr.net/mortis/ci:0.2.12@sha256:76b101f917c06f943d4b32aa9fca1bf0b5d13906cac618bd053dae3e17071f77
env:
PIP_DISABLE_PIP_VERSION_CHECK: "1"
steps:
+2 -2
View File
@@ -1,7 +1,7 @@
name: Images
# Builds the images under images/ with kaniko (osscontainertools fork, v1.28.6) and
# pushes them to git.rkdr.net/mortis/<name> (ADR 0004 in the maintainer's environment repository, Image distribution): the molecule
# pushes them to git.rkdr.net/mortis/<name> (ADR 0004, Image distribution): the molecule
# test targets (molecule-ubuntu2404, molecule-ubuntu2604) and the lint/build tooling (ci).
#
# Never on pull_request: a workflow file comes from the PR head, so a fork PR could
@@ -86,7 +86,7 @@ jobs:
dockerfile: Dockerfile
job_image: ubuntu:26.04@sha256:6a06111c3b0a8600feadb270aec771dc239bf407b25625f93f44ab00e11f4d3c
- name: ci
version: 0.2.15
version: 0.2.13
subpath: ""
dockerfile: images/ci/Dockerfile
job_image: ubuntu:26.04@sha256:6a06111c3b0a8600feadb270aec771dc239bf407b25625f93f44ab00e11f4d3c
+1 -1
View File
@@ -34,7 +34,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.15@sha256:32b6b44640b0864266fdabb37f7c9d1c8e83834753e63f69af9c0c8a1cc67eb1
image: git.rkdr.net/mortis/ci:0.2.12@sha256:76b101f917c06f943d4b32aa9fca1bf0b5d13906cac618bd053dae3e17071f77
env:
PIP_DISABLE_PIP_VERSION_CHECK: "1"
PRE_COMMIT_HOME: /opt/pre-commit
+6 -11
View File
@@ -7,16 +7,11 @@ name: Molecule
# It runs on the `kamino-molecule` label, a host executor on kamino-runner, which uses
# that LXC's own Docker daemon; no job container is given the Docker socket. That makes
# the job root-equivalent on the runner LXC, which is rebuildable and holds no
# production secret (ADR 0004 in the maintainer's environment repository, Runner
# isolation). The runner sits in an isolated network segment (outbound DNS to two
# resolvers and web traffic only; inbound SSH from two management hosts only), so a
# scenario cannot reach the LAN. A live test on 2026-11-08 showed a fork pull request's
# Build workflow starting on the runner at once, with no approval step (the tester may
# have had write access, so this is unproven for outsiders). The `if:` guard is a
# convenience filter, not a boundary: a fork controls its own workflow file. So the
# repository should not accept fork pull requests from untrusted users until the
# operator decides otherwise; the real condition is that only trusted people can push
# branches or open pull requests here.
# production secret (ADR 0004, Runner isolation). The runner's firewall is inert until
# the Proxmox datacenter firewall is enabled, so a scenario can reach the whole LAN:
# keep mortis/kamino private and accepting no fork pull requests until then. The `if:`
# guard is a convenience filter, not a boundary: the workflow file comes from the PR
# head. The real condition is that only trusted people can push branches here.
#
# Tooling is provisioned on the runner by the gitea_runner role (molecule venv and the
# collections the roles use); this job installs nothing. The test image is pulled from
@@ -51,7 +46,7 @@ jobs:
# Same-repo branches only (bot branches included: a Renovate pin pull request is what tests a new
# image); a push to main or a manual dispatch always runs. 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.
# block it. A fork pull request is skipped (and the repository takes none).
if: >-
github.repository == 'mortis/kamino' &&
(github.event_name != 'pull_request' ||
-6
View File
@@ -13,9 +13,3 @@ vault-pass*
gitleaks-report.json
# galaxy-importer output
importer_result.json
# APM (holocron skills): apm_modules/ is the dependency cache; .claude/skills,
# agents and hooks are `apm install` deploy output, regenerated on every install.
apm_modules/
.claude/skills/
.claude/agents/
.claude/hooks/
-4
View File
@@ -3,12 +3,8 @@ extends: default
ignore: |
.venv/**
apm_modules/**
# Generated by apm install; its list indentation fails the rules below.
apm.lock.yaml
# Written and rewritten by antsibull-changelog, which does not indent sequences.
changelogs/config.yaml
changelogs/changelog.yaml
rules:
trailing-spaces:
-51
View File
@@ -1,51 +0,0 @@
===========================
mortis.kamino Release Notes
===========================
.. contents:: Topics
v1.3.0
======
Release Summary
---------------
Adds the system_baseline role, the first role that needs other collections; community.general and ansible.posix are now declared dependencies.
Minor Changes
-------------
- galaxy.yml - Declare ``community.general`` (>=14.0.0) and ``ansible.posix`` (>=2.2.0) as dependencies, needed by ``system_baseline``. ``ansible-galaxy`` now installs them with the Collection unless the consumer's requirements already pin a satisfying version.
- system_baseline - New role. Applies a per-system-type OS baseline (apt upgrade, package install and removal, unattended-upgrades, locale, timezone, journal size cap, sysctl hardening, tmpfs mounts and an optional reboot). Besides ``main``, the ``update`` and ``reboot`` task files are supported entry points for callers that drive their own reboot; ``reboot`` sets the ``system_baseline_reboot_required`` fact.
v1.2.0
======
Minor Changes
-------------
- network_interfaces - New role. Renders /etc/network/interfaces from a layout of manual interfaces and bridges, validates it with ifreload and restores the backup if validation fails.
- systemd_hardening - New role. Disables and masks risky services per system type, writes a systemd manager hardening drop-in and renders opt-in per-service sandboxing drop-ins.
v1.1.0
======
Minor Changes
-------------
- fail2ban - New role. Installs Fail2Ban, manages jail.local and the service, deploys per-service jails into jail.d.
v1.0.0
======
Release Summary
---------------
First release. It holds the docker role; further roles follow in waves.
Minor Changes
-------------
- The Collection archive no longer contains extensions/ (the image-smoke molecule scenario), the roles' molecule scenarios, CLAUDE.md or other repository tooling; the Build workflow now fails when the archive holds anything outside an allow list, a member that is not a regular file or directory (symlinks, hardlinks, devices), or a path that is absolute or holds an empty, '..' or '.git' component (compared case-insensitively), a backslash or a control or zero-width character; it also fails on duplicate members, an empty archive or one that lacks MANIFEST.json, FILES.json, COPYING, README.md, meta/runtime.yml or changelogs/changelog.yaml, and on symlinks in the source tree (which ansible-galaxy would dereference).
- The archive check also rejects any file name containing "vault", SSH key and .envrc/.env* files, names that Windows or macOS extraction would read differently (trailing space or dot, reserved device names such as CON or NUL, "::", 8.3 aliases of .git, non-ASCII spaces, surrogate, private-use and unassigned characters, components over 255 bytes), case-insensitive duplicates and a name used as both a file and a directory. The Build workflow fails with a clear message unless exactly one tarball was built.
- docker - New role. Installs, updates or removes Docker Engine from the upstream APT repository and adds users to the docker group.
+95 -52
View File
@@ -5,24 +5,20 @@ Guidance for Claude Code (claude.ai/code) in this repository.
## What this is
`mortis.kamino`: an Ansible Collection (GPL-3.0-or-later, REUSE-compliant), extracted role by
role from the author's homelab environment repository. The design contract is ADR 0004 (in the
maintainer's environment repository). Roles arrive here wave by wave; `docker` is in 1.0.0, `fail2ban` in 1.1.0, `network_interfaces` and `systemd_hardening` in 1.2.0, `system_baseline` in 1.3.0.
role from the author's homelab Environment repo (`Defame1297/ansible-homelab-mono`). The
design contract is ADR 0004 in that repo (`docs/adr/0004-collection-consumption-and-release.md`)
and the tracking issue is its epic #486. There are no roles here yet: wave 1 arrives with the
extraction.
Fork pull requests from untrusted users are not accepted for now: a fork controls its own
workflow file, so the `if:` guards are a convenience, not a boundary (see the header of
`molecule.yml`). Do not change visibility, repository settings, branch or tag protection,
or create tags: those are the operator's.
The repo is **private and takes no fork pull requests** until the author has verified the
isolation of its CI runner. Do not change visibility, repository settings, branch or tag
protection, or create tags: those are the operator's.
## Working here
- Set up once per clone: `scripts/dev-setup.sh` (a virtualenv with the pinned tools and git
hooks that find them). The `language: system` hooks run `reuse`, `ansible-lint` and
`antsibull-changelog` by name, so a hook run without that virtualenv on `PATH` fails.
- Agent skills come from holocron through apm: `apm install` (the `apm` CLI is not one of the
pinned tools, and `dev-setup.sh` does not run it) deploys them to `.claude/skills` and
`.claude/agents`, both gitignored like `apm_modules/`. `apm.yml` and `apm.lock.yaml` are the only
tracked files. The entries are unpinned on purpose (see the comment in `apm.yml`); `apm install
--update` moves them. They are tooling, so `galaxy.yml` `build_ignore` keeps them out of the Collection.
- **Commit with git in a clone, never through the Gitea API.** The hooks (REUSE, yamllint,
actionlint, ansible-lint, gitleaks, changelog lint, Conventional Commits) only run in
`git commit`; an API commit skips them and CI finds the problem after the push. The first
@@ -35,20 +31,6 @@ or create tags: those are the operator's.
- Changes that can affect a consumer need a changelog fragment (`changelogs/fragments/`).
New files are covered by `REUSE.toml`; third-party-derived content needs its own annotation.
## Agent skills
### Issue tracker
Issues live in Gitea Issues on `mortis/kamino`, used through the `gitea-issues` skill and the Gitea MCP tools. See `docs/agents/issue-tracker.md`.
### Triage labels
The five triage roles map onto the repo's scoped `Status/` and `Reviewed/` labels. See `docs/agents/triage-labels.md`.
### Domain docs
Single-context: `GLOSSARY.md` and `docs/adr/` at the root, both created lazily. See `docs/agents/domain.md`.
## Workflows (`.gitea/workflows/`)
- Never `pull_request_target`. A fork `pull_request` run gets no secrets and a read-only job token; a same-repo pull request does get the org Actions secrets, so nothing but `image.yml` may reference them. Pass ref, repo and name values to
@@ -84,7 +66,8 @@ Single-context: `GLOSSARY.md` and `docs/adr/` at the root, both created lazily.
digest.
- kaniko runs inside the job container and unpacks the image it builds over it, so each matrix entry names its
job container (`job_image: ubuntu:<release>@sha256:...`) and its release must equal the `FROM ubuntu:` release
of the image's Dockerfile (`check_image_versions.py pins` fails otherwise). Moving an image to a new release is one edit: the Dockerfile `FROM`, the `job_image`
of the image's Dockerfile (`check_image_versions.py pins` fails otherwise; run 2529 broke a 24.04 build in a
26.04 job container). Moving an image to a new release is one edit: the Dockerfile `FROM`, the `job_image`
tag and digest, and the version bump. Digest drift within a release is tolerated. A `job_image`-only bump is
not an image input: no version bump, nothing rebuilt; the post-merge Images run only reaches the prepare step
for published versions, so that is its only exercise.
@@ -97,33 +80,93 @@ Single-context: `GLOSSARY.md` and `docs/adr/` at the root, both created lazily.
new version. Editing a label in a Dockerfile is an input and does.
- Each pushed layer must stay below 100 MB: Cloudflare rejects larger request bodies with
HTTP 413. That is why the `ci` image deletes the Go toolchains from the hook cache.
- `image.yml` is the only workflow that may reference the org Actions secrets (the registry push credential). Never print or use them anywhere else.
- `image.yml` tries the job token first with a write probe; Gitea 28 refuses it for the org's packages
(HTTP 401, run 2237), so the push uses the org Actions secrets `PACKAGE_PUSH_USER` and
`PACKAGE_PUSH_TOKEN`. Never print or use them anywhere else.
## Dependency automation (Renovate)
`renovate.json` is run by `.gitea/workflows/renovate.yml` (daily cron and `workflow_dispatch`) on the
`kamino-docker` runner, as a Kamino-only bot user, so code from this repository never runs in the
maintainer's production environment. Never reuse another Renovate credential here.
`renovate.json` is run by `.gitea/workflows/renovate.yml` (see below). Items marked unverified have not run yet.
- **Policy:** minor and patch bumps automerge, majors are manual; the Lint and Build checks are the gate.
A new Ubuntu release is a deliberate edit, never a bump. The `job_image` of each matrix entry in `image.yml`
never automerges: that job holds the registry push credential. kaniko is pinned by layer digests in
`image.yml` and updated by hand.
- **Two-PR loop for an image input** (`requirements-dev.txt`, `.pre-commit-config.yaml`, `images/**`): PR 1
carries the input change plus the PATCH bump of the image `version:` in `image.yml`
(`scripts/bump_image_versions.py [<base-ref>]`; `check_image_versions.py bump` then passes; Renovate runs it
as a post-upgrade task). The merge builds the image on `main`. PR 2 moves the consumers' pins to the new
digest (Renovate's pin-follow rule for the `mortis/*` images; a major version stays manual).
- **Bot-diff gate:** `scripts/check_bot_pr_diff.py` runs in the lint workflow, from `origin/main`'s copy so a
pull request cannot weaken it. A `renovate/` head ref may only change version lines (tool pins, hook `rev:`
lines, Dockerfile FROM tags and digests, matrix `version:` lines, `job_image:` pins, consumer image pins);
anything else fails, `renovate.json` included. The branch name is attacker-controlled, so this only
constrains the bot's own pull requests.
- **No Collection release from tooling bumps:** tooling files are in `galaxy.yml` `build_ignore`. A
role-visible change needs a changelog fragment and a new `galaxy.yml` version; only the operator tags.
- **No production images:** `check_image_versions.py pins` fails when anything under `.gitea/workflows`
mentions the maintainer's production image namespace.
- **Hand edits on a bot branch:** a commit pushed by hand to a `renovate/` branch makes Renovate stop
rebasing it, so merge that pull request by hand.
- **The runner has a single slot:** the Renovate job (up to 30 minutes) delays Lint, Build and Molecule.
- **Open item:** do not enable automerge for bot PRs until a live run has shown that they get Lint and Build.
- **Policy:** minor and patch bumps automerge, majors are manual. An `ansible-core` minor can show new
sanity findings; the Build check is the gate (a red bump is not merged), and `ansible-core` and
`ansible-lint` bump in one group. Dockerfile base-image tag and digest bumps (`images/*/Dockerfile`)
stay automergeable within a release: Kamino is the untrusted side and the pin PR's CI exercises the new image.
A new Ubuntu release (major `ubuntu` update) is never a bump: it is a deliberate edit. The `job_image` of each
matrix entry in `image.yml` (the job container) never automerges: that job holds the registry push credential.
kaniko is pinned by layer digests in `image.yml`; no Renovate manager reads them, so it is updated by
hand (the `/kaniko/` rule in `renovate.json` is only a safety net).
- **Two-PR loop for an image input** (`requirements-dev.txt`, `.pre-commit-config.yaml`,
`images/**`): PR 1 carries the input change plus the PATCH bump of the image `version:` in
`image.yml` (`scripts/bump_image_versions.py [<base-ref>]`, idempotent, edits only the
version line; `check_image_versions.py bump` then passes). The merge builds the image on
`main`. PR 2 moves the consumers' `image:<version>@sha256:<digest>` pins to that digest.
`renovate.json` runs the script as a `postUpgradeTasks` command of a catch-all rule (matches every package, since
only the first upgrade of a branch counts; branch mode, file filter `image.yml`; allowed by the one anchored regex in `RENOVATE_ALLOWED_COMMANDS` of `renovate.yml`),
so PR 1 carries the bump. PR 2 is Renovate's too: the pin-follow rule for
`git.rkdr.net/mortis/*` moves the `image:<version>@sha256:<digest>` pins of `lint.yml`, `build.yml`
and `molecule.yml` to the newest published version and automerges after its own Lint and Build ran
in the new image (unverified until the first such PR; a major version stays manual).
- **Bot-diff gate:** the `lint` workflow runs `scripts/check_bot_pr_diff.py` on pull requests. A
head ref starting `renovate/` may only change version lines in `requirements-dev.txt`, `rev:`
lines in `.pre-commit-config.yaml`, FROM tags/digests and the `uv==` pin in `images/*/Dockerfile`,
the matrix `version:` lines and the `job_image:` ubuntu pins in `image.yml`, and the image
pins in `lint.yml`, `build.yml` and `molecule.yml`. Anything else fails, `renovate.json` included.
Tags are `[A-Za-z0-9._-]` only, FROM and ubuntu lines must keep their digest, matrix versions must stay in
place and rise, and a binary or one-sided change fails.
The branch name is attacker-controlled, so this only constrains the bot's own pull requests; its
purpose is that automerging them cannot alter workflow logic or reach the org secrets.
- **No Collection release from tooling bumps:** everything involved is in `galaxy.yml`
`build_ignore`, so the Collection archive and version do not change. A role-visible change needs
a changelog fragment and a new `galaxy.yml` version, and only the operator tags.
- **No production images:** `check_image_versions.py pins` fails when anything under
`.gitea/workflows` mentions `git.rkdr.net/defame1297/`.
- **Where Renovate runs:** `.gitea/workflows/renovate.yml`, a daily cron (03:17 UTC) plus
`workflow_dispatch`, on the `kamino-runner` (`kamino-docker`): the untrusted side, so code from this
repository never runs in the production cluster (ADR 0004). It authenticates as a Kamino-only bot user
(write access to this repository only, no admin, no other repository) whose token is the repository
secret `RENOVATE_BOT_TOKEN` (scopes `write:repository`, `write:issue`, `read:user`, `read:organization`; not an org secret:
only `image.yml` may reference those). `read:organization` is needed because Renovate reads the owner organisation when it initialises the repository (dry run 2450: 403 without it). Never reuse the in-cluster Renovate user's token here: it
reaches the production repository. The workflow's own job token does not work: Renovate filters
its pull request lookups by its own username, which is the virtual user `gitea-actions`, and Gitea
answers `400 user does not exist` (dry run 2445). The bot user must not be able to push to `main`
or merge past the required checks (branch protection). The job container is `renovate/renovate:<version>-full@sha256:...` from Docker Hub
(the `-full` flavour for `python3`), same version as the cluster's CronJob, hand-bumped (renovate.json
disables updates for the workflow file). Lookups of the github.com pre-commit hooks are
unauthenticated (no `RENOVATE_GITHUB_COM_TOKEN` exists) and may hit rate limits: best effort.
- **Dry run:** Actions > Renovate > Run workflow with `dry_run=true` (the default for a manual run;
sets `RENOVATE_DRY_RUN=full`, `LOG_LEVEL=debug`). Read the debug log: no branch or PR is created. The
schedule runs live. The job fails (it used to stay green) when Renovate exits non-zero
(`RENOVATE_EXIT_CODE_FOR_ERRORS`, 7 for a failed clone) or when the JSON report
(`RENOVATE_REPORT_TYPE=file`) is missing or holds an ERROR or FATAL problem; warnings do not fail it.
A first good dry run shows a clone (no `external-host-error`, no `could not read Username`).
- **Open item: the first live run (do not enable automerge for bot PRs until one has shown it gets Lint and
Build).** The dry run proves the READS (lookups, config, branch plan) and, from the Renovate 44.161.0
source (confirm by the log line for the post-upgrade task), also runs `postUpgradeTasks`. Dry run 2445
already showed that git over HTTPS works with the global `http.<server>/.extraheader`
(`AUTHORIZATION: bearer <token>`, like `lint.yml`; Renovate does not pass `GIT_CONFIG_*` from its
environment to git but does pass `HOME`), which fixed the redirect failure of run 2439. Still unproven
until a run with the bot token: (1) that the bearer header is accepted for a personal access token (if
not, use basic auth with the bot user name); (2) that the first LIVE run can push a branch and open a
PR; (3) that PRs opened by the bot user trigger the PR workflows (it is a normal user, so they should; if
the required `Lint` and `Build` never start, automerge cannot work); (4) that bot PRs are held by
`main`'s required status checks (check the branch protection). Also confirm in the log: Renovate clones
blobless with full history, so `origin/main` exists for the script (source-based); `python3` is in the
image (no PyYAML: the scripts the bump step imports use the standard library only, dry run 2453); `github.head_ref` is populated (the gate fails closed on an empty one, via `EVENT_NAME`). Safety
net: a failing or disallowed post-upgrade command opens the PR WITHOUT the bump plus a red
`renovate/artifacts` status, and `check_image_versions.py bump` then fails lint. The job itself stays green:
the JSON report only records `branchName`, `prNo`, `prTitle`, `result` and `upgrades` per branch (run 2597),
with no field for a failed post-upgrade task, so the report check cannot see it.
- **The workflow holds the runner's slot:** the `kamino-runner` host has a single slot (the label is
`kamino-docker`), and the Renovate job may run up to 30 minutes (`timeout-minutes`) from 03:17 UTC, so
Lint, Build and Molecule checks queue behind it.
- **Not enabled:** credentials for the `git.rkdr.net` registry (`hostRules`; the tag and digest lookups
are anonymous). The `pre-commit` manager is beta.
- **Hand edits on a bot branch:** a commit pushed by hand to a `renovate/` branch makes Renovate treat
the branch as modified: it stops rebasing it, so merge that pull request by hand.
- **The guard runs from `main`:** the lint step extracts `scripts/` from `origin/main` and runs the
guard from there, so a pull request cannot weaken its own gate (the PR copy runs only while `main`
has no guard). A change to the guard takes effect for other PRs after it merges.
- A pin-only pull request (only `lint.yml`, `build.yml`, `molecule.yml`) does not match any
`image.yml` push path (`images/**`, `requirements-dev.txt`, `.pre-commit-config.yaml`,
`.gitea/workflows/image.yml`), so it rebuilds nothing.
+4 -6
View File
@@ -1,11 +1,9 @@
# Contributing
- Open a pull request against `main`. The forge does not allow self-registration, so only
accounts the maintainer has created can open pull requests or issues for now. Fork
pull requests are not a supported path: a fork controls its own workflow file, and a test
showed workflows starting without an approval step. Workflows on fork pull requests get
no secrets and a read-only token. To discuss a contribution, write to the address in
`SECURITY.md`.
- Open a pull request against `main`. A first-time contributor's fork pull
request needs a maintainer's approval before workflows run (Gitea waives this
once you have a merged pull request). Workflows on fork pull requests get no
secrets and a read-only token.
- Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/)
(`feat:`, `fix:`, `docs:`, `ci:` ...). CI checks every commit.
- Every user-visible change needs a changelog fragment in `changelogs/fragments/`
-19
View File
@@ -1,19 +0,0 @@
# Kamino
The language of contributing to the `mortis.kamino` Ansible Collection: how its guidance for contributors and their agents is named.
## Language
### Guidance
**Principle**:
A commitment that holds across the whole repository, stated with its reason.
_Avoid_: Value, guideline, philosophy
**Rule**:
What a principle requires of a contributor, human or agent, in one area of the repository.
_Avoid_: Convention, policy, standard
**Control**:
A mechanical check, a hook or a CI job, that holds a rule without depending on anyone's attention.
_Avoid_: Gate, guard, guardrail, enforcement
+3 -5
View File
@@ -4,7 +4,8 @@ An Ansible Collection of reusable, hardened roles for a self-hosted home lab:
Linux baseline, firewall, SSH, user management and, in later releases, Proxmox,
Gitea and Gitea Actions runner roles.
Status: roles arrive in waves. Release 1.3.0 holds the `docker`, `fail2ban`, `network_interfaces`, `system_baseline` and `systemd_hardening` roles.
Status: scaffolding. The Collection holds no roles yet; roles arrive in waves.
Version 1.0.0 is reserved for the first stable release.
## Consuming
@@ -16,12 +17,9 @@ name (FQCN) only, `mortis.kamino.<role>`:
collections:
- name: https://git.rkdr.net/mortis/kamino.git
type: git
version: v1.3.0
version: v0.1.0
```
Its dependencies (`community.general`, `ansible.posix`) are declared in `galaxy.yml`, so
`ansible-galaxy` installs them unless the same file already pins a satisfying version.
```yaml
- ansible.builtin.include_role:
name: mortis.kamino.<role>
-16
View File
@@ -1,16 +0,0 @@
# Security policy
## Reporting a vulnerability
Report a suspected vulnerability privately by email to security@rkdr.net. Do not open a
public issue or pull request for it.
A report should say which role, script or workflow is affected, how to reproduce the
problem and what impact you expect. The maintainer will acknowledge the report and
coordinate a fix and its disclosure with you.
## Scope
This repository holds Ansible roles, CI workflows and the container images they use. Roles
change the hosts they run against, so a flaw that weakens a hardening default or leaks a
secret is in scope. Only the latest release is supported.
-2631
View File
File diff suppressed because it is too large. Load diff
-29
View File
@@ -1,29 +0,0 @@
name: kamino
version: 0.1.0
description: Ansible Collection mortis.kamino. Consumer-side apm manifest for holocron skills.
license: GPL-3.0-or-later
# Consumer side: holocron plugins are addressed as git+path objects rather than
# <name>@holocron marketplace aliases, so nothing outside this manifest is
# needed. Unpinned (default branch) on purpose, matching ../ansible and
# ../ai-development: Renovate cannot keep a pin current here. Its apm manager
# documents only the string form (not these git+path objects), is not in
# renovate.json's enabledManagers, and holocron's v* tags are repo-wide and
# lag main (v2.0.1 is 164 commits behind and predates plugins/mattpocock). A
# hand-kept ref would just go stale. The third-party skills are pinned inside
# plugins/mattpocock/apm.yml, upstream of this manifest.
targets:
- claude
dependencies:
apm:
- git: [email protected]:Defame1297/holocron.git
path: plugins/bin
- git: [email protected]:Defame1297/holocron.git
path: plugins/core
- git: [email protected]:Defame1297/holocron.git
path: plugins/git
- git: [email protected]:Defame1297/holocron.git
path: plugins/gitea
- git: [email protected]:Defame1297/holocron.git
path: plugins/mattpocock
mcp: []
-39
View File
@@ -1,39 +0,0 @@
objects:
role:
docker:
description: Install, update or remove Docker Engine
name: docker
version_added: null
fail2ban:
description: Install and configure Fail2Ban
name: fail2ban
version_added: null
network_interfaces:
description: Manage /etc/network/interfaces
name: network_interfaces
version_added: null
system_baseline:
description: Apply the OS baseline for a system type
name: system_baseline
version_added: null
systemd_hardening:
description: Harden systemd for a system type
name: systemd_hardening
version_added: null
plugins:
become: {}
cache: {}
callback: {}
cliconf: {}
connection: {}
filter: {}
httpapi: {}
inventory: {}
lookup: {}
module: {}
netconf: {}
shell: {}
strategy: {}
test: {}
vars: {}
version: 1.3.0
+1 -72
View File
@@ -1,73 +1,2 @@
ancestor: null
releases:
1.0.0:
changes:
minor_changes:
- The Collection archive no longer contains extensions/ (the image-smoke molecule
scenario), the roles' molecule scenarios, CLAUDE.md or other repository tooling;
the Build workflow now fails when the archive holds anything outside an allow
list, a member that is not a regular file or directory (symlinks, hardlinks,
devices), or a path that is absolute or holds an empty, '..' or '.git' component
(compared case-insensitively), a backslash or a control or zero-width character;
it also fails on duplicate members, an empty archive or one that lacks MANIFEST.json,
FILES.json, COPYING, README.md, meta/runtime.yml or changelogs/changelog.yaml,
and on symlinks in the source tree (which ansible-galaxy would dereference).
- The archive check also rejects any file name containing "vault", SSH key and
.envrc/.env* files, names that Windows or macOS extraction would read differently
(trailing space or dot, reserved device names such as CON or NUL, "::", 8.3
aliases of .git, non-ASCII spaces, surrogate, private-use and unassigned characters,
components over 255 bytes), case-insensitive duplicates and a name used as
both a file and a directory. The Build workflow fails with a clear message
unless exactly one tarball was built.
- docker - New role. Installs, updates or removes Docker Engine from the upstream
APT repository and adds users to the docker group.
release_summary: First release. It holds the docker role; further roles follow
in waves.
fragments:
- ci-concurrency-main-runs.yml
- collection-tarball-contents.yml
- credential-and-workflow-comments.yml
- dev-setup-robustness.yml
- docker-role.yml
- image-version-and-pin-check.yml
- release-1.0.0.yml
- scaffold.yml
release_date: '2026-11-08'
1.1.0:
changes:
minor_changes:
- fail2ban - New role. Installs Fail2Ban, manages jail.local and the service,
deploys per-service jails into jail.d.
fragments:
- fail2ban-role.yml
release_date: '2026-11-08'
1.2.0:
changes:
minor_changes:
- network_interfaces - New role. Renders /etc/network/interfaces from a layout
of manual interfaces and bridges, validates it with ifreload and restores
the backup if validation fails.
- systemd_hardening - New role. Disables and masks risky services per system
type, writes a systemd manager hardening drop-in and renders opt-in per-service
sandboxing drop-ins.
fragments:
- systemd-hardening-network-interfaces-roles.yml
release_date: '2026-11-10'
1.3.0:
changes:
release_summary: Adds the system_baseline role, the first role that needs other
collections; community.general and ansible.posix are now declared dependencies.
minor_changes:
- galaxy.yml - Declare ``community.general`` (>=14.0.0) and ``ansible.posix``
(>=2.2.0) as dependencies, needed by ``system_baseline``. ``ansible-galaxy``
now installs them with the Collection unless the consumer's requirements already
pin a satisfying version.
- system_baseline - New role. Applies a per-system-type OS baseline (apt upgrade,
package install and removal, unattended-upgrades, locale, timezone, journal
size cap, sysctl hardening, tmpfs mounts and an optional reboot). Besides
``main``, the ``update`` and ``reboot`` task files are supported entry points
for callers that drive their own reboot; ``reboot`` sets the ``system_baseline_reboot_required``
fact.
fragments:
- system-baseline-role.yml
release_date: '2026-11-14'
releases: {}
@@ -0,0 +1,4 @@
trivial:
- >-
A later push to main no longer cancels the Lint and Build runs of an earlier one; pull request
runs still cancel their predecessors, and in the Build workflow a tag run has its own group.
@@ -0,0 +1,16 @@
minor_changes:
- >-
The Collection archive no longer contains extensions/ (the image-smoke molecule scenario),
the roles' molecule scenarios, CLAUDE.md or other repository tooling; the Build workflow
now fails when the archive holds anything outside an allow list, a member that is not a
regular file or directory (symlinks, hardlinks, devices), or a path that is absolute or
holds an empty, '..' or '.git' component (compared case-insensitively), a backslash or a
control or zero-width character; it also fails on duplicate members, an empty archive or one
that lacks MANIFEST.json, FILES.json, COPYING, README.md, meta/runtime.yml or
changelogs/changelog.yaml, and on symlinks in the source tree (which ansible-galaxy would
dereference).
- >-
The archive check also rejects any file name containing "vault", SSH key and .envrc/.env* files, names that Windows or macOS extraction
would read differently (trailing space or dot, reserved device names such as CON or NUL, "::", 8.3 aliases of .git, non-ASCII spaces,
surrogate, private-use and unassigned characters, components over 255 bytes), case-insensitive duplicates and a name used as both a
file and a directory. The Build workflow fails with a clear message unless exactly one tarball was built.
@@ -0,0 +1,2 @@
trivial:
- Document the credential model in CLAUDE.md, CONTRIBUTING.md and the workflow headers, and rename the image workflow to Images.
@@ -0,0 +1,6 @@
trivial:
- >-
scripts/dev-setup.sh checks for Python 3.11 or newer (KAMINO_PYTHON selects one), derives the repository from its own location, rebuilds an older
virtualenv, shell-quotes the repository path it writes into the installed hooks, lifts a repo-local core.hooksPath that points at this
repository's own hooks (including a multi-valued, empty or newline-containing one) for the install and restores it exactly, and fails early
only when core.hooksPath points elsewhere or is set outside the repository's config (a global value), or when the hooks are missing.
@@ -0,0 +1,9 @@
trivial:
- >-
Add scripts/check_image_versions.py and its tests, and run them in the Lint workflow:
image pins must name an image of the build matrix, and a pull request that changes an
image's inputs must bump its version.
- >-
scripts/check_image_versions.py reports a pin written in any case, with a port, in a nested path or without a tag; fails closed (naming
file and line) on a Dockerfile COPY source with a variable, quote or comment character and on a RUN --mount of the build context; says so
for a non-UTF-8 diff path and an empty image.yml; requires lint.yml and lists the consumer files it checked.
+2
View File
@@ -0,0 +1,2 @@
trivial:
- Initial repository scaffolding, CI workflows and the molecule base image definition.
-53
View File
@@ -1,53 +0,0 @@
# Domain Docs
How the engineering skills should consume this repo's domain documentation when exploring the codebase.
## Before exploring, read these
- **`GLOSSARY.md`** at the repo root, or
- **`GLOSSARY-MAP.md`** at the repo root if it exists: it points at one `GLOSSARY.md` per context. Read each one relevant to the topic.
- **`docs/adr/`**: read ADRs that touch the area you're about to work in. In multi-context repos, also check `src/<context>/docs/adr/` for context-scoped decisions.
Kamino's design contract is ADR 0004, kept in the maintainer's environment repository, not in this checkout. `docs/adr/` here holds only decisions made in this repository and may not exist yet.
If any of these files don't exist, **proceed silently**. Don't flag their absence; don't suggest creating them upfront. The `/domain-modeling` skill (reached via `/grill-with-docs` and `/improve-codebase-architecture`) creates them lazily when terms or decisions actually get resolved.
## File structure
Single-context repo (most repos):
```
/
├── GLOSSARY.md
├── docs/adr/
│ ├── 0001-event-sourced-orders.md
│ └── 0002-postgres-for-write-model.md
└── src/
```
Multi-context repo (presence of `GLOSSARY-MAP.md` at the root):
```
/
├── GLOSSARY-MAP.md
├── docs/adr/ ← system-wide decisions
└── src/
├── ordering/
│ ├── GLOSSARY.md
│ └── docs/adr/ ← context-specific decisions
└── billing/
├── GLOSSARY.md
└── docs/adr/
```
## Use the glossary's vocabulary
When your output names a domain concept (in an issue title, a refactor proposal, a hypothesis, a test name), use the term as defined in `GLOSSARY.md`. Don't drift to synonyms the glossary explicitly avoids.
If the concept you need isn't in the glossary yet, that's a signal: either you're inventing language the project doesn't use (reconsider) or there's a real gap (note it for `/domain-modeling`).
## Flag ADR conflicts
If your output contradicts an existing ADR, surface it explicitly rather than silently overriding:
> _Contradicts ADR-0007 (event-sourced orders), but worth reopening because…_
-30
View File
@@ -1,30 +0,0 @@
# Issue tracker: Gitea
Issues and specs for this repo live as Gitea issues on `mortis/kamino` (https://git.rkdr.net/mortis/kamino). Use the `gitea-issues` skill and the Gitea MCP tools (`mcp__gitea__issue_read`, `issue_write`, `list_issues`, `search_issues`); there is no `gh` or `glab`. Pull requests are a different object: `gitea-prs`.
## Conventions
- **Create an issue**: `issue_write` (method `create`) with `title` and `body`.
- **Read an issue**: `issue_read`, which returns the body, labels and comments.
- **List issues**: `list_issues` or `search_issues`, filtered by state and label.
- **Comment on an issue**: `issue_write` with the comment method.
- **Apply / remove labels**: label names are resolved to IDs with `label_read` (`list_repo_labels`); see `triage-labels.md`.
- **Close**: post the explanation as a comment first, then close the issue.
- **Sub-issues**: Gitea has no parent link. Put `Part of #<parent>` on the first line of the child body.
- **Blocking**: use Gitea's native dependencies (`issue_write`, method `add_dependency`, `dependency_type: blocked_by`), so the issue page shows what blocks it. A ticket is unblocked when every blocker is closed.
Issues and pull requests share one number space in Gitea, so confirm which one `#N` refers to before acting on it.
File issues only into `mortis/kamino`. The configured token holds `write:issue` and `write:repository` but not `read:organization`, so organisation-level labels cannot be read.
## Wayfinding operations
- **Map**: one issue labelled `Wayfinder/Map`.
- **Ticket**: a child issue of the map (`Part of #<map>`) with one type label: `Wayfinder/Grilling`, `Wayfinder/Research`, `Wayfinder/Prototype` or `Wayfinder/Task`. Maps and tickets carry no `Status/` label.
- **Claim**: assign the ticket to the Gitea account of the person driving the session, before any work. Ask for the account if it is not known; the token cannot look it up. An open, unassigned ticket is unclaimed.
- **Frontier**: the open, unassigned tickets of the map with no open blocker.
- **Resolve**: post the answer as a comment, close the ticket, then add one line to the map's "Decisions so far".
## Pull requests as a triage surface
**PRs as a request surface: no.** Fork pull requests are not accepted for now (CLAUDE.md), so PRs do not enter the triage queue. Set to `yes` only if that changes.
-13
View File
@@ -1,13 +0,0 @@
# Triage Labels
The skills speak in terms of five canonical triage roles. This file maps them to this repo's labels. The repo uses Gitea's scoped labels (`Scope/Name`, exclusive within a scope), so setting one `Status/` label replaces the previous one.
| Label in mattpocock/skills | Label in our tracker | Meaning |
| -------------------------- | ------------------------ | ---------------------------------------- |
| `needs-triage` | `Status/Needs Triage` | Maintainer needs to evaluate this issue |
| `needs-info` | `Status/Need More Info` | Waiting on reporter for more information |
| `ready-for-agent` | `Status/Ready for Agent` | Fully specified, ready for an AFK agent |
| `ready-for-human` | `Status/Ready for Human` | Requires human implementation |
| `wontfix` | `Reviewed/Won't Fix` | Will not be actioned |
`Status/Needs Triage`, `Status/Ready for Agent` and `Status/Ready for Human` are created for this mapping; the other two existed already. When a skill mentions a role, use the string from this table.
+1 -1
View File
@@ -27,7 +27,7 @@ It has no Node, so JavaScript actions (`actions/checkout`) cannot run in it: clo
As the job container of a workflow on the `kamino-docker` runner, pinned by tag and digest. This is the
shape of `.gitea/workflows/lint.yml` (which also holds the checkout step with the job-token authentication the
repository needs; read it for the full version):
private repository needs; read it for the full version):
```yaml
jobs:
+2 -11
View File
@@ -1,7 +1,7 @@
---
namespace: mortis
name: kamino
version: 1.3.0
version: 0.1.0
readme: README.md
authors:
- Defame1297
@@ -17,19 +17,12 @@ repository: https://git.rkdr.net/mortis/kamino
documentation: https://git.rkdr.net/mortis/kamino/src/branch/main/README.md
homepage: https://git.rkdr.net/mortis/kamino
issues: https://git.rkdr.net/mortis/kamino/issues
# Lower bounds are the versions CI tests against; no upper bound, so a consumer's
# newer pin does not conflict. Used by system_baseline.
dependencies:
community.general: ">=14.0.0"
ansible.posix: ">=2.2.0"
dependencies: {}
build_ignore:
# Repository tooling that is not part of the Collection. scripts/check_tarball.py fails
# the build if anything outside its allowlist ends up in the archive, so a new top-level
# file is a decision: ignore it here or allow it there.
- .ansible
- apm.yml
- apm.lock.yaml
- apm_modules
- .claude
- .gitea
- .gitignore
@@ -41,8 +34,6 @@ build_ignore:
- .ansible-lint
- CLAUDE.md
- CONTRIBUTING.md
- GLOSSARY.md
- SECURITY.md
- HANDOFF.md
- extensions
- images
+1 -1
View File
@@ -61,7 +61,7 @@ RUN python3 -m venv /opt/venv \
# uv only lives in the build stage (its own venv): the final image keeps the
# interpreters it downloaded, not the installer.
RUN python3 -m venv /opt/uv-venv \
&& /opt/uv-venv/bin/pip install uv==0.13.7 \
&& /opt/uv-venv/bin/pip install uv==0.13.6 \
&& /opt/uv-venv/bin/uv python install 3.11 3.13
# pre-commit needs a git repository to resolve a config. The hook repositories are
-10
View File
@@ -141,16 +141,6 @@
"ansible-lint"
]
},
{
"description": "Hold ansible-lint at the newest version galaxy-importer allows. galaxy-importer 0.4.44 (the newest release, used by the Build job) declares ansible-lint<=26.10.1, so a pin above that makes pip fail with ResolutionImpossible and Lint and Build go red (seen on the 26.11.0 bump). Remove this rule, and raise the cap, once a galaxy-importer release lifts its ansible-lint limit.",
"matchDatasources": [
"pypi"
],
"matchPackageNames": [
"ansible-lint"
],
"allowedVersions": "<=26.10.1"
},
{
"description": "The job containers of image.yml (matrix job_image, ubuntu by digest) hold the org registry push credential while the image job runs: never automerged, and kept in their own branch so the Dockerfile base-image bumps are not held back with them.",
"matchFileNames": [
+1 -1
View File
@@ -7,6 +7,6 @@
ansible-core==2.22.0
ansible-lint==26.10.1
pre-commit==4.7.0
antsibull-changelog==0.37.0
antsibull-changelog==0.36.0
galaxy-importer==0.4.44
reuse==6.3.0
View File
Whitespace-only changes.
-72
View File
@@ -1,72 +0,0 @@
# docker
Installs Docker Engine from the upstream Docker APT repository, optionally updates it, or removes it, and adds listed users to the `docker` group. Variables and their types are defined in [`meta/argument_specs.yml`](meta/argument_specs.yml), which is the source of truth.
## Supported platforms
Ubuntu. The key and repository URLs point at `download.docker.com/linux/ubuntu`, and the source line uses `ansible_distribution_release`. The default architecture is `amd64`. A limited molecule scenario covers the role's own logic (see [Tests](#tests)); the real Docker Engine is not tested.
## Requirements and run order
- Needs gathered facts and privilege escalation.
- Use it by its fully qualified name, `mortis.kamino.docker`.
- Run it before any role that needs the Docker group. Roles that install later and create their own user must add that user to the group themselves (see `docker_users`).
- The `ufw` role is not a dependency and is not called: Docker publishes ports through iptables and owns no UFW rule.
## Role variables
| Variable | Default | Required | Description |
|---|---|---|---|
| `docker_remove` | `false` | no | Remove Docker instead of installing it. |
| `docker_remove_data` | `false` | no | With `docker_remove`, purge packages and delete `/var/lib/docker`. |
| `docker_update` | `false` | no | Upgrade packages to their current candidate version. |
| `docker_packages` | `docker-ce`, `docker-ce-cli`, `containerd.io` | no | Packages managed. |
| `docker_keyring_path` | `/etc/apt/keyrings/docker.asc` | no | Repository key location. |
| `docker_apt_list_path` | `/etc/apt/sources.list.d/docker.list` | no | APT source file. |
| `docker_gpg_url` | `https://download.docker.com/linux/ubuntu/gpg` | no | Key URL. |
| `docker_repo_base_url` | `https://download.docker.com/linux/ubuntu` | no | Repository base URL. |
| `docker_apt_arch` | `amd64` | no | Architecture in the APT source. |
| `docker_service` | `docker` | no | systemd unit name. |
| `docker_group` | `docker` | no | Group for `docker_users`. |
| `docker_users` | `[]` | no | Users added to the group. |
## Tags
`docker` (everything), `install`, `update`, `remove`, `configure` (group membership). The tasks in `remove.yml` carry `docker` and `remove`.
Update (`docker_update: true`) and removal (`docker_remove: true`) are opt-in: run them on a host that is safe to change.
## Example play
```yaml
- hosts: standalone_vms
roles:
- role: mortis.kamino.docker
vars:
docker_users: [deploy]
```
## Tests
`molecule/default` runs in CI only (`.gitea/workflows/molecule.yml`, no local runner), in the `molecule-ubuntu2404` test container. A real Docker Engine cannot run there: `dockerd` needs the bridge, iptables rules and a delegated cgroup, and the container has no privileged mode. So the scenario builds a local APT repository, signs it with a throwaway key, and points the role at it with `docker_gpg_url` and `docker_repo_base_url`. The repository holds empty stand-ins for `docker-ce`, `docker-ce-cli` and `containerd.io`. The stand-in `docker-ce` ships a stub `docker.service` (`sleep infinity`) and creates the `docker` group, as the real package does.
What it shows, with the role's tasks running unchanged:
- The key is fetched, stored at `docker_keyring_path` with mode `0644`, and apt really verifies the repository against it (an unsigned or wrongly signed repository would leave no install candidate).
- The source line has the architecture, the `signed-by` keyring and `ansible_distribution_release`.
- The packages are installed from that repository, the unit is enabled and active, and `docker_users` join `docker_group`.
- `docker_remove` with `docker_remove_data` removes the source line, the keyring, the packages, the unit and `/var/lib/docker`.
- The argument check refuses a mapping for `docker_users` and a non-boolean `docker_remove`.
- A second run changes nothing (molecule's idempotence check).
What it does not show: that the upstream repository and key at `download.docker.com` are reachable and valid, that the real packages install, that `dockerd` starts, anything about container networking or iptables, the `docker_update` path (`tasks/update.yml`), and removal without `docker_remove_data` (the removal stops the unit first, so it can run only once per install). It needs the Ubuntu mirrors, for `gnupg` in `prepare.yml` and the `curl` the role installs. These gaps are a known residual risk of the role.
## Notes
- `docker_remove` is checked first: when true, only `remove.yml` runs.
- Removal with `docker_remove_data` is destructive. It deletes `/var/lib/docker`.
- The update task resolves each package's candidate with `apt-cache policy` and fails if a package has none. It installs `package=version`, never `latest`.
- Installing or updating the packages notifies `Restart docker`. The `meta: flush_handlers` at the end of `tasks/main.yml` is untagged, so it runs only without a `--tags` selection; under `--tags update` (or `install`) it is skipped and the handler runs at the end of the play instead.
- Do not combine with anything that installs the distro `docker.io` package on the same host: this role installs `docker-ce` from Docker's repository, and the two packages conflict.
- Docker bypasses UFW for published ports (`-p`), so UFW rules do not restrict container ports.
- `no_log` is not used: the role handles no secrets.
-31
View File
@@ -1,31 +0,0 @@
---
docker_update: false
docker_remove_data: false
docker_remove: false
docker_packages:
- docker-ce
- docker-ce-cli
- containerd.io
docker_keyring_path: /etc/apt/keyrings/docker.asc
docker_apt_list_path: /etc/apt/sources.list.d/docker.list
docker_gpg_url: https://download.docker.com/linux/ubuntu/gpg
docker_repo_base_url: https://download.docker.com/linux/ubuntu
# Override per host if a host is not amd64.
docker_apt_arch: amd64
docker_service: docker
docker_group: docker
# Usernames to add to the `docker` group at install time. Left empty by
# default: a role that needs Docker access but installs *after* this one in
# a host's `services:` list won't have created its run-as user yet when this
# role runs, so it must add itself to the group in its own tasks instead.
# This list only helps a role/user that already exists before `docker` runs.
docker_users: []
# Docker manipulates iptables directly for any published container port
# (`-p`), bypassing UFW rules entirely - so the role owns no UFW rule and does
# not call the ufw role.
-6
View File
@@ -1,6 +0,0 @@
---
- name: Restart docker
become: true
ansible.builtin.systemd:
name: "{{ docker_service }}"
state: restarted
-79
View File
@@ -1,79 +0,0 @@
---
argument_specs:
main:
short_description: Install, update or remove Docker Engine
description:
- >-
Installs Docker Engine from the upstream APT repository, or removes it when C(docker_remove) is true. Optionally updates the packages to
the current candidate versions, then adds C(docker_users) to C(docker_group).
- Needs gathered facts, because the APT source uses C(ansible_distribution_release).
options:
docker_remove:
type: bool
default: false
description:
- >-
Removes Docker instead of installing it. Stops the service, removes the packages, the APT source and the keyring,
and skips the install, update and group tasks.
docker_remove_data:
type: bool
default: false
description:
- >-
Only used with C(docker_remove). Purges the packages and deletes C(/var/lib/docker), which destroys images, containers and volumes.
docker_update:
type: bool
default: false
description:
- >-
Upgrades each package in C(docker_packages) to its current APT candidate version, pinned as package=version.
The C(Restart docker) handler is notified only when a package actually changes.
docker_packages:
type: list
elements: str
default: [docker-ce, docker-ce-cli, containerd.io]
description:
- Packages installed, updated or removed.
docker_keyring_path:
type: path
default: /etc/apt/keyrings/docker.asc
description:
- Where the Docker repository key is stored.
docker_apt_list_path:
type: path
default: /etc/apt/sources.list.d/docker.list
description:
- APT source file written for the Docker repository.
docker_gpg_url:
type: str
default: https://download.docker.com/linux/ubuntu/gpg
description:
- URL of the repository signing key.
docker_repo_base_url:
type: str
default: https://download.docker.com/linux/ubuntu
description:
- Base URL of the repository. The source line uses C(ansible_distribution_release) and the C(stable) component.
docker_apt_arch:
type: str
default: amd64
description:
- Architecture written into the APT source. Override per host if a host is not amd64.
docker_service:
type: str
default: docker
description:
- Name of the systemd unit that is enabled, started, restarted and stopped.
docker_group:
type: str
default: docker
description:
- Group that C(docker_users) are added to.
docker_users:
type: list
elements: str
default: []
description:
- >-
Existing users added to C(docker_group) with append. Empty by default, because a role that installs after docker creates its
run-as user too late and must join the group itself.
-17
View File
@@ -1,17 +0,0 @@
---
galaxy_info:
role_name: docker
namespace: mortis
author: Defame1297
license: GPL-3.0-or-later
description: Install, update or remove Docker Engine from the upstream Docker APT repository and add users to the docker group.
min_ansible_version: "2.19"
platforms:
- name: Ubuntu
versions:
- all
galaxy_tags:
- docker
- containers
- apt
dependencies: []
@@ -1,61 +0,0 @@
---
# The role runs unchanged against a signed local repository of stand-in packages (see
# prepare.yml), so the key fetch, the source line, the package install, the unit, the group
# membership and the handler are the real tasks. Only the packages are stand-ins: no Docker
# Engine is installed, and nothing here shows that dockerd works.
- name: Converge the role against the stand-in repository
hosts: all
vars:
docker_gpg_url: file:///srv/docker-stub-repo/docker.asc
docker_repo_base_url: file:///srv/docker-stub-repo
docker_users: [moleculeuser]
roles:
- role: mortis.kamino.docker
# The plays below are refusals: argument_specs rejects the wrong types before any task runs,
# so the idempotence run stays clean. A sentinel in the failure message tells "the role
# refused" from "the fail task after the role ran", which a bare rescue cannot.
- name: A docker_users value that is not a list is refused
hosts: all
gather_facts: false
vars:
docker_users:
not: a-list
tasks:
- name: Apply the role with a mapping for docker_users
block:
- name: Include the role
ansible.builtin.include_role:
name: mortis.kamino.docker
- name: Fail when the wrong type was accepted
ansible.builtin.fail:
msg: MOLECULE-ACCEPTED
rescue:
- name: The argument check stopped the play
ansible.builtin.assert:
that:
- "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')"
- "'docker_users' in ansible_failed_result.msg | default('')"
quiet: true
- name: A docker_remove value that is not a boolean is refused
hosts: all
gather_facts: false
vars:
docker_remove: maybe
tasks:
- name: Apply the role with a non-boolean docker_remove
block:
- name: Include the role
ansible.builtin.include_role:
name: mortis.kamino.docker
- name: Fail when the wrong type was accepted
ansible.builtin.fail:
msg: MOLECULE-ACCEPTED
rescue:
- name: The argument check stopped the play
ansible.builtin.assert:
that:
- "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')"
- "'docker_remove' in ansible_failed_result.msg | default('')"
quiet: true
@@ -1,101 +0,0 @@
#!/bin/bash
# Builds the signed APT repository the docker scenario installs from, so the role's own key,
# source-line and package tasks run for real without the real Docker Engine.
#
# build-stub-repo.sh <repo-root> <codename> <work-dir>
#
# The repository holds empty stand-ins for docker-ce, docker-ce-cli and containerd.io (the
# default docker_packages). docker-ce ships a stub docker.service and a postinst that creates
# the docker group, as the real package does. The Release file is signed with a throwaway key
# generated here; the matching public key is exported to <repo-root>/docker.asc, which is what
# the role fetches as its keyring. The secret key stays in <work-dir> and is never installed.
set -euo pipefail
repo=${1:?usage: build-stub-repo.sh <repo-root> <codename> <work-dir>}
codename=${2:?usage: build-stub-repo.sh <repo-root> <codename> <work-dir>}
work=${3:?usage: build-stub-repo.sh <repo-root> <codename> <work-dir>}
version=0.0.1~molecule
rm -rf "$repo" "$work"
mkdir -p "$repo/pool" "$repo/dists/$codename/stable/binary-amd64" "$work/gnupg" "$work/pkg"
chmod 0700 "$work/gnupg"
build_deb() {
local name=$1 tree="$work/pkg/$1"
mkdir -p "$tree/DEBIAN"
cat > "$tree/DEBIAN/control" <<CONTROL
Package: $name
Version: $version
Architecture: all
Maintainer: Molecule <molecule@invalid>
Description: stand-in for $name in the docker role's molecule scenario
Empty package. It installs nothing from Docker.
CONTROL
if [ "$name" = docker-ce ]; then
mkdir -p "$tree/usr/lib/systemd/system"
cat > "$tree/usr/lib/systemd/system/docker.service" <<'UNIT'
[Unit]
Description=Stand-in for the Docker Engine (molecule)
[Service]
ExecStart=/bin/sleep infinity
[Install]
WantedBy=multi-user.target
UNIT
cat > "$tree/DEBIAN/postinst" <<'POSTINST'
#!/bin/sh
set -e
if [ "$1" = configure ]; then
getent group docker > /dev/null || groupadd --system docker
systemctl daemon-reload || true
fi
POSTINST
chmod 0755 "$tree/DEBIAN/postinst"
fi
dpkg-deb --root-owner-group --build "$tree" "$repo/pool/${name}_${version}_all.deb" > /dev/null
}
for name in docker-ce docker-ce-cli containerd.io; do
build_deb "$name"
done
index="$repo/dists/$codename/stable/binary-amd64/Packages"
: > "$index"
for deb in "$repo"/pool/*.deb; do
{
dpkg-deb --field "$deb"
echo "Filename: pool/$(basename "$deb")"
echo "Size: $(stat --format %s "$deb")"
echo "SHA256: $(sha256sum "$deb" | cut -d' ' -f1)"
echo
} >> "$index"
done
release="$repo/dists/$codename/Release"
{
echo "Origin: molecule-stub"
echo "Label: molecule-stub"
echo "Suite: $codename"
echo "Codename: $codename"
echo "Date: $(LC_ALL=C date -u '+%a, %d %b %Y %H:%M:%S UTC')"
echo "Architectures: amd64"
echo "Components: stable"
echo "SHA256:"
echo " $(sha256sum "$index" | cut -d' ' -f1) $(stat --format %s "$index") stable/binary-amd64/Packages"
} > "$release"
export GNUPGHOME="$work/gnupg"
gpg --batch --quiet --pinentry-mode loopback --passphrase '' \
--quick-generate-key 'molecule stub repository <molecule@invalid>' rsa2048 sign never
gpg --batch --quiet --yes --armor --export > "$repo/docker.asc"
gpg --batch --quiet --yes --pinentry-mode loopback --passphrase '' --clearsign \
--output "$repo/dists/$codename/InRelease" "$release"
gpg --batch --quiet --yes --pinentry-mode loopback --passphrase '' --armor --detach-sign \
--output "$repo/dists/$codename/Release.gpg" "$release"
# The _apt user reads the repository during apt update.
chmod -R a+rX "$repo"
# Stop the gpg-agent that gpg started, so it does not outlive the script.
gpgconf --kill gpg-agent || true
@@ -1,28 +0,0 @@
---
# Runs on the repository's own runner (label kamino-molecule), in the molecule-ubuntu2404 image
# (MOLECULE_IMAGE, the pin in .gitea/workflows/molecule.yml). No privileged mode: systemd needs a
# writable cgroup, nothing else. NET_ADMIN is kept so the platform matches the other scenarios;
# this role does not need it, because the Docker Engine is a stand-in package and no daemon,
# bridge or iptables rule is created.
driver:
name: docker
platforms:
- name: docker-instance
image: ${MOLECULE_IMAGE}
pre_build_image: true
pull: true
command: /sbin/init
cgroupns_mode: host
volumes:
- /sys/fs/cgroup:/sys/fs/cgroup:rw
tmpfs:
- /run
- /run/lock
capabilities:
- NET_ADMIN
security_opts:
- apparmor=unconfined
provisioner:
name: ansible
verifier:
name: ansible
-55
View File
@@ -1,55 +0,0 @@
---
# The real Docker Engine cannot run in an unprivileged test container (dockerd needs the
# bridge, iptables and a delegated cgroup), so the role installs stand-in packages from a
# local APT repository. The repository is built and signed here, with a throwaway key, so the
# role's own tasks run unchanged: fetch the key, write the source line, install, enable and
# start the unit, join the group. Like the pihole and system_baseline scenarios, this needs
# the Ubuntu mirrors for gnupg and for the curl the role installs.
- name: Prepare
hosts: all
vars:
docker_molecule_repo: /srv/docker-stub-repo
docker_molecule_work: /var/tmp/docker-stub-work
tasks:
- name: Install gnupg, which signs the stand-in repository
ansible.builtin.apt:
name: gnupg
state: present
update_cache: true
- name: Copy the repository builder
ansible.builtin.copy:
src: build-stub-repo.sh
dest: /var/tmp/build-stub-repo.sh
owner: root
group: root
mode: "0755"
- name: Build and sign the stand-in repository
ansible.builtin.command:
argv:
- /var/tmp/build-stub-repo.sh
- "{{ docker_molecule_repo }}"
- "{{ ansible_facts['distribution_release'] }}"
- "{{ docker_molecule_work }}"
creates: "{{ docker_molecule_repo }}/docker.asc"
- name: Remove the signing key and the builder
ansible.builtin.file:
path: "{{ item }}"
state: absent
loop:
- "{{ docker_molecule_work }}"
- /var/tmp/build-stub-repo.sh
- name: Create a user for the docker group
ansible.builtin.user:
name: moleculeuser
shell: /usr/sbin/nologin
create_home: false
- name: Seed a Docker data directory for the removal test
ansible.builtin.file:
path: /var/lib/docker/molecule-marker
state: directory
mode: "0755"
-134
View File
@@ -1,134 +0,0 @@
---
# What the role is for, as far as stand-in packages can show it: the repository key and the
# source line are in place and apt really used them, the packages are installed from that
# repository, the unit is enabled and running, and the user joined the group. The second play
# runs the removal, which would break the checks of the first, so it comes last.
- name: Verify the install
hosts: all
vars:
docker_verify_packages: [docker-ce, docker-ce-cli, containerd.io]
tasks:
- name: Read the source list and the two keys
ansible.builtin.slurp:
src: "{{ item }}"
loop:
- /etc/apt/sources.list.d/docker.list
- /etc/apt/keyrings/docker.asc
- /srv/docker-stub-repo/docker.asc
register: docker_verify_files
- name: The source line carries the arch, the keyring and the release
ansible.builtin.assert:
that:
- >-
(docker_verify_files.results[0].content | b64decode) ==
'deb [arch=amd64 signed-by=/etc/apt/keyrings/docker.asc] file:///srv/docker-stub-repo '
~ ansible_facts['distribution_release'] ~ ' stable\n'
quiet: true
- name: The keyring is the key the repository published
ansible.builtin.assert:
that:
- docker_verify_files.results[1].content == docker_verify_files.results[2].content
quiet: true
- name: Stat the keyring
ansible.builtin.stat:
path: /etc/apt/keyrings/docker.asc
register: docker_verify_keyring
- name: The keyring is world-readable, as apt needs
ansible.builtin.assert:
that: docker_verify_keyring.stat.mode == "0644"
quiet: true
- name: Ask apt where docker-ce comes from
ansible.builtin.command: apt-cache policy docker-ce
register: docker_verify_policy
changed_when: false
- name: Apt installed docker-ce from the signed stand-in repository
ansible.builtin.assert:
that:
- "'Installed: 0.0.1~molecule' in docker_verify_policy.stdout"
- "'file:/srv/docker-stub-repo' in docker_verify_policy.stdout"
quiet: true
- name: Ask dpkg for the package states
ansible.builtin.command:
argv: [dpkg-query, --show, --showformat, "${db:Status-Status}\\n", "{{ item }}"]
loop: "{{ docker_verify_packages }}"
register: docker_verify_dpkg
changed_when: false
- name: Every package is installed
ansible.builtin.assert:
that: docker_verify_dpkg.results | map(attribute='stdout') | map('trim') | unique | list == ['installed']
quiet: true
- name: Ask systemd about the unit
ansible.builtin.systemd:
name: docker.service
register: docker_verify_unit
check_mode: true
- name: The unit is enabled and running
ansible.builtin.assert:
that:
- docker_verify_unit.status.UnitFileState == "enabled"
- docker_verify_unit.status.ActiveState == "active"
quiet: true
- name: Ask which groups the user is in
ansible.builtin.command: id -nG moleculeuser
register: docker_verify_groups
changed_when: false
- name: The user joined the docker group
ansible.builtin.assert:
that: "'docker' in docker_verify_groups.stdout.split()"
quiet: true
# docker_remove_data is set, so this also covers the destructive path: the packages are
# purged and /var/lib/docker, seeded in prepare.yml, is deleted. The removal stops the unit
# before the package takes it away, so it can only run once; a second run would fail on the
# missing unit, which is why it is not in the converge.
- name: Verify the removal
hosts: all
gather_facts: false
vars:
docker_remove: true
docker_remove_data: true
docker_verify_packages: [docker-ce, docker-ce-cli, containerd.io]
tasks:
- name: Remove Docker with its data
ansible.builtin.include_role:
name: mortis.kamino.docker
- name: Stat what the removal must delete
ansible.builtin.stat:
path: "{{ item }}"
loop:
- /etc/apt/sources.list.d/docker.list
- /etc/apt/keyrings/docker.asc
- /var/lib/docker
- /usr/lib/systemd/system/docker.service
register: docker_verify_gone
- name: The source list, the keyring, the data and the unit are gone
ansible.builtin.assert:
that: docker_verify_gone.results | map(attribute='stat.exists') | unique | list == [false]
quiet: true
- name: Ask dpkg for the package states
ansible.builtin.command:
argv: [dpkg-query, --show, --showformat, "${db:Status-Status}\\n", "{{ item }}"]
loop: "{{ docker_verify_packages }}"
register: docker_verify_dpkg
changed_when: false
failed_when: false
- name: No package is installed any more
ansible.builtin.assert:
that: "'installed' not in docker_verify_dpkg.results | map(attribute='stdout') | map('trim') | list"
quiet: true
-52
View File
@@ -1,52 +0,0 @@
---
- name: Install prerequisite packages
become: true
ansible.builtin.apt:
name:
- ca-certificates
- curl
state: present
update_cache: true
tags: [docker, install]
- name: Ensure APT keyrings directory exists
become: true
ansible.builtin.file:
path: /etc/apt/keyrings
state: directory
mode: "0755"
tags: [docker, install]
- name: Install Docker APT GPG key
become: true
ansible.builtin.get_url:
url: "{{ docker_gpg_url }}"
dest: "{{ docker_keyring_path }}"
mode: "0644"
tags: [docker, install]
- name: Install Docker APT source list
become: true
ansible.builtin.copy:
dest: "{{ docker_apt_list_path }}"
content: |
deb [arch={{ docker_apt_arch }} signed-by={{ docker_keyring_path }}] {{ docker_repo_base_url }} {{ ansible_distribution_release }} stable
mode: "0644"
tags: [docker, install]
- name: Install Docker Engine packages
become: true
ansible.builtin.apt:
name: "{{ docker_packages }}"
state: present
update_cache: true
notify: Restart docker
tags: [docker, install]
- name: Enable and start Docker service
become: true
ansible.builtin.systemd:
name: "{{ docker_service }}"
enabled: true
state: started
tags: [docker, install]
-30
View File
@@ -1,30 +0,0 @@
---
- name: Remove Docker (explicit only)
ansible.builtin.include_tasks: remove.yml
when: docker_remove | default(false) | bool
tags: [docker, remove]
- name: Install Docker Engine
ansible.builtin.include_tasks: install.yml
when: not (docker_remove | default(false) | bool)
tags: [docker, install]
- name: Ensure Docker Engine is up-to-date
ansible.builtin.include_tasks: update.yml
when:
- not (docker_remove | default(false) | bool)
- docker_update | bool
tags: [docker, update]
- name: Add configured users to the docker group
become: true
ansible.builtin.user:
name: "{{ item }}"
groups: "{{ docker_group }}"
append: true
loop: "{{ docker_users }}"
when: not (docker_remove | default(false) | bool)
tags: [docker, configure]
- name: Flush handlers
ansible.builtin.meta: flush_handlers
-39
View File
@@ -1,39 +0,0 @@
---
# Run with docker_remove=true (and docker_remove_data=true to purge) on a host that is safe to change.
- name: Stop and disable Docker service
become: true
ansible.builtin.systemd:
name: "{{ docker_service }}"
state: stopped
enabled: false
tags: [docker, remove]
- name: Remove Docker Engine packages
become: true
ansible.builtin.apt:
name: "{{ docker_packages }}"
state: absent
purge: "{{ docker_remove_data | default(false) | bool }}"
tags: [docker, remove]
- name: Remove Docker APT source list
become: true
ansible.builtin.file:
path: "{{ docker_apt_list_path }}"
state: absent
tags: [docker, remove]
- name: Remove Docker APT keyring
become: true
ansible.builtin.file:
path: "{{ docker_keyring_path }}"
state: absent
tags: [docker, remove]
- name: Remove Docker data directory (images, containers, volumes)
become: true
ansible.builtin.file:
path: /var/lib/docker
state: absent
when: docker_remove_data | default(false) | bool
tags: [docker, remove]
-61
View File
@@ -1,61 +0,0 @@
---
# Run with docker_update=true (tag: update).
- name: Refresh APT cache before checking for Docker updates
become: true
ansible.builtin.apt:
update_cache: true
tags: [docker, update]
- name: Determine latest available candidate version for each Docker package
ansible.builtin.command: "apt-cache policy {{ item }}"
register: docker_apt_policy
changed_when: false
# Read-only, so it also runs in the --check preview. Skipped there, there is no stdout to read the
# candidate from.
check_mode: false
loop: "{{ docker_packages }}"
loop_control:
label: "{{ item }}"
tags: [docker, update]
- name: Extract candidate version for each Docker package
ansible.builtin.set_fact:
docker_candidates: >-
{{ docker_candidates | default({}) | combine({item.item:
item.stdout | regex_search('Candidate:\s+(\S+)', '\1')
| default([''], true) | first}) }}
loop: "{{ docker_apt_policy.results }}"
loop_control:
label: "{{ item.item }}"
tags: [docker, update]
- name: Fail if any Docker package has no installable candidate
ansible.builtin.fail:
msg: >-
No installable candidate version found for Docker package '{{ item.key }}'
(apt-cache policy reported candidate '{{ item.value }}'). Check that the
Docker APT repo is reachable and the package name in docker_packages is
correct.
loop: "{{ docker_candidates | dict2items }}"
loop_control:
label: "{{ item.key }}"
when: not item.value or item.value == '(none)'
tags: [docker, update]
# Pinned to each package's resolved candidate version (never state=latest)
# so this task stays idempotent and passes ansible-lint's package-latest rule.
- name: Build pinned package=version list from candidates
ansible.builtin.set_fact:
docker_pinned_packages: "{{ docker_pinned_packages | default([]) + [item.key ~ '=' ~ item.value] }}"
loop: "{{ docker_candidates | dict2items }}"
loop_control:
label: "{{ item.key }}"
tags: [docker, update]
- name: Update Docker Engine packages to latest candidate versions
become: true
ansible.builtin.apt:
name: "{{ docker_pinned_packages }}"
state: present
notify: Restart docker
tags: [docker, update]
-73
View File
@@ -1,73 +0,0 @@
# fail2ban
Installs Fail2Ban, writes `/etc/fail2ban/jail.local` from `fail2ban_jails`, ensures the service runs and verifies the enabled jails loaded. A second entry point, `service_jail`, lets a service role deploy its own jail and filter into `jail.d`. Variables and their types are defined in [`meta/argument_specs.yml`](meta/argument_specs.yml), which is the source of truth.
## Supported platforms
Ubuntu 24.04 (noble), the image the molecule scenario runs on. The default `sshd` jail reads the systemd journal because sshd logs there on that release. The role installs `python3-systemd`, which `backend = systemd` jails need.
## Requirements and run order
- Use it by its fully qualified name, `mortis.kamino.fail2ban`.
- No hard prerequisite. `system_baseline` also lists `fail2ban` among its packages, so it normally runs first; this role installs it regardless.
- Main entry point: apply it after `ufw` in the play that hardens a host.
- `service_jail` entry point: called by a service role such as `gitea` (`include_role` with `tasks_from: service_jail`) after it has installed the service.
- A file named by a jail's `logpath` must exist when `fail2ban-client -t` runs, or the configuration test fails.
## Role variables
Main entry point:
| Variable | Default | Required | Description |
|---|---|---|---|
| `fail2ban_package_name` | `fail2ban` | no | Package name. |
| `fail2ban_jails` | one `sshd` jail (systemd backend, maxretry 3, bantime 1h, findtime 10m) | no | Jails written to `jail.local`. Each needs `name`, `enabled`, `filter`, `maxretry`, `bantime`, `findtime` and `logpath`, `journalmatch` or `backend: systemd`. |
| `fail2ban_service` | `enabled: true`, `state: started` | no | Service enablement and state. |
| `fail2ban_defaults` | `maxretry: 5`, `bantime: 600`, `findtime: 600` | no | Fallbacks for those keys. Only used by the `service_jail` entry point; main-entry jails must set all three (`tasks/validate.yml` asserts them), so there the fallback only applies when validation is skipped, for example under `--tags fail2ban_configure`. |
`service_jail` entry point:
| Variable | Default | Required | Description |
|---|---|---|---|
| `fail2ban_service_name` | none | yes | Jail name and file name under `filter.d` and `jail.d`. |
| `fail2ban_service_jail` | none | yes | Jail mapping; needs `logpath` or `journalmatch`. |
| `fail2ban_service_filter` | none | yes | Filter mapping; needs `failregex`, optional `ignoreregex`. |
| `fail2ban_package_name`, `fail2ban_defaults` | as above | no | Read from the role defaults. |
## Tags
Main entry point: `fail2ban` (everything), `fail2ban_install`, `fail2ban_validate`, `fail2ban_configure`, `fail2ban_service`.
`service_jail`: `fail2ban`, `fail2ban_install`, `fail2ban_service_jail`.
## Example play
```yaml
- hosts: pve_lxcs
roles:
- role: mortis.kamino.fail2ban
vars:
fail2ban_defaults:
maxretry: 5
bantime: 600
findtime: 600
- hosts: gitea
tasks:
- name: Deploy a service jail
ansible.builtin.include_role:
name: mortis.kamino.fail2ban
tasks_from: service_jail
vars:
fail2ban_service_name: gitea
fail2ban_service_jail: "{{ gitea_fail2ban_jail }}"
fail2ban_service_filter: "{{ gitea_fail2ban_filter }}"
```
## Notes
- Each service owns `jail.d/<name>.local`, so one play cannot overwrite another service's jail. `jail.local` only holds `fail2ban_jails`.
- Changing `jail.local` restarts Fail2Ban, which drops the in-memory ban list. Service jails only trigger a reload.
- `fail2ban-client -t` runs on every invocation of both entry points, not only when a file changed, so a broken file fails every run until fixed. It also runs in check mode.
- `fail2ban_service_jail` and `fail2ban_service_filter` must be passed as a single templated expression so they stay mappings, not strings or lists.
- `no_log` is not used: the role handles no secrets.
-25
View File
@@ -1,25 +0,0 @@
---
fail2ban_package_name: fail2ban
fail2ban_jails:
- name: sshd
enabled: true
port: ssh
filter: sshd
# Read the journal, not /var/log/auth.log: sshd logs to the journal on
# Ubuntu 24.04 and rsyslog's auth.log stays empty. Pinned so detection does
# not depend on the package's default backend. The filter's own journalmatch
# applies.
backend: systemd
maxretry: 3
bantime: "1h"
findtime: "10m"
fail2ban_service:
enabled: true
state: started
fail2ban_defaults:
maxretry: 5
bantime: 600
findtime: 600
-17
View File
@@ -1,17 +0,0 @@
---
- name: Restart Fail2Ban
become: true
ansible.builtin.service:
name: fail2ban
state: restarted
# Service jails only add a jail.d file, so reload instead of restarting the
# daemon (a restart drops the in-memory ban list). state=reloaded starts the
# service if it is not running. The config test runs as a task in
# service_jail.yml, so a broken file fails every run instead of only the one
# that wrote it.
- name: Reload Fail2Ban
become: true
ansible.builtin.systemd:
name: fail2ban
state: reloaded
-99
View File
@@ -1,99 +0,0 @@
---
argument_specs:
main:
short_description: Install and configure Fail2Ban
description:
- >-
Installs fail2ban and python3-systemd, validates C(fail2ban_jails), writes /etc/fail2ban/jail.local, tests the
configuration, ensures the service and checks that every enabled jail is loaded.
options:
fail2ban_package_name:
type: str
default: fail2ban
description:
- Name of the Fail2Ban package.
fail2ban_jails:
type: list
elements: dict
description:
- Jails written to jail.local. The role default is a single C(sshd) jail on the systemd backend.
- >-
Each item needs C(name), C(enabled), C(filter), C(maxretry), C(bantime) and C(findtime), plus one of
C(logpath), C(journalmatch) or C(backend) set to systemd.
- Optional keys are C(port) (default any), C(backend), C(journalmatch) and C(logpath).
fail2ban_service:
type: dict
description:
- Service management. The role default is C(enabled=true), C(state=started). Missing keys fall back to those values.
- Enabled jails are only checked with fail2ban-client when state is started.
options:
enabled:
type: bool
description: Whether the service starts at boot.
state:
type: str
description: Desired systemd state of the service, for example started or stopped.
fail2ban_defaults:
type: dict
description:
- >-
Fallback C(maxretry), C(bantime) and C(findtime). The role default is 5, 600 and 600. Only used by the
service_jail entry point; main-entry jails must set all three (C(tasks/validate.yml) asserts them), so
there the fallback only applies when validation is skipped, for example under C(--tags fail2ban_configure).
options:
maxretry:
type: int
description: Fallback number of failures before a ban.
bantime:
type: raw
description: Fallback ban duration, seconds or a Fail2Ban time string.
findtime:
type: raw
description: Fallback window in which failures are counted, seconds or a Fail2Ban time string.
service_jail:
short_description: Deploy one service jail and filter into jail.d
description:
- Entry point for a service role that owns its jail, used with C(include_role) and C(tasks_from=service_jail).
- >-
Installs Fail2Ban, writes /etc/fail2ban/filter.d/<name>.conf and /etc/fail2ban/jail.d/<name>.local, reloads
Fail2Ban and tests the configuration. It never touches jail.local.
options:
fail2ban_package_name:
type: str
default: fail2ban
description:
- Name of the Fail2Ban package installed by this entry point.
fail2ban_service_name:
type: str
required: true
description:
- Service name, used as the jail section name and the file names under filter.d and jail.d.
fail2ban_service_jail:
type: raw
required: true
description:
- >-
Mapping describing the jail. Must contain C(logpath) or C(journalmatch). Optional keys are C(enabled) (default
true), C(port) (default any), C(filter) (default the service name), C(backend) (default systemd, only used
with journalmatch), C(maxretry), C(bantime) and C(findtime), which fall back to C(fail2ban_defaults).
- Typed raw because callers pass a templated variable, for example C(gitea_fail2ban_jail). It is asserted to be a mapping.
fail2ban_service_filter:
type: raw
required: true
description:
- Mapping with C(failregex) (required) and C(ignoreregex) (optional, default empty).
- Typed raw because callers pass a templated variable. It is asserted to be a mapping.
fail2ban_defaults:
type: dict
description:
- Fallback C(maxretry), C(bantime) and C(findtime), read from the role defaults.
options:
maxretry:
type: int
description: Fallback number of failures before a ban.
bantime:
type: raw
description: Fallback ban duration.
findtime:
type: raw
description: Fallback failure counting window.
-16
View File
@@ -1,16 +0,0 @@
---
galaxy_info:
role_name: fail2ban
namespace: mortis
author: Defame1297
license: GPL-3.0-or-later
description: Install Fail2Ban, manage jail.local and the service, and deploy per-service jails and filters into jail.d.
min_ansible_version: "2.19"
platforms:
- name: Ubuntu
versions:
- noble
galaxy_tags:
- fail2ban
- security
dependencies: []
@@ -1,57 +0,0 @@
---
- name: Converge the base role (jail.local, sshd jail on the systemd backend)
hosts: all
roles:
- role: mortis.kamino.fail2ban
# The entry point service roles use. Two services must not overwrite each other:
# each gets its own jail.d file.
- name: Converge two service jails through the entry point
hosts: all
tasks:
- name: Service jail with a logpath
ansible.builtin.include_role:
name: mortis.kamino.fail2ban
tasks_from: service_jail
vars:
fail2ban_service_name: svc-a
fail2ban_service_jail:
port: "8080"
logpath: /var/log/svc-a.log
maxretry: 4
fail2ban_service_filter:
failregex: "^.*auth failure from <HOST>.*$"
- name: Service jail with a journalmatch
ansible.builtin.include_role:
name: mortis.kamino.fail2ban
tasks_from: service_jail
vars:
fail2ban_service_name: svc-b
fail2ban_service_jail:
port: "9090"
journalmatch: "_SYSTEMD_UNIT=ssh.service"
fail2ban_service_filter:
failregex: "^.*denied for <HOST>.*$"
# An input the entry point must reject. The block proves it is refused (the
# verify step proves no file was left behind); the play still passes, so the
# idempotence run stays clean.
- name: Missing failregex is rejected
block:
- name: Service jail without a failregex
ansible.builtin.include_role:
name: mortis.kamino.fail2ban
tasks_from: service_jail
vars:
fail2ban_service_name: svc-bad
fail2ban_service_jail:
logpath: /var/log/svc-a.log
fail2ban_service_filter: {}
- name: Fail when the invalid input was accepted
ansible.builtin.fail:
msg: service_jail accepted a filter without a failregex
rescue:
- name: The entry point refused the input
ansible.builtin.debug:
msg: Rejected as expected
@@ -1,26 +0,0 @@
---
# Runs on the repository's own runner (label kamino-molecule), in the molecule-ubuntu2404 image
# (MOLECULE_IMAGE, the pin in .gitea/workflows/molecule.yml). No privileged mode: systemd needs a
# writable cgroup and the firewall tools need NET_ADMIN, nothing else.
driver:
name: docker
platforms:
- name: fail2ban-instance
image: ${MOLECULE_IMAGE}
pre_build_image: true
pull: true
command: /sbin/init
cgroupns_mode: host
volumes:
- /sys/fs/cgroup:/sys/fs/cgroup:rw
tmpfs:
- /run
- /run/lock
capabilities:
- NET_ADMIN
security_opts:
- apparmor=unconfined
provisioner:
name: ansible
verifier:
name: ansible
@@ -1,13 +0,0 @@
---
# The log file a service jail watches must exist, or `fail2ban-client -t` fails.
- name: Prepare
hosts: all
gather_facts: false
tasks:
- name: Create the log file the logpath jail watches
ansible.builtin.file:
path: /var/log/svc-a.log
state: touch
mode: "0644"
access_time: preserve
modification_time: preserve
@@ -1,55 +0,0 @@
---
# What matters: the daemon accepts the whole configuration, loads the base jail and
# both service jails (each from its own jail.d file, #433), the sshd jail does not
# fall back to the empty auth.log, and a rejected input left nothing behind. The
# file contents are the templates' own output and are not restated here.
- name: Verify
hosts: all
gather_facts: false
tasks:
- name: Read jail.local
ansible.builtin.slurp:
src: /etc/fail2ban/jail.local
register: fail2ban_verify_jail_local
- name: The sshd jail reads the journal, not auth.log
ansible.builtin.assert:
that: "'/var/log/auth.log' not in (fail2ban_verify_jail_local.content | b64decode)"
quiet: true
- name: Stat the service jails and the rejected one
ansible.builtin.stat:
path: "{{ item }}"
loop:
- /etc/fail2ban/jail.d/svc-a.local
- /etc/fail2ban/jail.d/svc-b.local
- /etc/fail2ban/jail.d/svc-bad.local
- /etc/fail2ban/filter.d/svc-bad.conf
register: fail2ban_verify_files
- name: Each service has its own file and the rejected input left nothing behind
ansible.builtin.assert:
that:
- fail2ban_verify_files.results[0].stat.exists
- fail2ban_verify_files.results[1].stat.exists
- not fail2ban_verify_files.results[2].stat.exists
- not fail2ban_verify_files.results[3].stat.exists
quiet: true
- name: Test the configuration the daemon will load
ansible.builtin.command: fail2ban-client -t
changed_when: false
- name: Ask the running daemon for its jails
ansible.builtin.command: fail2ban-client status
register: fail2ban_verify_status
changed_when: false
- name: The daemon loaded the base and both service jails
ansible.builtin.assert:
that:
- "'sshd' in fail2ban_verify_status.stdout"
- "'svc-a' in fail2ban_verify_status.stdout"
- "'svc-b' in fail2ban_verify_status.stdout"
- "'svc-bad' not in fail2ban_verify_status.stdout"
quiet: true
-10
View File
@@ -1,10 +0,0 @@
---
- name: Configure Fail2Ban jail.local
become: true
ansible.builtin.template:
src: jail.local.j2
dest: /etc/fail2ban/jail.local
owner: root
group: root
mode: "0600"
notify: Restart Fail2Ban
-9
View File
@@ -1,9 +0,0 @@
---
- name: Install Fail2Ban package
become: true
ansible.builtin.package:
name:
- "{{ fail2ban_package_name }}"
# Required for `backend = systemd` jails (journalmatch), e.g. gitea's.
- python3-systemd
state: present
-16
View File
@@ -1,16 +0,0 @@
---
- name: Install Fail2Ban
ansible.builtin.import_tasks: install.yml
tags: [fail2ban, fail2ban_install]
- name: Validate Fail2Ban jails
ansible.builtin.import_tasks: validate.yml
tags: [fail2ban, fail2ban_validate]
- name: Configure Fail2Ban
ansible.builtin.import_tasks: configure.yml
tags: [fail2ban, fail2ban_configure]
- name: Ensure Fail2Ban service
ansible.builtin.import_tasks: service.yml
tags: [fail2ban, fail2ban_service]
-36
View File
@@ -1,36 +0,0 @@
---
# -t loads every jail, so a jail that cannot start (missing logpath, bad
# backend) fails here. -d only dumps the config and treats those as warnings.
- name: Test Fail2Ban configuration
become: true
ansible.builtin.command: fail2ban-client -t
register: fail2ban_test
failed_when: fail2ban_test.rc != 0
changed_when: false
check_mode: false
- name: Ensure Fail2Ban service is running
become: true
ansible.builtin.systemd:
name: fail2ban
enabled: "{{ fail2ban_service.enabled | default(true) }}"
state: "{{ fail2ban_service.state | default('started') }}"
# Handlers run at the end of the play; flush so the restart happens before the
# jail check below.
- name: Apply pending Fail2Ban handlers
ansible.builtin.meta: flush_handlers
- name: Verify enabled jails are loaded
become: true
ansible.builtin.command: "fail2ban-client status {{ item.name }}"
loop: "{{ fail2ban_jails | selectattr('enabled') }}"
loop_control:
label: "{{ item.name }}"
register: fail2ban_jail_status
until: fail2ban_jail_status.rc == 0
retries: 5
delay: 2
changed_when: false
check_mode: false
when: fail2ban_service.state | default('started') == 'started'
-57
View File
@@ -1,57 +0,0 @@
---
# Entry point for a service role that owns its own jail. Called with
# `include_role: name=mortis.kamino.fail2ban tasks_from=service_jail` and explicit vars; the
# jail lands in jail.d/<name>.local, never in the shared jail.local, so one
# play cannot overwrite another service's jail.
- name: Install Fail2Ban
ansible.builtin.import_tasks: install.yml
tags: [fail2ban, fail2ban_install]
- name: Validate service jail inputs
ansible.builtin.assert:
that:
- fail2ban_service_name is string
- fail2ban_service_jail is mapping
- fail2ban_service_filter is mapping
- fail2ban_service_filter.failregex is defined
- fail2ban_service_jail.logpath is defined or fail2ban_service_jail.journalmatch is defined
fail_msg: >-
fail2ban_service_jail and fail2ban_service_filter must be dicts. Pass the
variable as a single templated expression, not wrapped in a list or
embedded in a string.
tags: [fail2ban, fail2ban_service_jail]
- name: Deploy service filter definition
become: true
ansible.builtin.copy:
dest: "/etc/fail2ban/filter.d/{{ fail2ban_service_name }}.conf"
content: |
[Definition]
failregex = {{ fail2ban_service_filter.failregex }}
ignoreregex = {{ fail2ban_service_filter.ignoreregex | default('') }}
owner: root
group: root
mode: "0644"
notify: Reload Fail2Ban
tags: [fail2ban, fail2ban_service_jail]
- name: Deploy service jail
become: true
ansible.builtin.template:
src: service_jail.local.j2
dest: "/etc/fail2ban/jail.d/{{ fail2ban_service_name }}.local"
owner: root
group: root
mode: "0644"
notify: Reload Fail2Ban
# Read-only, so it also runs in check mode. A failure leaves the broken file on
# disk and fails every run until fixed, instead of only the run that wrote it.
tags: [fail2ban, fail2ban_service_jail]
- name: Test Fail2Ban configuration
become: true
ansible.builtin.command: fail2ban-client -t
changed_when: false
check_mode: false
tags: [fail2ban, fail2ban_service_jail]
-13
View File
@@ -1,13 +0,0 @@
---
- name: Validate Fail2Ban jails
ansible.builtin.assert:
that:
- item.name is defined
- item.enabled is defined
- item.filter is defined
- item.logpath is defined or item.journalmatch is defined or item.backend | default('') == 'systemd'
- item.maxretry is defined
- item.bantime is defined
- item.findtime is defined
fail_msg: "Invalid Fail2Ban jail: {{ item }}"
loop: "{{ fail2ban_jails }}"
-21
View File
@@ -1,21 +0,0 @@
# Managed by Ansible - Fail2Ban jail.local
{% for jail in fail2ban_jails %}
[{{ jail.name }}]
enabled = {{ jail.enabled | default(true) }}
port = {{ jail.port | default('any') }}
filter = {{ jail.filter | default(jail.name) }}
{% if jail.backend is defined or jail.journalmatch is defined %}
backend = {{ jail.backend | default('systemd') }}
{% endif %}
{% if jail.journalmatch is defined %}
journalmatch = {{ jail.journalmatch }}
{% endif %}
{% if (jail.backend | default('systemd' if jail.journalmatch is defined else 'auto')) != 'systemd' %}
logpath = {{ jail.logpath | default('/var/log/auth.log') }}
{% endif %}
maxretry = {{ jail.maxretry | default(fail2ban_defaults.maxretry) }}
bantime = {{ jail.bantime | default(fail2ban_defaults.bantime) }}
findtime = {{ jail.findtime | default(fail2ban_defaults.findtime) }}
{% endfor %}
@@ -1,14 +0,0 @@
# Managed by Ansible - Fail2Ban jail for {{ fail2ban_service_name }}
[{{ fail2ban_service_name }}]
enabled = {{ fail2ban_service_jail.enabled | default(true) | lower }}
port = {{ fail2ban_service_jail.port | default('any') }}
filter = {{ fail2ban_service_jail.filter | default(fail2ban_service_name) }}
{% if fail2ban_service_jail.journalmatch is defined %}
backend = {{ fail2ban_service_jail.backend | default('systemd') }}
journalmatch = {{ fail2ban_service_jail.journalmatch }}
{% else %}
logpath = {{ fail2ban_service_jail.logpath }}
{% endif %}
maxretry = {{ fail2ban_service_jail.maxretry | default(fail2ban_defaults.maxretry) }}
bantime = {{ fail2ban_service_jail.bantime | default(fail2ban_defaults.bantime) }}
findtime = {{ fail2ban_service_jail.findtime | default(fail2ban_defaults.findtime) }}
-60
View File
@@ -1,60 +0,0 @@
# network_interfaces
Renders `/etc/network/interfaces` from a list of manual interfaces and bridges, validates it with `ifreload`, and restores the backup if validation fails. Variables and their types are defined in [`meta/argument_specs.yml`](meta/argument_specs.yml), which is the source of truth.
## Supported platforms
Debian-based hosts using `ifupdown2` (`ifreload`), such as Proxmox hosts. The molecule scenario (`molecule/default/`, CI only) runs on Ubuntu 24.04 without `ifupdown2`: the validate and reload commands are stubs, so it tests the rendered file, the backup, the single reload and the restore after a failing validation. It does not test `ifreload`, so no Debian release or `ifupdown2` version is verified by a test.
## Requirements and run order
- `ifupdown2` must be installed, because the validate and apply commands call `ifreload`.
- Use it by its fully qualified name, `mortis.kamino.network_interfaces`.
- Run it with `serial: 1` and the most important host last, so a bad change is caught on another host first. It rewrites the host's network configuration, so run it before roles that depend on the network.
- Gathered facts are not read. The tasks use `become` where they write.
- `network_interfaces_layout` normally comes from inventory (group_vars or host_vars), so each host can have its own layout.
## Role variables
| Variable | Default | Required | Description |
|---|---|---|---|
| `network_interfaces_layout` | `manual: []`, `bridges: []` | no | `manual` is a list of interface names. `bridges` is a list of mappings with `name`, `method`, `address`, `netmask`, `gateway`, `ports`, `stp`, `fd`, `vlan_aware`, `vlan_ids`. |
| `network_interfaces_file` | `/etc/network/interfaces` | no | File rewritten. |
| `network_interfaces_backup` | `/etc/network/interfaces.bak` | no | Backup path. |
| `network_interfaces_validate_command` | `ifreload -s -a` | no | Validation command. |
| `network_interfaces_apply_command` | `ifreload -a` | no | Reload command, run by the handler. |
The `address` sub-option is typed `raw` in the spec so that an inventory can template it, for example from `ansible_host`.
## Tags
None. The role does not tag its tasks, so only a play-level tag applies.
## Example play
```yaml
- hosts: hypervisors
serial: 1
roles:
- role: mortis.kamino.network_interfaces
vars:
network_interfaces_layout:
manual: [nic0, nic1]
bridges:
- name: vmbr0
method: static
address: 192.0.2.10
netmask: 255.255.255.0
gateway: 192.0.2.1
ports: nic0
vlan_aware: true
```
## Notes
- The template replaces the whole file: any stanza not described by `network_interfaces_layout` is dropped. Interfaces carried by other consumers (for example a bridge that carries a router VM's WAN) must be listed.
- Only a content difference triggers work. Idempotent runs change nothing.
- On change the order is: copy the current file to `network_interfaces_backup`, write the new file (notifies `Reload Interfaces`), run the validate command, flush handlers. Any failure in that block restores the backup and fails with "Invalid network configuration detected. Previous config restored." The restore does not reload the interfaces.
- The validate command runs after the file is written, and the reload runs right after it. A configuration that passes validation but breaks connectivity is not detected.
- With `method: static`, `address` and `netmask` are required by the template.
- `no_log` is not used: the role handles no secrets.
@@ -1,9 +0,0 @@
---
network_interfaces_layout:
manual: []
bridges: []
network_interfaces_file: /etc/network/interfaces
network_interfaces_backup: /etc/network/interfaces.bak
network_interfaces_validate_command: "ifreload -s -a"
network_interfaces_apply_command: "ifreload -a"
@@ -1,5 +0,0 @@
---
- name: Reload Interfaces
become: true
ansible.builtin.command: "{{ network_interfaces_apply_command }}"
changed_when: true
@@ -1,80 +0,0 @@
---
argument_specs:
main:
short_description: Manage /etc/network/interfaces
description:
- >-
Reads the interfaces file, renders it from C(network_interfaces_layout), and when the content differs backs up the current file, writes the new
one, validates it and reloads. A failed validation restores the backup and fails the play.
- Needs C(ifupdown2), because validation and reload use C(ifreload).
options:
network_interfaces_layout:
type: dict
default: {manual: [], bridges: []}
description:
- >-
Desired network layout. The file is fully replaced with a loopback stanza, one C(iface <name> inet manual) per C(manual) entry and one
stanza per bridge. Both keys are optional when the variable is set.
options:
manual:
type: list
elements: str
description: Interface names configured as C(inet manual), without C(auto).
bridges:
type: list
elements: dict
description: Bridges, rendered in order with C(auto <name>).
options:
name:
type: str
required: true
description: Bridge name, for example C(vmbr0).
method:
type: str
description: Address method. The template default is C(manual). With C(static), C(address) and C(netmask) are read unconditionally.
address:
type: raw
description: >-
IP address, only used when C(method) is C(static). Typed raw so that an inventory can template it, for
example from C(ansible_host).
netmask:
type: str
description: Netmask, only used when C(method) is C(static).
gateway:
type: str
description: Default gateway, only used when C(method) is C(static) and the key is present.
ports:
type: str
description: Value of C(bridge_ports). The template default is C(none).
stp:
type: str
description: Value of C(bridge_stp). The template default is C(off). Quote C("off"), because unquoted YAML turns it into a boolean.
fd:
type: raw
description: Value of C(bridge_fd), written only when C(stp) is not C(off). The template default is 2.
vlan_aware:
type: bool
description: Adds C(bridge_vlan_aware yes) and C(bridge_vids). The template default is false.
vlan_ids:
type: str
description: Value of C(bridge_vids) when C(vlan_aware) is true. The template default is C(2-4094).
network_interfaces_file:
type: path
default: /etc/network/interfaces
description:
- File that is read, compared and rewritten.
network_interfaces_backup:
type: path
default: /etc/network/interfaces.bak
description:
- Where the current file is copied before it is replaced, and restored from when validation fails.
network_interfaces_validate_command:
type: str
default: ifreload -s -a
description:
- Command run after the new file is written, in syntax-check mode. A failure triggers the restore.
network_interfaces_apply_command:
type: str
default: ifreload -a
description:
- Command run by the C(Reload Interfaces) handler, which the role flushes right after validation.
-17
View File
@@ -1,17 +0,0 @@
---
galaxy_info:
role_name: network_interfaces
namespace: mortis
author: Defame1297
license: GPL-3.0-or-later
description: Render /etc/network/interfaces for Proxmox hosts from manual and bridge definitions, validate with ifreload and restore the backup on failure.
min_ansible_version: "2.19"
platforms:
- name: Debian
versions:
- all
galaxy_tags:
- network
- bridge
- proxmox
dependencies: []
@@ -1,27 +0,0 @@
---
# ifupdown2 and its ifreload are not in the image, and a real reload could cut the
# container's own network, so the validate command is `true` and the apply command appends
# to a marker file. The role itself (read, render, compare, back up, write, validate,
# flush handlers) runs unchanged.
- name: Converge the role with a layout of manual interfaces and bridges
hosts: all
gather_facts: false
vars:
network_interfaces_validate_command: /bin/true
network_interfaces_apply_command: '/bin/sh -c "echo reloaded >> /var/tmp/network-interfaces-reload.log"'
network_interfaces_layout:
manual: [eno1]
bridges:
- name: vmbr0
method: static
address: 10.0.0.2
netmask: 255.255.255.0
gateway: 10.0.0.1
ports: eno1
stp: "off"
vlan_aware: true
- name: vmbr1
stp: "on"
fd: 5
roles:
- role: mortis.kamino.network_interfaces
@@ -1,26 +0,0 @@
---
# Runs on the repository's own runner (label kamino-molecule), in the molecule-ubuntu2404 image
# (MOLECULE_IMAGE, the pin in .gitea/workflows/molecule.yml). No privileged mode: systemd needs a
# writable cgroup and the firewall tools need NET_ADMIN, nothing else.
driver:
name: docker
platforms:
- name: network-interfaces-instance
image: ${MOLECULE_IMAGE}
pre_build_image: true
pull: true
command: /sbin/init
cgroupns_mode: host
volumes:
- /sys/fs/cgroup:/sys/fs/cgroup:rw
tmpfs:
- /run
- /run/lock
capabilities:
- NET_ADMIN
security_opts:
- apparmor=unconfined
provisioner:
name: ansible
verifier:
name: ansible
@@ -1,29 +0,0 @@
---
# The role slurps the interfaces file before it compares, so the file must exist, and the
# image has no /etc/network. Both files get a legacy body that differs from anything the
# template renders, so the converge has a change to make and a backup to take.
- name: Prepare
hosts: all
gather_facts: false
tasks:
- name: Create /etc/network
ansible.builtin.file:
path: /etc/network
state: directory
owner: root
group: root
mode: "0755"
- name: Seed the interfaces files with a legacy body
ansible.builtin.copy:
dest: "{{ item }}"
content: |
# legacy seed
auto lo
iface lo inet loopback
owner: root
group: root
mode: "0644"
loop:
- /etc/network/interfaces
- /etc/network/interfaces.rollback
@@ -1,102 +0,0 @@
---
# The rendered file, the backup of the legacy body and the single reload. The last play is the
# role's lock-out protection: a failing validation must put the previous file back. It
# changes the container, so it lives here and not in converge.yml, where the idempotence
# run would see it change twice. It works on its own copy of the file.
- name: Verify the converged layout
hosts: all
gather_facts: false
tasks:
- name: Read the interfaces file, its backup and the reload marker
ansible.builtin.slurp:
src: "{{ item }}"
loop:
- /etc/network/interfaces
- /etc/network/interfaces.bak
- /var/tmp/network-interfaces-reload.log
register: network_interfaces_verify_files
- name: The file holds the loopback, the manual interface and both bridges
ansible.builtin.assert:
that:
- lines is contains('iface lo inet loopback')
- lines is contains('iface eno1 inet manual')
- lines is contains('auto vmbr0')
- lines is contains('iface vmbr0 inet static')
- lines is contains(' address 10.0.0.2')
- lines is contains(' netmask 255.255.255.0')
- lines is contains(' gateway 10.0.0.1')
- lines is contains(' bridge_ports eno1')
- lines is contains(' bridge_stp off')
- lines is contains(' bridge_vlan_aware yes')
- lines is contains(' bridge_vids 2-4094')
- lines is contains('auto vmbr1')
- lines is contains('iface vmbr1 inet manual')
- lines is contains(' bridge_ports none')
- lines is contains(' bridge_stp on')
- lines is contains(' bridge_fd 5')
- lines | select('search', 'bridge_fd') | list | length == 1
- lines | select('search', 'bridge_vlan_aware') | list | length == 1
- "'legacy seed' not in content"
quiet: true
vars:
content: "{{ network_interfaces_verify_files.results[0].content | b64decode }}"
lines: "{{ content.split('\n') }}"
- name: The backup is the legacy body and the reload ran once
ansible.builtin.assert:
that:
- "'# legacy seed' in (network_interfaces_verify_files.results[1].content | b64decode)"
- "'vmbr0' not in (network_interfaces_verify_files.results[1].content | b64decode)"
- (network_interfaces_verify_files.results[2].content | b64decode).split('\n') | select | list | length == 1
quiet: true
- name: A failing validation restores the previous file
hosts: all
gather_facts: false
vars:
network_interfaces_file: /etc/network/interfaces.rollback
network_interfaces_backup: /etc/network/interfaces.rollback.bak
network_interfaces_validate_command: /bin/false
# A handler notified by the write is still pending when the block is rescued, and it
# runs at the end of the play, so it must not touch the reload marker.
network_interfaces_apply_command: /bin/true
network_interfaces_layout:
manual: [eno1]
bridges:
- name: vmbr9
tasks:
- name: Read the file before
ansible.builtin.slurp:
src: /etc/network/interfaces.rollback
register: network_interfaces_verify_before
- name: Apply the role with a validation that fails
block:
- name: Include the role
ansible.builtin.include_role:
name: mortis.kamino.network_interfaces
- name: Fail when the invalid configuration was accepted
ansible.builtin.fail:
msg: MOLECULE-ACCEPTED
rescue:
- name: The role reverted and refused
ansible.builtin.assert:
that: "'Previous config restored' in ansible_failed_result.msg | default('')"
quiet: true
- name: Read the file and the backup after
ansible.builtin.slurp:
src: "{{ item }}"
loop:
- /etc/network/interfaces.rollback
- /etc/network/interfaces.rollback.bak
register: network_interfaces_verify_after
- name: The previous file is back and the bad one is gone
ansible.builtin.assert:
that:
- network_interfaces_verify_after.results[0].content == network_interfaces_verify_before.content
- network_interfaces_verify_after.results[1].content == network_interfaces_verify_before.content
- "'vmbr9' not in (network_interfaces_verify_after.results[0].content | b64decode)"
quiet: true
-33
View File
@@ -1,33 +0,0 @@
---
- name: Apply network configuration safely
become: true
when: network_interfaces_changed
block:
- name: Backup current interfaces file
ansible.builtin.copy:
src: "{{ network_interfaces_file }}"
dest: "{{ network_interfaces_backup }}"
remote_src: true
owner: root
group: root
mode: "0644"
- name: Write new interfaces configuration
ansible.builtin.copy:
content: "{{ network_interfaces_rendered }}"
dest: "{{ network_interfaces_file }}"
owner: root
group: root
mode: "0644"
notify: Reload Interfaces
- name: Validate network configuration
ansible.builtin.command: "{{ network_interfaces_validate_command }}"
changed_when: false
- name: Trigger network reload
ansible.builtin.meta: flush_handlers
rescue:
- name: Revert interfaces
ansible.builtin.import_tasks: revert.yml
-9
View File
@@ -1,9 +0,0 @@
---
- name: Read current network configuration
ansible.builtin.import_tasks: read.yml
- name: Render desired network configuration
ansible.builtin.import_tasks: render.yml
- name: Apply network configuration if changed
ansible.builtin.import_tasks: apply.yml
-5
View File
@@ -1,5 +0,0 @@
---
- name: Read current interfaces config
ansible.builtin.slurp:
src: "{{ network_interfaces_file }}"
register: network_interfaces_current
@@ -1,9 +0,0 @@
---
- name: Render interfaces template
ansible.builtin.set_fact:
network_interfaces_rendered: "{{ lookup('template', 'interfaces.j2') }}"
- name: Detect interface configuration changes
ansible.builtin.set_fact:
network_interfaces_changed: >-
{{ network_interfaces_rendered != (network_interfaces_current.content | b64decode) }}
-13
View File
@@ -1,13 +0,0 @@
---
- name: Restore previous interfaces configuration
ansible.builtin.copy:
src: "{{ network_interfaces_backup }}"
dest: "{{ network_interfaces_file }}"
remote_src: true
owner: root
group: root
mode: "0644"
- name: Abort due to invalid network configuration
ansible.builtin.fail:
msg: "Invalid network configuration detected. Previous config restored."
@@ -1,36 +0,0 @@
# Managed by Ansible – DO NOT EDIT
# Loopback
auto lo
iface lo inet loopback
# Manual interfaces
{% for iface in network_interfaces_layout.manual | default([]) %}
iface {{ iface }} inet manual
{% endfor %}
# Bridges
{% for br in network_interfaces_layout.bridges | default([]) %}
auto {{ br.name }}
iface {{ br.name }} inet {{ br.method | default('manual') }}
{% if br.method | default('manual') == 'static' %}
address {{ br.address }}
netmask {{ br.netmask }}
{% if br.gateway is defined %}
gateway {{ br.gateway }}
{% endif %}
{% endif %}
{% if br.ports is defined %}
bridge_ports {{ br.ports }}
{% else %}
bridge_ports none
{% endif %}
bridge_stp {{ br.stp | default('off') }}
{% if br.stp | default('off') != 'off' %}
bridge_fd {{ br.fd | default(2) }}
{% endif %}
{% if br.vlan_aware | default(false) %}
bridge_vlan_aware yes
bridge_vids {{ br.vlan_ids | default('2-4094') }}
{% endif %}
{% endfor %}
-102
View File
@@ -1,102 +0,0 @@
# system_baseline
Applies an OS baseline chosen by `system_baseline_system_type`: apt upgrade, package install and removal, unattended-upgrades, locale, timezone, a journal size cap, sysctl hardening, tmpfs mounts and an optional reboot. Variables and their types are defined in [`meta/argument_specs.yml`](meta/argument_specs.yml), which is the source of truth.
## Supported platforms
Ubuntu 24.04 (noble, covered by the molecule scenario), Ubuntu 22.04 (jammy) and Debian 13 (trixie, Proxmox hosts). The tasks use apt and the reboot check is limited to the Debian family. See `meta/main.yml`. The molecule scenario (`molecule/default/`, CI only) converges the `ubuntu_lxc` profile on Ubuntu 24.04 and only resolves the `pve` and `ubuntu_vm` profiles; Ubuntu 22.04 and Debian 13 are not verified by a test.
## Requirements and run order
- Facts must be gathered (`gather_facts: true`); `reboot.yml` reads `ansible_os_family`.
- `system_baseline_system_type` is required and has no default (the role does not read a global such as `system_type`; map it in the inventory). Valid values: `ubuntu_lxc`, `ubuntu_vm` or `pve`.
- Use it by its fully qualified name, `mortis.kamino.system_baseline`.
- Collections: `community.general` (locale, timezone) and `ansible.posix` (sysctl, mount).
- Run it after the roles that manage users and SSH, and before the roles that harden services and manage firewalls and jails. A firewall role that rewrites sysctl values (ufw re-applies its stock `/etc/ufw/sysctl.conf` when it is enabled) must run after this role and needs the same values as this role's `sysctl_hardening` to keep them.
- The role has no declared dependencies.
## Role variables
The resolved `system_baseline_*` inputs derived from the active profile (`_profile`, `_essential_packages`, `_remove_packages`, `_apt_periodic_settings`,
`_unattended_upgrade_settings`, `_sysctl_hardening`, `_secure_tmp_mounts`) are listed below but
deliberately not in the spec: their defaults index the profile by `system_baseline_system_type`, and the spec is
templated before `validate.yml` runs, so an invalid `system_baseline_system_type` would otherwise fail with a
templating error instead of the role's own message.
| Name | Default | Required | Description |
| --- | --- | --- | --- |
| `system_baseline_system_type` | none | yes | Profile selector, validated by `tasks/validate.yml` |
| `system_baseline_profiles` | see `defaults/main.yml` | no | Policy per system type; overriding replaces all profiles |
| `system_baseline_profile_overrides` | `{}` | no | Per-system-type overrides, merged recursively into the active profile |
| `system_baseline_profile` | derived | no | Active profile after overrides |
| `system_baseline_essential_packages` | from profile | no | Packages to install |
| `system_baseline_remove_packages` | from profile | no | Packages to purge when present |
| `system_baseline_apt_periodic_settings` | from profile | no | Keys for `20auto-upgrades` |
| `system_baseline_unattended_upgrade_settings` | from profile | no | Keys for `50unattended-upgrades` |
| `system_baseline_sysctl_hardening` | from profile | no | List of `name` and `value` sysctl pairs |
| `system_baseline_secure_tmp_mounts` | from profile | no | Paths remounted as tmpfs with `noexec,nosuid,nodev` |
| `system_baseline_journal_max_use` | `200M` | no | Upper bound of the persistent journal (journald `SystemMaxUse`). |
| `system_baseline_timezone` | `Etc/UTC` | no | Timezone |
| `system_baseline_locale` | `en_US.UTF-8` | no | Locale |
| `system_baseline_reboot_if_required` | `true` | no | Reboot when `/var/run/reboot-required` exists |
A flat `system_baseline_*` input replaces that value entirely. To change one key of a profile dict, use `system_baseline_profile_overrides`, for example to let unattended-upgrades reboot a group on its own:
```yaml
system_baseline_profile_overrides:
ubuntu_vm:
unattended_upgrade_settings:
"Unattended-Upgrade::Automatic-Reboot": true
```
## Entry points
Besides `main`, two task files are a supported interface, for a caller that drives its own reboot (for example a Kubernetes node patch flow that cordons and drains first). Their names, the fact name and the behaviour below follow the Collection's semantic versioning: changing them is a breaking change.
- `tasks_from: update`: apt update, upgrade, autoremove and autoclean, nothing else.
- `tasks_from: reboot`: sets the fact `system_baseline_reboot_required` (bool, from `/var/run/reboot-required`) on Debian family hosts, then reboots when `system_baseline_reboot_if_required` is true and the fact is true. With `system_baseline_reboot_if_required: false` it only computes the fact. On other families the fact is not set, so read it with `default(false)`.
```yaml
- name: Upgrade packages
ansible.builtin.import_role:
name: mortis.kamino.system_baseline
tasks_from: update
- name: Check whether a reboot is required
ansible.builtin.import_role:
name: mortis.kamino.system_baseline
tasks_from: reboot
vars:
system_baseline_reboot_if_required: false
- name: Reboot after draining
ansible.builtin.reboot:
when: system_baseline_reboot_required | default(false)
```
`validate.yml` has no spec and is not an entry point; the molecule scenario calls it to load the defaults.
## Tags
`always` (validation), `update` (apt upgrade and the reboot), `packages`, `unattended-upgrades`, `locale`, `timezone`, `journald`, `sysctl`, `secure_tmp`.
## Example play
```yaml
- name: Baseline LXC guests
hosts: lxc_guests
gather_facts: true
vars:
system_baseline_system_type: ubuntu_lxc
roles:
- role: mortis.kamino.system_baseline
```
## Notes
- The `pve` profile has no `ufw`; the `ubuntu_*` profiles install it and `fail2ban`.
- No profile lets unattended-upgrades reboot on its own (`Automatic-Reboot: false`); a host opts in through `system_baseline_profile_overrides`.
- Set `system_baseline_reboot_if_required: false` for hosts whose reboot takes other machines down (hypervisors) or needs a drain first (cluster nodes).
- Molecule skips `sysctl`, `secure_tmp`, `update` and `timezone` (no privileged container); see `molecule/default/molecule.yml`.
- Policy lives in defaults, not `vars/`, so group_vars and host_vars can override it.
- `no_log` is not used: the role handles no secrets.
-206
View File
@@ -1,206 +0,0 @@
---
# General defaults for all system types
# timedatectl reports the canonical name; "UTC" would show as changed on every run.
system_baseline_timezone: "Etc/UTC"
system_baseline_locale: "en_US.UTF-8"
system_baseline_reboot_if_required: true
# Upper bound of the persistent journal (journald SystemMaxUse); older archived files are removed above it.
system_baseline_journal_max_use: 200M
# Per-system_type policy. Everything below is a role default, so group_vars and host_vars
# override it with normal Ansible precedence.
#
# How to override:
# - A flat input (for example system_baseline_essential_packages) replaces that value
# entirely. Lists and dicts are replaced, not merged.
# - system_baseline_profile_overrides merges recursively into the active profile, keyed by
# system_type, so one key of a dict can change without repeating the rest:
# system_baseline_profile_overrides:
# ubuntu_vm:
# unattended_upgrade_settings:
# "Unattended-Upgrade::Automatic-Reboot": true
# (the ubuntu_vm profile does not reboot on its own; a host opts in this way)
# Lists inside it are still replaced.
# Never reference a flat input inside the profiles: the chain is one-way
# (profiles -> profile -> flat inputs).
system_baseline_profiles:
pve:
essential_packages:
- vim
- htop
- curl
- wget
# - ufw
- fail2ban
- smartmontools
- etckeeper
- lvm2
- jq
- python3-pip
- apt-transport-https
- ca-certificates
- gnupg
- unattended-upgrades
remove_packages:
- telnet
- ftp
- xinetd
- samba
- whoopsie
- modemmanager
- snapd
apt_periodic_settings:
"APT::Periodic::Update-Package-Lists": true
"APT::Periodic::Download-Upgradeable-Packages": true
"APT::Periodic::AutocleanInterval": 7
"APT::Periodic::Unattended-Upgrade": true
unattended_upgrade_settings:
"Unattended-Upgrade::Automatic-Reboot": false
"Unattended-Upgrade::Automatic-Reboot-Time": "03:00"
"Unattended-Upgrade::Remove-Unused-Dependencies": true
"Unattended-Upgrade::MinimalSteps": true
sysctl_hardening:
- { name: "net.ipv4.tcp_syncookies", value: 1 }
- { name: "kernel.randomize_va_space", value: 2 }
- { name: "net.ipv4.conf.all.accept_source_route", value: 0 }
- { name: "net.ipv4.conf.all.accept_redirects", value: 0 }
- { name: "net.ipv4.conf.all.secure_redirects", value: 0 }
- { name: "net.ipv4.icmp_echo_ignore_broadcasts", value: 1 }
- { name: "net.ipv4.icmp_ignore_bogus_error_responses", value: 1 }
- { name: "net.ipv4.conf.all.log_martians", value: 1 }
- { name: "vm.swappiness", value: 10 }
secure_tmp_mounts:
- /dev/shm
- /tmp
- /var/tmp
ubuntu_lxc:
essential_packages:
- logrotate
- vim
- curl
- wget
- git
- htop
- ufw
- fail2ban
- unattended-upgrades
- net-tools
- iproute2
- cron
- apt-transport-https
- ca-certificates
- gnupg
remove_packages:
- snapd
- cloud-init
- whoopsie
- modemmanager
- popularity-contest
- telnet
- ftp
- xinetd
- samba
- avahi-daemon
apt_periodic_settings:
"APT::Periodic::Update-Package-Lists": true
"APT::Periodic::Download-Upgradeable-Packages": true
"APT::Periodic::AutocleanInterval": 7
"APT::Periodic::Unattended-Upgrade": true
unattended_upgrade_settings:
"Unattended-Upgrade::Automatic-Reboot": false
"Unattended-Upgrade::Automatic-Reboot-Time": "05:00"
"Unattended-Upgrade::Remove-Unused-Dependencies": true
"Unattended-Upgrade::MinimalSteps": true
sysctl_hardening:
- { name: "net.ipv4.tcp_syncookies", value: 1 }
- { name: "net.ipv4.conf.all.accept_source_route", value: 0 }
- { name: "net.ipv4.conf.all.accept_redirects", value: 0 }
- { name: "net.ipv4.conf.all.secure_redirects", value: 0 }
- { name: "net.ipv4.icmp_echo_ignore_broadcasts", value: 1 }
- { name: "net.ipv4.icmp_ignore_bogus_error_responses", value: 1 }
secure_tmp_mounts:
- /dev/shm
ubuntu_vm:
essential_packages:
- qemu-guest-agent
- logrotate
- vim
- curl
- wget
- git
- htop
- ufw
- fail2ban
- unattended-upgrades
- etckeeper
- ncdu
- software-properties-common
- net-tools
- python3-pip
- lsof
- apt-transport-https
- ca-certificates
- gnupg
remove_packages:
- telnet
- ftp
- xinetd
- snapd
- modemmanager
- whoopsie
- popularity-contest
apt_periodic_settings:
"APT::Periodic::Update-Package-Lists": true
"APT::Periodic::Download-Upgradeable-Packages": true
"APT::Periodic::AutocleanInterval": 7
"APT::Periodic::Unattended-Upgrade": true
unattended_upgrade_settings:
"Unattended-Upgrade::Automatic-Reboot": false
"Unattended-Upgrade::Automatic-Reboot-Time": "04:00"
"Unattended-Upgrade::Remove-Unused-Dependencies": true
"Unattended-Upgrade::MinimalSteps": true
sysctl_hardening:
- { name: "net.ipv4.tcp_syncookies", value: 1 }
- { name: "kernel.randomize_va_space", value: 2 }
- { name: "net.ipv4.conf.all.accept_source_route", value: 0 }
- { name: "net.ipv4.conf.all.accept_redirects", value: 0 }
- { name: "net.ipv4.conf.all.secure_redirects", value: 0 }
- { name: "net.ipv4.icmp_echo_ignore_broadcasts", value: 1 }
- { name: "net.ipv4.icmp_ignore_bogus_error_responses", value: 1 }
- { name: "net.ipv4.conf.all.log_martians", value: 1 }
secure_tmp_mounts:
- /dev/shm
# Sparse per-system_type overrides, merged recursively into the active profile.
system_baseline_profile_overrides: {}
# Selects the profile. system_baseline_system_type is a required input with no default,
# validated by tasks/validate.yml (map the inventory's system type onto it).
system_baseline_profile: >-
{{ system_baseline_profiles[system_baseline_system_type]
| combine(system_baseline_profile_overrides[system_baseline_system_type] | default({}), recursive=True) }}
# Inputs the tasks read
system_baseline_essential_packages: "{{ system_baseline_profile.essential_packages }}"
system_baseline_remove_packages: "{{ system_baseline_profile.remove_packages }}"
system_baseline_apt_periodic_settings: "{{ system_baseline_profile.apt_periodic_settings }}"
system_baseline_unattended_upgrade_settings: "{{ system_baseline_profile.unattended_upgrade_settings }}"
system_baseline_sysctl_hardening: "{{ system_baseline_profile.sysctl_hardening }}"
system_baseline_secure_tmp_mounts: "{{ system_baseline_profile.secure_tmp_mounts }}"
-16
View File
@@ -1,16 +0,0 @@
---
- name: Update locale
ansible.builtin.command: update-locale LANG={{ system_baseline_locale }}
become: true
changed_when: false
- name: Reload systemd-timedatectl
ansible.builtin.command: timedatectl set-timezone {{ system_baseline_timezone }}
become: true
changed_when: false
- name: Restart systemd-journald
become: true
ansible.builtin.systemd:
name: systemd-journald
state: restarted
@@ -1,84 +0,0 @@
---
argument_specs:
main:
short_description: Apply the OS baseline for a system type
description:
- >-
Validates C(system_baseline_system_type), then runs the update, packages, unattended-upgrades, locale, timezone, journald,
sysctl, tmpfs and reboot task files, in that order.
- Needs gathered facts, because the reboot check reads C(ansible_os_family).
- >-
The resolved inputs C(system_baseline_profile), C(system_baseline_essential_packages),
C(system_baseline_remove_packages), C(system_baseline_apt_periodic_settings), C(system_baseline_unattended_upgrade_settings),
C(system_baseline_sysctl_hardening) and C(system_baseline_secure_tmp_mounts) are deliberately not listed. Their defaults are
Jinja that indexes C(system_baseline_profiles) with C(system_baseline_system_type), and the argument spec is validated (templated) before
tasks/validate.yml runs, so listing them would fail on an invalid C(system_baseline_system_type) with a templating error ahead of the
role's own C(is invalid) message. They are derived from the profile and may be set directly to replace one resolved value
(a list or dict, for example C(system_baseline_remove_packages)).
options:
system_baseline_system_type:
type: str
required: true
description:
- >-
Selects the profile in C(system_baseline_profiles). One of C(ubuntu_vm), C(ubuntu_lxc) or C(pve); any other value is
refused by tasks/validate.yml.
- Not restricted by C(choices) so that the refusal keeps its own message.
system_baseline_profiles:
type: dict
description:
- >-
Policy per system type. Each profile holds C(essential_packages), C(remove_packages), C(apt_periodic_settings),
C(unattended_upgrade_settings), C(sysctl_hardening) and C(secure_tmp_mounts).
- Overriding it replaces all profiles. To change part of one profile use C(system_baseline_profile_overrides).
system_baseline_profile_overrides:
type: dict
default: {}
description:
- Sparse overrides keyed by system type and merged recursively into the active profile. Lists inside it are replaced, not merged.
system_baseline_journal_max_use:
type: str
default: 200M
description:
- Upper bound of the persistent systemd journal (journald C(SystemMaxUse), for example C(200M)).
- Written to a drop-in under C(/etc/systemd/journald.conf.d).
system_baseline_timezone:
type: str
default: Etc/UTC
description:
- Timezone name as reported by C(timedatectl).
system_baseline_locale:
type: str
default: en_US.UTF-8
description:
- Locale generated and set as C(LANG).
system_baseline_reboot_if_required:
type: bool
default: true
description:
- Reboot when C(/var/run/reboot-required) exists after the run.
update:
short_description: Update and upgrade apt packages
description:
- Runs an apt update, upgrade, autoremove and autoclean, and nothing else.
- >-
A supported entry point (C(tasks_from=update)) for a caller that drives its own reboot, for example a
Kubernetes node patch flow that drains the node first.
reboot:
short_description: Compute system_baseline_reboot_required and reboot when allowed
description:
- >-
Sets the C(system_baseline_reboot_required) fact from C(/var/run/reboot-required) on Debian family hosts, then reboots when
C(system_baseline_reboot_if_required) is true and the fact is true.
- >-
A supported entry point (C(tasks_from=reboot)). With C(system_baseline_reboot_if_required=false) it only computes the fact and
never reboots, so a caller can read C(system_baseline_reboot_required) (bool) and reboot on its own terms, for example after
draining a node. The fact name and this behaviour are part of the role's interface.
- On a non-Debian host the fact is not set; read it with C(default(false)).
- Reads C(ansible_os_family), so facts must be gathered.
options:
system_baseline_reboot_if_required:
type: bool
default: true
description:
- Reboot when a reboot is required.
-21
View File
@@ -1,21 +0,0 @@
---
galaxy_info:
role_name: system_baseline
namespace: mortis
author: Defame1297
license: GPL-3.0-or-later
description: "Per-system-type OS baseline: apt upgrade, packages, unattended-upgrades, locale, timezone, journal cap, sysctl, tmpfs mounts, reboot."
min_ansible_version: "2.19"
platforms:
- name: Ubuntu
versions:
- jammy
- noble
- name: Debian
versions:
- trixie
galaxy_tags:
- baseline
- apt
- security
dependencies: []
@@ -1,97 +0,0 @@
---
- name: Refuse an unknown system_baseline_system_type
hosts: all
gather_facts: false
tasks:
- name: Run the role with a bad system_baseline_system_type
block:
- name: Include system_baseline
ansible.builtin.include_role:
name: mortis.kamino.system_baseline
vars:
system_baseline_system_type: not_a_type
- name: Unreachable when validation works
ansible.builtin.fail:
msg: system_baseline ran with an invalid system_baseline_system_type
rescue:
- name: The validation stopped the play
ansible.builtin.assert:
that: "'is invalid' in ansible_failed_result.msg | default('')"
quiet: true
- name: Converge the LXC profile
hosts: all
gather_facts: true
vars:
system_baseline_system_type: ubuntu_lxc
roles:
- role: mortis.kamino.system_baseline
# The remaining plays only load the role's defaults (validate.yml changes nothing) and assert
# the resolved inputs. They cover the profiles the converge above cannot run.
- name: The pve profile resolves
hosts: all
gather_facts: false
vars:
system_baseline_system_type: pve
tasks:
- name: Load the role defaults
ansible.builtin.include_role:
name: mortis.kamino.system_baseline
tasks_from: validate.yml
public: true
- name: Assert the pve profile
ansible.builtin.assert:
that:
- "'ufw' not in system_baseline_essential_packages"
- "'unattended-upgrades' in system_baseline_essential_packages"
- system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot'] == false
- system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '03:00'
- system_baseline_secure_tmp_mounts == ['/dev/shm', '/tmp', '/var/tmp']
quiet: true
- name: The ubuntu_vm profile resolves
hosts: all
gather_facts: false
vars:
system_baseline_system_type: ubuntu_vm
tasks:
- name: Load the role defaults
ansible.builtin.include_role:
name: mortis.kamino.system_baseline
tasks_from: validate.yml
public: true
- name: Assert the ubuntu_vm profile
ansible.builtin.assert:
that:
- "'qemu-guest-agent' in system_baseline_essential_packages"
- system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot'] == false
- system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '04:00'
- system_baseline_sysctl_hardening | selectattr('name', 'equalto', 'net.ipv4.conf.all.log_martians') | list | length == 1
quiet: true
# Consumer play vars override the profile.
- name: Consumer overrides win over the profile
hosts: all
gather_facts: false
vars:
system_baseline_system_type: ubuntu_vm
system_baseline_remove_packages: [telnet]
system_baseline_profile_overrides:
ubuntu_vm:
unattended_upgrade_settings:
"Unattended-Upgrade::Automatic-Reboot": true
tasks:
- name: Load the role defaults
ansible.builtin.include_role:
name: mortis.kamino.system_baseline
tasks_from: validate.yml
public: true
- name: Assert the overrides
ansible.builtin.assert:
that:
- system_baseline_remove_packages == ['telnet']
- system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot'] == true
- system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '04:00'
- "'qemu-guest-agent' in system_baseline_essential_packages"
quiet: true
@@ -1,33 +0,0 @@
---
# Runs on the repository's own runner (label kamino-molecule), in the molecule-ubuntu2404 image
# (MOLECULE_IMAGE, the pin in .gitea/workflows/molecule.yml). Unlike the other scenarios
# this one installs packages (the role's system_baseline_essential_packages list) from the Ubuntu
# mirrors during prepare and converge, so the runner needs outbound network. No
# privileged mode: systemd needs a writable cgroup and the firewall tools need
# NET_ADMIN, nothing else.
driver:
name: docker
platforms:
- name: system-baseline-instance
image: ${MOLECULE_IMAGE}
pre_build_image: true
pull: true
command: /sbin/init
cgroupns_mode: host
volumes:
- /sys/fs/cgroup:/sys/fs/cgroup:rw
tmpfs:
- /run
- /run/lock
capabilities:
- NET_ADMIN
security_opts:
- apparmor=unconfined
provisioner:
name: ansible
options:
# sysctl and tmpfs mounts need a privileged container; a full upgrade adds only
# time; the timezone needs timedatectl. The rest of the role runs for real.
skip-tags: molecule-notest,notest,sysctl,secure_tmp,update,timezone
verifier:
name: ansible
@@ -1,12 +0,0 @@
---
# A package the role must remove, and the locales tool the role assumes exists
# (it does on a stock Ubuntu host).
- name: Prepare
hosts: all
gather_facts: false
tasks:
- name: Install a package on the role's remove list and locale-gen
ansible.builtin.apt:
name: [telnet, locales]
state: present
update_cache: true
@@ -1,105 +0,0 @@
---
- name: Verify
hosts: all
gather_facts: false
tasks:
- name: Read the installed packages
ansible.builtin.package_facts:
manager: auto
- name: The essential packages are installed and the removed one is gone
ansible.builtin.assert:
that:
- "'ufw' in ansible_facts.packages"
- "'fail2ban' in ansible_facts.packages"
- "'unattended-upgrades' in ansible_facts.packages"
- "'telnet' not in ansible_facts.packages"
quiet: true
- name: Read the journald drop-in
ansible.builtin.slurp:
src: /etc/systemd/journald.conf.d/50-system-baseline.conf
register: system_baseline_verify_journald
- name: The journal size is capped
ansible.builtin.assert:
that:
- system_baseline_verify_journald.content | b64decode is search('(?m)^SystemMaxUse=200M$')
quiet: true
- name: Read the apt configuration the role writes
ansible.builtin.slurp:
src: "{{ item }}"
loop:
- /etc/apt/apt.conf.d/20auto-upgrades
- /etc/apt/apt.conf.d/50unattended-upgrades
register: system_baseline_verify_apt
- name: Automatic upgrades are on and the reboot setting is applied
ansible.builtin.assert:
that:
- system_baseline_verify_apt.results[0].content | b64decode is search('APT::Periodic::Unattended-Upgrade "1";')
- system_baseline_verify_apt.results[1].content | b64decode is search('Unattended-Upgrade::Automatic-Reboot "False";')
- system_baseline_verify_apt.results[1].content | b64decode is search('Unattended-Upgrade::Automatic-Reboot-Time "05:00";')
quiet: true
- name: Read the generated locales
ansible.builtin.command: locale -a
register: system_baseline_verify_locales
changed_when: false
- name: The configured locale exists
ansible.builtin.assert:
that: system_baseline_verify_locales.stdout_lines | map('lower') | map('replace', '-', '') | select('match', 'en_us.utf8') | list | length > 0
quiet: true
# The reboot entry point is a supported interface: with system_baseline_reboot_if_required
# false it only sets system_baseline_reboot_required. Here and not in converge, because it
# creates and removes the marker file, which the idempotence run would report as a change.
# Reaching the assert after the marker exists shows the entry point did not reboot.
- name: The reboot entry point only computes the fact when told not to reboot
hosts: all
gather_facts: true
tasks:
- name: Remove the reboot marker
ansible.builtin.file:
path: /var/run/reboot-required
state: absent
- name: Run the reboot entry point without a pending reboot
ansible.builtin.include_role:
name: mortis.kamino.system_baseline
tasks_from: reboot
vars:
system_baseline_reboot_if_required: false
- name: No reboot is required
ansible.builtin.assert:
that:
- system_baseline_reboot_required is defined
- not system_baseline_reboot_required
quiet: true
- name: Create the reboot marker
ansible.builtin.copy:
dest: /var/run/reboot-required
content: ""
mode: "0644"
- name: Run the reboot entry point with a pending reboot
ansible.builtin.include_role:
name: mortis.kamino.system_baseline
tasks_from: reboot
vars:
system_baseline_reboot_if_required: false
- name: A reboot is required and the host did not reboot
ansible.builtin.assert:
that:
- system_baseline_reboot_required
quiet: true
- name: Remove the reboot marker again
ansible.builtin.file:
path: /var/run/reboot-required
state: absent
-24
View File
@@ -1,24 +0,0 @@
---
# An uncapped persistent journal can fill a small root disk. A drop-in caps it; the cap applies on
# the next journald start, which the handler triggers.
- name: Ensure the journald drop-in directory exists
become: true
ansible.builtin.file:
path: /etc/systemd/journald.conf.d
state: directory
owner: root
group: root
mode: "0755"
- name: Cap the size of the persistent journal
become: true
ansible.builtin.copy:
dest: /etc/systemd/journald.conf.d/50-system-baseline.conf
content: |
# Managed by Ansible (role system_baseline).
[Journal]
SystemMaxUse={{ system_baseline_journal_max_use }}
owner: root
group: root
mode: "0644"
notify: Restart systemd-journald
-7
View File
@@ -1,7 +0,0 @@
---
- name: Set locale
community.general.locale_gen:
name: "{{ system_baseline_locale }}"
state: present
become: true
notify: Update locale
-44
View File
@@ -1,44 +0,0 @@
---
- name: Validate inputs
ansible.builtin.import_tasks: validate.yml
tags: always
- name: Update & Upgrade Dist
ansible.builtin.import_tasks: update.yml
tags: update
- name: Manage packages
ansible.builtin.import_tasks: packages.yml
tags: packages
- name: Configure unattended-upgrades
ansible.builtin.import_tasks: unattended_upgrades.yml
when: "'unattended-upgrades' in system_baseline_essential_packages"
tags: unattended-upgrades
- name: Set locale
ansible.builtin.import_tasks: locale.yml
tags: locale
- name: Set timezone
ansible.builtin.import_tasks: timezone.yml
tags: timezone
- name: Cap the journal size
ansible.builtin.import_tasks: journald.yml
tags: journald
- name: Harden sysctl
ansible.builtin.import_tasks: sysctl.yml
tags: sysctl
- name: Secure temporary filesystems
ansible.builtin.import_tasks: secure_tmp.yml
tags: secure_tmp
- name: Reboot if required
ansible.builtin.import_tasks: reboot.yml
tags: update
- name: Flush handlers early
ansible.builtin.meta: flush_handlers
-21
View File
@@ -1,21 +0,0 @@
---
- name: Install essential packages
ansible.builtin.package:
name: "{{ system_baseline_essential_packages }}"
state: present
update_cache: true
become: true
- name: Gather installed packages
ansible.builtin.package_facts:
manager: auto
become: true
- name: Remove unnecessary packages if installed
ansible.builtin.package:
name: "{{ item }}"
state: absent
purge: true
loop: "{{ system_baseline_remove_packages }}"
when: item in ansible_facts.packages
become: true
-20
View File
@@ -1,20 +0,0 @@
---
- name: Check if reboot required (Debian)
when: ansible_os_family == "Debian"
block:
- name: Check if reboot is required (Debian)
ansible.builtin.stat:
path: /var/run/reboot-required
register: system_baseline_reboot_required_file
- name: Set system_baseline_reboot_required fact
ansible.builtin.set_fact:
system_baseline_reboot_required: "{{ system_baseline_reboot_required_file.stat.exists }}"
- name: Reboot the server if required
ansible.builtin.reboot:
reboot_timeout: 900
become: true
when:
- system_baseline_reboot_if_required
- system_baseline_reboot_required | default(false)
@@ -1,11 +0,0 @@
---
- name: Secure temporary filesystems
become: true
ansible.posix.mount:
path: "{{ item }}"
src: tmpfs
fstype: tmpfs
opts: defaults,noexec,nosuid,nodev
state: mounted
loop: "{{ system_baseline_secure_tmp_mounts }}"
when: system_baseline_secure_tmp_mounts | length > 0
-9
View File
@@ -1,9 +0,0 @@
---
- name: Apply sysctl hardening settings
ansible.posix.sysctl:
name: "{{ item.name }}"
value: "{{ item.value }}"
sysctl_set: true
reload: true
loop: "{{ system_baseline_sysctl_hardening }}"
become: true
-7
View File
@@ -1,7 +0,0 @@
---
- name: Set timezone
community.general.timezone:
name: "{{ system_baseline_timezone }}"
become: true
notify:
- Reload systemd-timedatectl
@@ -1,29 +0,0 @@
---
- name: Apply APT periodic settings (20auto-upgrades)
become: true
ansible.builtin.lineinfile:
path: /etc/apt/apt.conf.d/20auto-upgrades
regexp: "^(//\\s*)?{{ item.key }}"
line: '{{ item.key }} "{{ 1 if item.value else 0 }}";'
state: present
create: true
mode: "0644"
loop: "{{ system_baseline_apt_periodic_settings | dict2items }}"
- name: Apply unattended-upgrades settings (50unattended-upgrades)
become: true
ansible.builtin.lineinfile:
path: /etc/apt/apt.conf.d/50unattended-upgrades
state: present
create: true
regexp: "^(//|#\\s*)?{{ item.key }}(\\s+).*"
line: '{{ item.key }} "{{ item.value }}";'
mode: "0644"
loop: "{{ system_baseline_unattended_upgrade_settings | dict2items }}"
- name: Validate unattended-upgrades config
become: true
ansible.builtin.command: unattended-upgrades --dry-run --debug
register: system_baseline_unattended_check
changed_when: false
failed_when: system_baseline_unattended_check.rc != 0
-9
View File
@@ -1,9 +0,0 @@
---
- name: Update & upgrade apt packages
ansible.builtin.package:
update_cache: true
upgrade: true
autoremove: true
autoclean: true
cache_valid_time: 3600
become: true
-19
View File
@@ -1,19 +0,0 @@
---
# Required input with no default: the role does not read a global such as system_type;
# the inventory maps it onto system_baseline_system_type.
- name: Require system_baseline_system_type
ansible.builtin.assert:
that:
- system_baseline_system_type is defined
fail_msg: >-
system_baseline_system_type is required and has no default. Set it in
the play or the inventory.
tags: always
- name: Validate system_baseline_system_type variable
ansible.builtin.assert:
that:
- system_baseline_system_type in ['ubuntu_vm', 'ubuntu_lxc', 'pve']
fail_msg: "system_baseline_system_type '{{ system_baseline_system_type }}' is invalid. Must be: ubuntu_vm, ubuntu_lxc, pve."
success_msg: "system_baseline_system_type '{{ system_baseline_system_type }}' is valid."
tags: always
-56
View File
@@ -1,56 +0,0 @@
# systemd_hardening
Disables and masks risky services, writes a systemd manager hardening drop-in and renders opt-in per-service sandboxing drop-ins. Variables and their types are defined in [`meta/argument_specs.yml`](meta/argument_specs.yml), which is the source of truth.
## Supported platforms
Hosts with systemd and `systemctl list-unit-files`: Ubuntu 24.04 (noble) LXCs, Ubuntu 22.04 (jammy) VMs and Debian 13 (trixie) Proxmox hosts. The role is applied to the three system types in `systemd_hardening_profiles`: `pve` (Proxmox hosts), `ubuntu_lxc` and `ubuntu_vm`. The molecule scenario (`molecule/default/`, CI only) runs the `ubuntu_lxc` profile on Ubuntu 24.04 against stub unit files, because the test image installs none of the services the role disables or masks. It checks the disable and mask results, the manager and service drop-ins (loaded by systemd after the reload) and the refusals; it cannot show that a real `rpcbind` or similar stops. The `pve` and `ubuntu_vm` profiles and Ubuntu 22.04 and Debian 13 are not verified by a test.
## Requirements and run order
- `systemd_hardening_system_type` is required and has no default (the role does not read a global such as `system_type`; map it in the inventory). The role fails if it is undefined or not a key of `systemd_hardening_profiles`.
- Use it by its fully qualified name, `mortis.kamino.systemd_hardening`.
- Run it after your baseline role and before the roles that manage firewalls and jails.
- Needs privilege escalation: tasks use `become`.
## Role variables
Two variables below, `systemd_hardening_disable_services_extra` and `systemd_hardening_disable_services_effective`, are deliberately not in the spec: their defaults index the profile by `systemd_hardening_system_type`, and the spec is templated before the role's assert runs, so an invalid `systemd_hardening_system_type` would otherwise fail with a templating error instead of the role's own message.
| Variable | Default | Required | Description |
|---|---|---|---|
| `systemd_hardening_system_type` | none | yes | Profile key. Every play that includes the role sets it. |
| `systemd_hardening_profiles` | `pve`, `ubuntu_lxc`, `ubuntu_vm` profiles | no | Per type `disable_services_extra`. Overriding replaces all profiles. |
| `systemd_hardening_disable_services` | `rpcbind`, `avahi-daemon`, `cups`, `bluetooth`, `nfs-server` | no | Disabled on every type. |
| `systemd_hardening_disable_services_extra` | profile entry for `systemd_hardening_system_type` | no | Added to the list above. |
| `systemd_hardening_disable_services_effective` | base plus extra | no | Result, do not set. |
| `systemd_hardening_mask_services` | `telnet`, `rsh`, `rlogin`, `xinetd` | no | Masked. |
| `systemd_hardening_services` | `{}` | no | Unit to directive map for drop-ins. |
## Tags
Only `always` (the `systemd_hardening_system_type` assert) works as intended. `disable`, `mask`, `harden-manager` and `dropins` sit on the `include_tasks` lines in `tasks/main.yml`, and tags on a dynamic include select only the include itself: the included tasks are untagged, so they are skipped. `--tags disable` or `--tags mask` therefore runs only the assert and the unit listing, and `--tags harden-manager` or `--tags dropins` runs only the assert. Do not use these tags for selective runs; run the role untagged.
## Example play
```yaml
- name: Harden LXC services
hosts: lxc_guests
vars:
systemd_hardening_system_type: ubuntu_lxc
roles:
- role: mortis.kamino.systemd_hardening
vars:
systemd_hardening_services:
myservice:
ProtectSystem: strict
NoNewPrivileges: true
```
## Notes
- Only units that appear in `systemctl list-unit-files --type=service` are disabled or masked, with or without the `.service` suffix.
- The manager drop-in (`DefaultLimitNOFILE`, `DefaultLimitNPROC`, `DefaultLimitCORE`, and task, memory and CPU accounting) is written verbatim by `tasks/harden_manager.yml` and has no variable.
- Drop-in and manager changes notify `systemd reload`, which runs `daemon-reload`. Handlers are flushed at the end of the role.
- Policy lives in defaults, not `vars/`, so group_vars and host_vars can override it.
- `no_log` is not used: the role handles no secrets.
-53
View File
@@ -1,53 +0,0 @@
---
# Per-systemd_hardening_system_type policy. Overridable from group_vars/host_vars: set
# systemd_hardening_disable_services_extra (replaces the list for every type in that scope), or
# override systemd_hardening_profiles (replaces ALL profiles, so copy the ones you
# keep). Not in vars/ or include_vars: both outrank group_vars and host_vars.
systemd_hardening_profiles:
pve:
disable_services_extra: []
ubuntu_lxc:
# Not present or not meaningful in an LXC
disable_services_extra:
- systemd-journal-remote
ubuntu_vm:
disable_services_extra:
- multipathd
# Default services to disable globally
systemd_hardening_disable_services:
- rpcbind
- avahi-daemon
- cups
- bluetooth
- nfs-server
# Added to the list above for this systemd_hardening_system_type. Lazy (read at use), no set_fact,
# so a group_vars override of the flat name wins.
systemd_hardening_disable_services_extra: "{{ systemd_hardening_profiles[systemd_hardening_system_type].disable_services_extra }}"
# What the role actually disables: base + extra. Read-only result, do not set.
systemd_hardening_disable_services_effective: "{{ systemd_hardening_disable_services + systemd_hardening_disable_services_extra }}"
# High-risk services to mask completely (security policy)
systemd_hardening_mask_services:
- telnet
- rsh
- rlogin
- xinetd
# Per-service hardening overrides (opt-in)
# Map of <unit name without .service> -> {Directive: value}. Values render as:
# booleans -> yes/no, lists -> space-joined, everything else as-is.
# Example:
# systemd_hardening_services:
# myservice:
# ProtectSystem: "strict"
# NoNewPrivileges: true
#
# Do NOT add ssh/sshd here. Sandboxing directives on sshd.service
# (ProtectSystem, PrivateTmp, NoNewPrivileges, ...) are inherited by every
# SSH login session and everything spawned from it, including sudo. That
# makes admin and Ansible sessions see a read-only filesystem / private /tmp
# and can break privilege escalation. Harden sshd via the sshd role instead.
systemd_hardening_services: {}
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more