Merge branch 'main' into feat/pihole-role
This commit is contained in:
commit
9979dfa8ed
29 files changed
+1221
-97
No files matched your search
@@ -0,0 +1,11 @@
|
|||||||
|
---
|
||||||
|
minor_changes:
|
||||||
|
- >-
|
||||||
|
docker - Add the opt-in inputs ``docker_start_missed`` and ``docker_stop_at_shutdown`` (both default ``false``, so a host that does not
|
||||||
|
set them is unchanged) for a host that runs Docker with ``live-restore``. ``docker_start_missed`` installs a boot unit that starts the
|
||||||
|
containers dockerd's restore pass skipped after a reboot of the whole host (exited with code 255 during this boot, restart policy
|
||||||
|
``unless-stopped`` or ``always``; one stopped on purpose stays stopped), with ``docker_start_missed_settle_seconds`` (default 30).
|
||||||
|
``docker_stop_at_shutdown`` installs a unit that ends every container process at shutdown while the network and NFS shares are still up
|
||||||
|
(SIGTERM, then SIGKILL after ``docker_stop_at_shutdown_timeout`` seconds, default 30, never ``docker stop`` or ``docker kill``), so that
|
||||||
|
a container holding an NFS mount does not stall the shutdown while the network is already down. Setting an input back to ``false``, or ``docker_remove``,
|
||||||
|
removes its unit and script. Both units do nothing when ``/usr/bin/docker`` does not exist.
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
---
|
||||||
|
trivial:
|
||||||
|
- >-
|
||||||
|
Every public role README follows the fixed heading set: Supported platforms, Requirements and
|
||||||
|
run order, Role variables, Entry points, Variables set by the role, Tags, Example play, Tests
|
||||||
|
and Notes, with an "Idempotent" line.
|
||||||
@@ -63,9 +63,11 @@ itself always stops and starts the service.
|
|||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
|
|
||||||
Two molecule scenarios run against stub binaries (shell scripts) under a stub unit, with no
|
Two molecule scenarios run on Ubuntu 24.04 (noble) against stub binaries (shell scripts) under
|
||||||
network: `default` covers a successful bump, its idempotence, a binary that cannot start, a
|
a stub unit, with no network: `default` covers a successful bump, its idempotence, a binary
|
||||||
binary that reports another version (both rolled back), a run with nothing staged (the service
|
that cannot start, a binary that reports another version (both rolled back), a run with nothing
|
||||||
is not stopped), a direct call from a play (refused) and a first install with nothing to back
|
staged (the service is not stopped), a direct call from a play (refused) and a first install
|
||||||
up. `check_mode` runs the bump under `--check` against a stopped service and checks that
|
with nothing to back up. `check_mode` runs the bump under `--check` against a stopped service
|
||||||
nothing changed. The calling roles' own scenarios cover a real upstream binary.
|
and checks that nothing changed. The calling roles' own scenarios cover a real upstream binary.
|
||||||
|
|
||||||
|
Idempotent: yes.
|
||||||
+26
-19
@@ -4,11 +4,14 @@ Installs cloudflared as a systemd service for a locally managed Cloudflare Tunne
|
|||||||
|
|
||||||
## Supported platforms
|
## Supported platforms
|
||||||
|
|
||||||
Ubuntu 24.04 (noble), the image the molecule scenario runs on. The role downloads the `cloudflared-linux-amd64` binary only, so other architectures are unsupported, and it needs `systemd`. The tasks that call the Cloudflare API run on the controller (`delegate_to: localhost`) and need the `community.general` collection (`cloudflare_dns`) there; the `mint` entry point also needs the `openssl` command on the controller. The target needs outbound access to github.com and to Cloudflare's edge; the role defines no firewall rules because the daemon only connects outbound.
|
Ubuntu 24.04 (noble), the platform the molecule scenario runs on. The role downloads the `cloudflared-linux-amd64` binary only, so other architectures are unsupported, and it needs `systemd`. The tasks that call the Cloudflare API run on the controller (`delegate_to: localhost`) and need the `community.general` collection (`cloudflare_dns`) there; the `mint` entry point also needs the `openssl` command on the controller. The target needs outbound access to github.com and to Cloudflare's edge; the role defines no firewall rules because the daemon only connects outbound.
|
||||||
|
|
||||||
|
The role targets Ubuntu hosts that run the tunnel daemon, not Proxmox nodes, so it does not cover Debian trixie.
|
||||||
|
|
||||||
## Requirements and run order
|
## Requirements and run order
|
||||||
|
|
||||||
- Use it by its fully qualified name, `mortis.kamino.cloudflared`.
|
- Use it by its fully qualified name, `mortis.kamino.cloudflared`.
|
||||||
|
- Role dependencies: it includes `mortis.kamino._binary_update` of this Collection.
|
||||||
- Before the first run: set `cloudflared_account_id` and `cloudflared_tunnel_api_token` (vaulted), and, while `cloudflared_manage_dns` is true, `cloudflared_zone_name`; list the routed hostnames in `cloudflared_ingress`. The token needs Cloudflare Tunnel Edit, DNS Edit and Zone Read; do not reuse a token that serves another purpose (for example an ACME DNS-challenge token).
|
- Before the first run: set `cloudflared_account_id` and `cloudflared_tunnel_api_token` (vaulted), and, while `cloudflared_manage_dns` is true, `cloudflared_zone_name`; list the routed hostnames in `cloudflared_ingress`. The token needs Cloudflare Tunnel Edit, DNS Edit and Zone Read; do not reuse a token that serves another purpose (for example an ACME DNS-challenge token).
|
||||||
- First run versus later runs: `cloudflared_tunnel_id` and `cloudflared_credentials_json` have no role default and the main entry point never creates them. Validation asserts both are defined and non-empty before anything changes and fails with the mint instructions otherwise. On a new host run the `mint` entry point first, persist its output facts into inventory under these two names, then run the role (see Entry points).
|
- First run versus later runs: `cloudflared_tunnel_id` and `cloudflared_credentials_json` have no role default and the main entry point never creates them. Validation asserts both are defined and non-empty before anything changes and fails with the mint instructions otherwise. On a new host run the `mint` entry point first, persist its output facts into inventory under these two names, then run the role (see Entry points).
|
||||||
- The secrets are not `required` in the argument spec, on purpose, as an exception to the rule that a secret is a required input: argument validation would stop a first run with a generic "missing required arguments" message, where the role's own assert names the mint entry point that creates the tunnel, and the `mint` entry point must run while `cloudflared_tunnel_id` is still undefined. All four (`cloudflared_tunnel_id`, `cloudflared_credentials_json`, `cloudflared_account_id`, `cloudflared_tunnel_api_token`) have no default and are asserted non-empty before any change.
|
- The secrets are not `required` in the argument spec, on purpose, as an exception to the rule that a secret is a required input: argument validation would stop a first run with a generic "missing required arguments" message, where the role's own assert names the mint entry point that creates the tunnel, and the `mint` entry point must run while `cloudflared_tunnel_id` is still undefined. All four (`cloudflared_tunnel_id`, `cloudflared_credentials_json`, `cloudflared_account_id`, `cloudflared_tunnel_api_token`) have no default and are asserted non-empty before any change.
|
||||||
@@ -45,26 +48,30 @@ Ubuntu 24.04 (noble), the image the molecule scenario runs on. The role download
|
|||||||
## Entry points
|
## Entry points
|
||||||
|
|
||||||
- `main`: install, configure, update or remove cloudflared, as above.
|
- `main`: install, configure, update or remove cloudflared, as above.
|
||||||
- `mint` (`tasks_from: mint`): creates the tunnel. Run it by hand from an operator play, never from CI:
|
- `mint` (`tasks_from: mint`): creates the tunnel, see [`mint`](#mint).
|
||||||
|
|
||||||
```yaml
|
### `mint`
|
||||||
- name: Mint the Cloudflare Tunnel
|
|
||||||
hosts: tunnel_hosts
|
|
||||||
tasks:
|
|
||||||
- name: Mint
|
|
||||||
ansible.builtin.include_role:
|
|
||||||
name: mortis.kamino.cloudflared
|
|
||||||
tasks_from: mint
|
|
||||||
# Then vault-encrypt cloudflared_minted_tunnel_id and cloudflared_minted_credentials_json
|
|
||||||
# (when defined) into inventory as cloudflared_tunnel_id and cloudflared_credentials_json.
|
|
||||||
```
|
|
||||||
|
|
||||||
Run it with `-e cloudflared_mint_confirm=true`.
|
Run it by hand from an operator play, never from CI:
|
||||||
|
|
||||||
- Guards: `cloudflared_mint_confirm` must be true, and the entry point fails when `GITHUB_ACTIONS`, `GITEA_ACTIONS` or `CI` is set in the controller environment. This guards against accidents; it is not a security boundary.
|
```yaml
|
||||||
- When `cloudflared_tunnel_id` is already defined and non-empty (undefined, null and `""` count as missing) it only reports that and creates nothing, so a re-run is safe. It creates nothing in check mode.
|
- name: Mint the Cloudflare Tunnel
|
||||||
- Otherwise it asserts `cloudflared_account_id`, `cloudflared_tunnel_api_token` and `cloudflared_tunnel_name`, generates the tunnel secret in memory with `openssl rand -base64 32` on the controller, creates the tunnel through the API with `config_src: local` and registers `cloudflared_minted_tunnel_id` and `cloudflared_minted_credentials_json` as `no_log` facts. The secret and the API response are cleared from the host's variables afterwards.
|
hosts: tunnel_hosts
|
||||||
- Persisting the facts is the calling play's job. The credentials are shown nowhere else, so a mint whose result is not persisted must be repeated, and leaves an orphan tunnel on Cloudflare to delete by hand.
|
tasks:
|
||||||
|
- name: Mint
|
||||||
|
ansible.builtin.include_role:
|
||||||
|
name: mortis.kamino.cloudflared
|
||||||
|
tasks_from: mint
|
||||||
|
# Then vault-encrypt cloudflared_minted_tunnel_id and cloudflared_minted_credentials_json
|
||||||
|
# (when defined) into inventory as cloudflared_tunnel_id and cloudflared_credentials_json.
|
||||||
|
```
|
||||||
|
|
||||||
|
Run it with `-e cloudflared_mint_confirm=true`.
|
||||||
|
|
||||||
|
- Guards: `cloudflared_mint_confirm` must be true, and the entry point fails when `GITHUB_ACTIONS`, `GITEA_ACTIONS` or `CI` is set in the controller environment. This guards against accidents; it is not a security boundary.
|
||||||
|
- When `cloudflared_tunnel_id` is already defined and non-empty (undefined, null and `""` count as missing) it only reports that and creates nothing, so a re-run is safe. It creates nothing in check mode.
|
||||||
|
- Otherwise it asserts `cloudflared_account_id`, `cloudflared_tunnel_api_token` and `cloudflared_tunnel_name`, generates the tunnel secret in memory with `openssl rand -base64 32` on the controller, creates the tunnel through the API with `config_src: local` and registers `cloudflared_minted_tunnel_id` and `cloudflared_minted_credentials_json` as `no_log` facts. The secret and the API response are cleared from the host's variables afterwards.
|
||||||
|
- Persisting the facts is the calling play's job. The credentials are shown nowhere else, so a mint whose result is not persisted must be repeated, and leaves an orphan tunnel on Cloudflare to delete by hand.
|
||||||
|
|
||||||
## Variables set by the role
|
## Variables set by the role
|
||||||
|
|
||||||
@@ -99,7 +106,7 @@ Remove with `-e "cloudflared_remove=true cloudflared_remove_data=true"`; only `c
|
|||||||
|
|
||||||
## Tests
|
## Tests
|
||||||
|
|
||||||
The `default` molecule scenario runs without Cloudflare: a stub cloudflared binary stands in for the daemon, the downloads come from local `file://` URLs, and a stub of the Cloudflare API on the controller's loopback (`molecule/default/files/cloudflare_api_stub.py`, reached through `cloudflared_api_base_url`) answers the tunnel, zone and DNS record calls. It covers the converge with `cloudflared_manage_dns` false and an update through `_binary_update` (and its idempotence), the rendered `config.yml`, credentials file and unit, a stale credentials file, a failed checksum that leaves the daemon running, the input asserts, the deleted-tunnel and DNS guards, the `mint` entry point (confirm guard, CI refusal, no-op, check mode and a mint against the stub, run as child processes) and the remove path. The `community.general.cloudflare_dns` calls, which cannot be pointed at the stub, are not covered: creating, pruning and deleting records.
|
The `default` molecule scenario runs on one platform, Ubuntu 24.04 (noble) (`${MOLECULE_IMAGE}`), without Cloudflare: a stub cloudflared binary stands in for the daemon, the downloads come from local `file://` URLs, and a stub of the Cloudflare API on the controller's loopback (`molecule/default/files/cloudflare_api_stub.py`, reached through `cloudflared_api_base_url`) answers the tunnel, zone and DNS record calls. It covers the converge with `cloudflared_manage_dns` false and an update through `_binary_update` (and its idempotence), the rendered `config.yml`, credentials file and unit, a stale credentials file, a failed checksum that leaves the daemon running, the input asserts, the deleted-tunnel and DNS guards, the `mint` entry point (confirm guard, CI refusal, no-op, check mode and a mint against the stub, run as child processes) and the remove path. The `community.general.cloudflare_dns` calls, which cannot be pointed at the stub, are not covered: creating, pruning and deleting records.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
|
|
||||||
|
|||||||
+31
-5
@@ -4,13 +4,18 @@ Installs Docker Engine from the upstream Docker APT repository, optionally updat
|
|||||||
|
|
||||||
## Supported platforms
|
## Supported platforms
|
||||||
|
|
||||||
Ubuntu. The key and repository URLs point at `download.docker.com/linux/ubuntu`, and the source line uses `ansible_distribution_release`. The apt architecture is derived from the host (`x86_64` gives `amd64`, `aarch64` gives `arm64`); any other architecture fails the play until `docker_apt_arch` is set. A limited molecule scenario covers the role's own logic (see [Tests](#tests)); the real Docker Engine is not tested.
|
Ubuntu 24.04 (noble), the platform the molecule scenario runs on. The key and repository URLs point at `download.docker.com/linux/ubuntu`, and the source line uses `ansible_distribution_release`. The apt architecture is derived from the host (`x86_64` gives `amd64`, `aarch64` gives `arm64`); any other architecture fails the play until `docker_apt_arch` is set. A limited molecule scenario covers the role's own logic (see [Tests](#tests)); the real Docker Engine is not tested.
|
||||||
|
|
||||||
|
Untested platforms: Ubuntu releases other than 24.04; `meta/main.yml` declares Ubuntu `all`.
|
||||||
|
|
||||||
|
The role targets Ubuntu hosts only: it installs from Docker's Ubuntu repository, so it does not cover Debian trixie (Proxmox hosts).
|
||||||
|
|
||||||
## Requirements and run order
|
## Requirements and run order
|
||||||
|
|
||||||
- Needs gathered facts and privilege escalation.
|
- Needs gathered facts and privilege escalation.
|
||||||
- Use it by its fully qualified name, `mortis.kamino.docker`.
|
- 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`).
|
- 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`).
|
||||||
|
- Role dependencies: none.
|
||||||
- The `ufw` role is not a dependency and is not called: Docker publishes ports through iptables and owns no UFW rule.
|
- The `ufw` role is not a dependency and is not called: Docker publishes ports through iptables and owns no UFW rule.
|
||||||
|
|
||||||
## Role variables
|
## Role variables
|
||||||
@@ -26,16 +31,35 @@ Ubuntu. The key and repository URLs point at `download.docker.com/linux/ubuntu`,
|
|||||||
| `docker_gpg_url` | `https://download.docker.com/linux/ubuntu/gpg` | no | Key URL. |
|
| `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_repo_base_url` | `https://download.docker.com/linux/ubuntu` | no | Repository base URL. |
|
||||||
| `docker_apt_arch` | derived from the host | no | Architecture in the APT source. Empty derives it (`x86_64` gives `amd64`, `aarch64` gives `arm64`); another architecture fails until this is set. A value set here is always used; lowercase letters and digits only. |
|
| `docker_apt_arch` | derived from the host | no | Architecture in the APT source. Empty derives it (`x86_64` gives `amd64`, `aarch64` gives `arm64`); another architecture fails until this is set. A value set here is always used; lowercase letters and digits only. |
|
||||||
|
| `docker_start_missed` | `false` | no | Install a boot unit that starts the containers Docker skipped after a reboot (see [Boot and shutdown units](#boot-and-shutdown-units)). |
|
||||||
|
| `docker_start_missed_settle_seconds` | `30` | no | Seconds the boot unit waits after Docker answers, so dockerd's own restarts finish first. |
|
||||||
|
| `docker_stop_at_shutdown` | `false` | no | Install a unit that ends container processes at shutdown while the network and NFS are still up. |
|
||||||
|
| `docker_stop_at_shutdown_timeout` | `30` | no | Seconds the shutdown unit waits after SIGTERM before it sends SIGKILL (at least 1). |
|
||||||
| `docker_service` | `docker` | no | systemd unit name. |
|
| `docker_service` | `docker` | no | systemd unit name. |
|
||||||
| `docker_group` | `docker` | no | Group for `docker_users`. |
|
| `docker_group` | `docker` | no | Group for `docker_users`. |
|
||||||
| `docker_users` | `[]` | no | Users added to the group. |
|
| `docker_users` | `[]` | no | Users added to the group. |
|
||||||
|
|
||||||
## Tags
|
## Tags
|
||||||
|
|
||||||
`docker` (everything), `install`, `update`, `remove`, `configure` (group membership). The tasks in `remove.yml` carry `docker` and `remove`.
|
`docker` (everything), `install`, `update`, `remove`, `configure` (group membership and the two units). 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.
|
Update (`docker_update: true`) and removal (`docker_remove: true`) are opt-in: run them on a host that is safe to change.
|
||||||
|
|
||||||
|
## Boot and shutdown units
|
||||||
|
|
||||||
|
Both are opt-in, for a host that runs Docker with `live-restore` (a `docker.service` restart then leaves containers running). They are part of this role, so they exist only on a host you apply it to, and each does nothing when `/usr/bin/docker` does not exist.
|
||||||
|
|
||||||
|
- **`docker_start_missed`**: a reboot of the whole host kills the containers, and dockerd's restore pass at the next boot sometimes skips one without trying (`RestartCount` stays 0; Docker reports exit code 255). The unit `docker-start-missed.service` runs once per boot after Docker, waits `docker_start_missed_settle_seconds`, and starts a container only if its restart policy is `unless-stopped` or `always`, it exited with code 255, and it finished after this boot began. A container stopped on purpose (exit code 0, 137 or 143) stays stopped. It is `Type=simple`, so it never delays or fails the boot.
|
||||||
|
- **`docker_stop_at_shutdown`**: with `live-restore` dockerd does not stop containers at host shutdown, and systemd-shutdown signals them after the network is gone. A container that holds an NFS mount then blocks in the kernel's final unmount until the SIGKILL timer. The unit `docker-stop-at-shutdown.service` is started by the role; its stop action runs after Docker has stopped and before the network and remote file systems, sends SIGTERM to every container process, waits up to `docker_stop_at_shutdown_timeout` seconds, then SIGKILL, and logs to the journal under the tag `docker-stop-at-shutdown`. It never calls `docker stop` or `docker kill`, which would set the manually-stopped marker, so a container with `unless-stopped` starts again at the next boot. Check that `systemctl is-active docker-stop-at-shutdown` says `active`, because the stop action runs only for an active unit.
|
||||||
|
|
||||||
|
Setting an input back to `false` removes that unit's file and script. The role never stops a running shutdown unit, because stopping it runs its stop action and ends every container; it takes effect as systemd reloads and reboots.
|
||||||
|
|
||||||
|
Things to know before you switch `docker_stop_at_shutdown` on:
|
||||||
|
|
||||||
|
- The unit is ordered before `docker.service` and after `network-online.target` and `remote-fs.target`. That ordering applies at boot as well: Docker starts only after the network and the remote file systems are up, so an unreachable NFS server delays Docker until its mount gives up.
|
||||||
|
- The script reads the layout of the systemd cgroup driver on cgroup v2 (`/sys/fs/cgroup/system.slice/docker-<id>.scope`, and the cgroups below it). On a host that lays containers out differently it finds nothing, logs "no container scopes" and changes nothing, so check the journal (`journalctl -t docker-stop-at-shutdown -b -1`) after the first reboot.
|
||||||
|
- `docker-start-missed --dry-run` lists what the boot unit would start; add `--settle 0` to skip the wait.
|
||||||
|
|
||||||
## Example play
|
## Example play
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
@@ -48,7 +72,7 @@ Update (`docker_update: true`) and removal (`docker_remove: true`) are opt-in: r
|
|||||||
|
|
||||||
## Tests
|
## 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.
|
`molecule/default` runs in CI only (`.gitea/workflows/molecule.yml`, no local runner), on one platform: Ubuntu 24.04 (noble), the `molecule-ubuntu2404` test container (`${MOLECULE_IMAGE}`). 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:
|
What it shows, with the role's tasks running unchanged:
|
||||||
|
|
||||||
@@ -56,13 +80,15 @@ What it shows, with the role's tasks running unchanged:
|
|||||||
- The source line has the architecture, the `signed-by` keyring and `ansible_distribution_release`.
|
- 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`.
|
- 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`.
|
- `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`.
|
- Both units are installed, enabled, ordered against `docker.service` as stated, the shutdown unit is active, a unit is removed when its input is `false`, and `docker_remove` removes both.
|
||||||
|
- The argument check refuses a mapping for `docker_users`, a non-boolean `docker_remove` and a `docker_stop_at_shutdown_timeout` of 0.
|
||||||
- A second run changes nothing (molecule's idempotence check).
|
- A second run changes nothing (molecule's idempotence check).
|
||||||
|
|
||||||
What it does not show: that the upstream repository and key at `download.docker.com` are reachable and valid, that the real packages install, that `dockerd` starts, anything about container networking or iptables, the `docker_update` path (`tasks/update.yml`), and removal without `docker_remove_data` (the removal stops the unit first, so it can run only once per install). It needs the Ubuntu mirrors, for the `curl` the role installs. These gaps are a known residual risk of the role.
|
What it does not show: what the units do at a real boot or shutdown (the container has no dockerd, no NFS shares and no reboot; the selection logic of `docker-start-missed` is unit-tested in `tests/scripts/test_docker_files.py`), that the upstream repository and key at `download.docker.com` are reachable and valid, that the real packages install, that `dockerd` starts, anything about container networking or iptables, the `docker_update` path (`tasks/update.yml`), and removal without `docker_remove_data` (the removal stops the unit first, so it can run only once per install). It needs the Ubuntu mirrors, for the `curl` the role installs. These gaps are a known residual risk of the role.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
|
|
||||||
|
- Idempotent: yes.
|
||||||
- `docker_remove` is checked first: when true, only `remove.yml` runs.
|
- `docker_remove` is checked first: when true, only `remove.yml` runs.
|
||||||
- Removal with `docker_remove_data` is destructive. It deletes `/var/lib/docker`.
|
- 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`.
|
- 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`.
|
||||||
|
|||||||
@@ -30,3 +30,19 @@ docker_users: []
|
|||||||
# Docker manipulates iptables directly for any published container port
|
# Docker manipulates iptables directly for any published container port
|
||||||
# (`-p`), bypassing UFW rules entirely - so the role owns no UFW rule and does
|
# (`-p`), bypassing UFW rules entirely - so the role owns no UFW rule and does
|
||||||
# not call the ufw role.
|
# not call the ufw role.
|
||||||
|
|
||||||
|
# With live-restore Docker leaves containers running when dockerd stops, but a reboot of the whole host kills them, and dockerd's restore
|
||||||
|
# pass at the next boot sometimes skips one without trying. When true, a boot unit starts the containers that Docker left down: only
|
||||||
|
# those exited with code 255 during this boot whose restart policy is unless-stopped or always, so one stopped on purpose stays stopped.
|
||||||
|
# Off by default; set it on a host that runs Docker with live-restore.
|
||||||
|
docker_start_missed: false
|
||||||
|
# Seconds to wait after Docker answers, so dockerd's own restarts finish first.
|
||||||
|
docker_start_missed_settle_seconds: 30
|
||||||
|
|
||||||
|
# With live-restore dockerd does not stop containers at host shutdown, and systemd-shutdown signals them only after the network is gone. A
|
||||||
|
# container that holds an NFS mount then blocks in the kernel's final unmount until the SIGKILL timer, and the host takes minutes to stop.
|
||||||
|
# When true, a shutdown unit sends SIGTERM to every container process while the network and NFS are still up, waits up to
|
||||||
|
# docker_stop_at_shutdown_timeout seconds, then SIGKILL. It never uses `docker stop`, so the manually-stopped marker is not set.
|
||||||
|
# Off by default; set it on a host whose containers mount NFS shares.
|
||||||
|
docker_stop_at_shutdown: false
|
||||||
|
docker_stop_at_shutdown_timeout: 30
|
||||||
Executable
+176
@@ -0,0 +1,176 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Start the containers that Docker skipped when the host booted.
|
||||||
|
|
||||||
|
With live-restore, dockerd leaves containers running when it stops, but a reboot of the whole host kills them. At the next boot dockerd's
|
||||||
|
restore pass sometimes skips one without trying to restart it (RestartCount stays 0, no error) although its restart policy is
|
||||||
|
unless-stopped or always. Docker then reports the container as exited with code 255, the code it uses when the process vanished without
|
||||||
|
Docker seeing it exit.
|
||||||
|
|
||||||
|
This runs once per boot, after docker.service, waits for the normal restarts to settle and starts what is still down. It starts a
|
||||||
|
container only when ALL of these hold, so a container someone stopped on purpose stays stopped:
|
||||||
|
- the restart policy is unless-stopped or always;
|
||||||
|
- it is exited with code 255 (a manual `docker stop` gives 0, 137 or 143);
|
||||||
|
- it finished after this boot began (it died with this reboot, not earlier).
|
||||||
|
Exit 0: nothing to do, or everything started (--dry-run only reports). 1: a start failed or the container did not stay up. 2: Docker never
|
||||||
|
answered, or its output could not be read. The boot time comes from /proc/uptime: in an LXC that needs lxcfs, otherwise it is the host's
|
||||||
|
and the window only gets wider, which the exit-code and policy tests still bound.
|
||||||
|
A container whose data cannot be read fails the run (exit 2) instead of being guessed at. Standard library only: it runs on the managed host.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
POLICIES = ("unless-stopped", "always")
|
||||||
|
KILLED_EXIT_CODE = 255
|
||||||
|
BOOT_TOLERANCE_SECONDS = 5
|
||||||
|
|
||||||
|
|
||||||
|
def parse_time(text):
|
||||||
|
"""Docker's RFC 3339 timestamps carry nanoseconds, which datetime cannot read: cut to microseconds."""
|
||||||
|
head, _, rest = text.rstrip("Z").partition(".")
|
||||||
|
frac = "".join(ch for ch in rest if ch.isdigit())[:6].ljust(6, "0")
|
||||||
|
return datetime.strptime(f"{head}.{frac}", "%Y-%m-%dT%H:%M:%S.%f").replace(
|
||||||
|
tzinfo=timezone.utc # noqa: UP017 (datetime.UTC needs Python 3.11; Ubuntu 22.04 has 3.10)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def missed(containers, boot_time):
|
||||||
|
"""Names of the containers (docker inspect objects) that died with this reboot and should be running."""
|
||||||
|
names = []
|
||||||
|
for c in containers:
|
||||||
|
state, policy = (
|
||||||
|
c.get("State", {}),
|
||||||
|
c.get("HostConfig", {}).get("RestartPolicy", {}).get("Name", ""),
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
state.get("Running")
|
||||||
|
or state.get("Status") == "restarting"
|
||||||
|
or policy not in POLICIES
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
if state.get("ExitCode") != KILLED_EXIT_CODE:
|
||||||
|
continue
|
||||||
|
finished = state.get("FinishedAt", "")
|
||||||
|
if not finished or finished.startswith("0001-"):
|
||||||
|
continue
|
||||||
|
if (
|
||||||
|
parse_time(finished) - boot_time
|
||||||
|
).total_seconds() >= -BOOT_TOLERANCE_SECONDS:
|
||||||
|
names.append(c["Name"].lstrip("/"))
|
||||||
|
return sorted(names)
|
||||||
|
|
||||||
|
|
||||||
|
def boot_time_now(uptime_path="/proc/uptime"):
|
||||||
|
with open(uptime_path, encoding="ascii") as handle:
|
||||||
|
up = float(handle.read().split()[0])
|
||||||
|
return datetime.fromtimestamp(time.time() - up, tz=timezone.utc) # noqa: UP017 (see parse_time)
|
||||||
|
|
||||||
|
|
||||||
|
def docker(*args):
|
||||||
|
return subprocess.run(
|
||||||
|
["docker", *args], capture_output=True, text=True, check=False
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def wait_for_docker(attempts, delay, run=docker, sleep=time.sleep):
|
||||||
|
for _ in range(attempts):
|
||||||
|
if run("info").returncode == 0:
|
||||||
|
return True
|
||||||
|
sleep(delay)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def find_missed(run, boot_time, log):
|
||||||
|
"""The names to start, or None when Docker's answer could not be read (already logged)."""
|
||||||
|
listing = run("ps", "-aq", "--filter", "status=exited")
|
||||||
|
if listing.returncode != 0:
|
||||||
|
log(f"docker ps failed: {listing.stderr.strip()}")
|
||||||
|
return None
|
||||||
|
ids = listing.stdout.split()
|
||||||
|
try:
|
||||||
|
inspected = []
|
||||||
|
if ids:
|
||||||
|
inspection = run("inspect", *ids)
|
||||||
|
if inspection.returncode != 0 and not inspection.stdout.strip():
|
||||||
|
log(f"docker inspect failed: {inspection.stderr.strip()}")
|
||||||
|
return None
|
||||||
|
inspected = json.loads(
|
||||||
|
inspection.stdout
|
||||||
|
) # a container removed in between is simply missing from the list
|
||||||
|
return missed(inspected, boot_time)
|
||||||
|
except (
|
||||||
|
ValueError,
|
||||||
|
KeyError,
|
||||||
|
TypeError,
|
||||||
|
) as exc: # not JSON, or a timestamp or field Docker formats differently than expected
|
||||||
|
log(f"could not read the container list: {exc!r}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def start_all(names, run, sleep, log):
|
||||||
|
"""Start each container, then check after a few seconds that it stayed up. Returns the names that failed."""
|
||||||
|
failed = []
|
||||||
|
for name in names:
|
||||||
|
result = run("start", name)
|
||||||
|
if result.returncode != 0:
|
||||||
|
log(f"could not start {name}: {result.stderr.strip()}")
|
||||||
|
failed.append(name)
|
||||||
|
else:
|
||||||
|
log(f"started {name}, which docker skipped at boot")
|
||||||
|
sleep(5)
|
||||||
|
for name in names:
|
||||||
|
if (
|
||||||
|
name not in failed
|
||||||
|
and run("inspect", "-f", "{{.State.Running}}", name).stdout.strip()
|
||||||
|
!= "true"
|
||||||
|
):
|
||||||
|
log(f"{name} did not stay up")
|
||||||
|
failed.append(name)
|
||||||
|
return failed
|
||||||
|
|
||||||
|
|
||||||
|
def run_once(
|
||||||
|
settle, run=docker, sleep=time.sleep, boot_time=None, log=print, dry_run=False
|
||||||
|
):
|
||||||
|
boot_time = boot_time or boot_time_now()
|
||||||
|
if not wait_for_docker(24, 5, run, sleep):
|
||||||
|
log("docker did not answer within 2 minutes")
|
||||||
|
return 2
|
||||||
|
sleep(
|
||||||
|
settle
|
||||||
|
) # dockerd's own restart pass runs in the first seconds: let it finish before judging what is still down
|
||||||
|
todo = find_missed(run, boot_time, log)
|
||||||
|
if todo is None:
|
||||||
|
return 2
|
||||||
|
if not todo:
|
||||||
|
log("no container to start")
|
||||||
|
return 0
|
||||||
|
if dry_run:
|
||||||
|
log("would start: " + ", ".join(todo))
|
||||||
|
return 0
|
||||||
|
return 1 if start_all(todo, run, sleep, log) else 0
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv):
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||||
|
parser.add_argument(
|
||||||
|
"--settle",
|
||||||
|
type=int,
|
||||||
|
default=30,
|
||||||
|
help="seconds to wait after docker answers, for dockerd's own restarts",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--dry-run",
|
||||||
|
action="store_true",
|
||||||
|
help="say what would be started and start nothing",
|
||||||
|
)
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
return run_once(args.settle, dry_run=args.dry_run)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main(sys.argv[1:]))
|
||||||
Executable
+44
@@ -0,0 +1,44 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# End every container's processes while the network and the NFS shares are still up.
|
||||||
|
#
|
||||||
|
# With live-restore dockerd does not stop containers at host shutdown, and systemd-shutdown then signals them only after the network is
|
||||||
|
# gone. A container that holds an NFS mount blocks in the kernel's final unmount of it (a request to a server it can no longer reach)
|
||||||
|
# until the SIGKILL timer, which makes the host take minutes to stop.
|
||||||
|
#
|
||||||
|
# Run by the unit's ExecStop, which systemd orders after docker.service has stopped (so no restart policy interferes) and before the
|
||||||
|
# network and remote-fs targets. SIGTERM to every process of every container, wait, then SIGKILL what is left. It never uses
|
||||||
|
# `docker stop` or `docker kill`: both set the manually-stopped marker, and a container with restart policy unless-stopped would then not
|
||||||
|
# start again at the next boot. With dockerd down the containers simply exit and their policy restarts them at boot.
|
||||||
|
# It reads the systemd cgroup driver's layout (cgroup v2, /sys/fs/cgroup/system.slice/docker-<id>.scope). On a host that lays containers out
|
||||||
|
# differently it finds nothing, says so in the journal and changes nothing.
|
||||||
|
set -u
|
||||||
|
shopt -s nullglob
|
||||||
|
|
||||||
|
timeout="${DOCKER_STOP_TIMEOUT:-30}"
|
||||||
|
scopes=(/sys/fs/cgroup/system.slice/docker-*.scope)
|
||||||
|
|
||||||
|
if [ "${#scopes[@]}" -eq 0 ]; then
|
||||||
|
logger -t docker-stop-at-shutdown "no container scopes, nothing to do"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Every process of every scope, including those in child cgroups. Only real PIDs: a process this namespace cannot see is listed as 0,
|
||||||
|
# and `kill 0` would signal our own process group.
|
||||||
|
pids() { find "${scopes[@]}" -name cgroup.procs -exec cat {} + 2> /dev/null | grep -E '^[1-9][0-9]*$'; }
|
||||||
|
|
||||||
|
logger -t docker-stop-at-shutdown "SIGTERM to $(pids | wc -l) processes in ${#scopes[@]} container scopes (wait up to ${timeout}s)"
|
||||||
|
pids | xargs -r kill -TERM 2> /dev/null
|
||||||
|
|
||||||
|
deadline=$((SECONDS + timeout))
|
||||||
|
while [ "$SECONDS" -lt "$deadline" ] && [ -n "$(pids)" ]; do
|
||||||
|
sleep 0.25
|
||||||
|
done
|
||||||
|
|
||||||
|
left=$(pids | wc -l)
|
||||||
|
if [ "$left" -gt 0 ]; then
|
||||||
|
logger -t docker-stop-at-shutdown "$left processes still there after ${timeout}s: SIGKILL"
|
||||||
|
pids | xargs -r kill -KILL 2> /dev/null
|
||||||
|
sleep 1
|
||||||
|
fi
|
||||||
|
logger -t docker-stop-at-shutdown "done after ${SECONDS}s, processes left: $(pids | wc -l)"
|
||||||
|
exit 0
|
||||||
@@ -62,6 +62,46 @@ argument_specs:
|
|||||||
Architecture written into the APT source. Empty (the default) derives it from the host: C(x86_64) gives C(amd64), C(aarch64)
|
Architecture written into the APT source. Empty (the default) derives it from the host: C(x86_64) gives C(amd64), C(aarch64)
|
||||||
gives C(arm64). Any other host architecture fails the play, so set this to the name Docker publishes for it. Lowercase letters
|
gives C(arm64). Any other host architecture fails the play, so set this to the name Docker publishes for it. Lowercase letters
|
||||||
and digits only. A value set here is always used.
|
and digits only. A value set here is always used.
|
||||||
|
docker_start_missed:
|
||||||
|
type: bool
|
||||||
|
default: false
|
||||||
|
description:
|
||||||
|
- >-
|
||||||
|
Installs C(/usr/local/sbin/docker-start-missed) and the unit C(docker-start-missed.service). After each boot the unit starts the
|
||||||
|
containers that Docker left down: exited with code 255 during this boot, with restart policy C(unless-stopped) or C(always). A
|
||||||
|
container stopped on purpose stays stopped. Setting it back to false removes the unit and the script.
|
||||||
|
- >-
|
||||||
|
Meant for a host that runs Docker with C(live-restore), where dockerd's restore pass can skip a container after a reboot of the
|
||||||
|
whole host. The unit does nothing when C(/usr/bin/docker) does not exist.
|
||||||
|
docker_start_missed_settle_seconds:
|
||||||
|
type: int
|
||||||
|
default: 30
|
||||||
|
description:
|
||||||
|
- Seconds the unit waits after Docker answers, so dockerd's own restarts finish before it judges what is still down. At least 0.
|
||||||
|
docker_stop_at_shutdown:
|
||||||
|
type: bool
|
||||||
|
default: false
|
||||||
|
description:
|
||||||
|
- >-
|
||||||
|
Installs C(/usr/local/sbin/docker-stop-at-shutdown) and the unit C(docker-stop-at-shutdown.service), started by the role, whose stop
|
||||||
|
action runs at host shutdown after Docker has stopped and before the network and remote file systems. It sends SIGTERM to every
|
||||||
|
container process, waits up to C(docker_stop_at_shutdown_timeout) seconds, then SIGKILL. It never uses C(docker stop) or
|
||||||
|
C(docker kill), which would set the manually-stopped marker. Setting it back to false removes the unit and the script. The role
|
||||||
|
never stops the running unit, because stopping it runs its stop action and ends every container.
|
||||||
|
- >-
|
||||||
|
The unit is ordered before C(docker.service) and after C(network-online.target) and C(remote-fs.target), and that ordering
|
||||||
|
also applies at boot: Docker then starts only after the network and the remote file systems are up. The script reads the
|
||||||
|
layout of the systemd cgroup driver on cgroup v2 (C(/sys/fs/cgroup/system.slice/docker-<id>.scope)); on a host that lays
|
||||||
|
containers out differently it finds nothing, says so in the journal and changes nothing.
|
||||||
|
- >-
|
||||||
|
Meant for a host that runs Docker with C(live-restore) and whose containers mount NFS shares: without it a container holding
|
||||||
|
a mount blocks the shutdown in the kernel's final unmount once the network is gone. The unit does nothing when
|
||||||
|
C(/usr/bin/docker) does not exist.
|
||||||
|
docker_stop_at_shutdown_timeout:
|
||||||
|
type: int
|
||||||
|
default: 30
|
||||||
|
description:
|
||||||
|
- Seconds the unit waits for container processes to end after SIGTERM before it sends SIGKILL. At least 1.
|
||||||
docker_service:
|
docker_service:
|
||||||
type: str
|
type: str
|
||||||
default: docker
|
default: docker
|
||||||
|
|||||||
@@ -9,6 +9,9 @@
|
|||||||
docker_gpg_url: file:///srv/docker-stub-repo/docker.asc
|
docker_gpg_url: file:///srv/docker-stub-repo/docker.asc
|
||||||
docker_repo_base_url: file:///srv/docker-stub-repo
|
docker_repo_base_url: file:///srv/docker-stub-repo
|
||||||
docker_users: [moleculeuser]
|
docker_users: [moleculeuser]
|
||||||
|
docker_start_missed: true
|
||||||
|
docker_stop_at_shutdown: true
|
||||||
|
docker_stop_at_shutdown_timeout: 20
|
||||||
roles:
|
roles:
|
||||||
- role: mortis.kamino.docker
|
- role: mortis.kamino.docker
|
||||||
|
|
||||||
@@ -83,3 +86,26 @@
|
|||||||
- "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')"
|
- "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')"
|
||||||
- "'docker_apt_arch' in ansible_failed_result.msg | default('')"
|
- "'docker_apt_arch' in ansible_failed_result.msg | default('')"
|
||||||
quiet: true
|
quiet: true
|
||||||
|
|
||||||
|
# The unit timings are checked before anything changes.
|
||||||
|
- name: A docker_stop_at_shutdown_timeout of 0 is refused
|
||||||
|
hosts: all
|
||||||
|
gather_facts: false
|
||||||
|
vars:
|
||||||
|
docker_stop_at_shutdown_timeout: 0
|
||||||
|
tasks:
|
||||||
|
- name: Apply the role with a timeout of 0
|
||||||
|
block:
|
||||||
|
- name: Include the role
|
||||||
|
ansible.builtin.include_role:
|
||||||
|
name: mortis.kamino.docker
|
||||||
|
- name: Fail when the timeout was accepted
|
||||||
|
ansible.builtin.fail:
|
||||||
|
msg: MOLECULE-ACCEPTED
|
||||||
|
rescue:
|
||||||
|
- name: The validation stopped the play
|
||||||
|
ansible.builtin.assert:
|
||||||
|
that:
|
||||||
|
- "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')"
|
||||||
|
- "'docker_stop_at_shutdown_timeout' in ansible_failed_result.msg | default('')"
|
||||||
|
quiet: true
|
||||||
@@ -5,7 +5,7 @@
|
|||||||
# build-stub-repo.sh <repo-root> <codename> <work-dir>
|
# 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
|
# 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
|
# default docker_packages). docker-ce ships a stub docker.service, a stub /usr/bin/docker and a postinst that creates
|
||||||
# the docker group, as the real package does. The Release file is signed with a throwaway key
|
# 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
|
# 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.
|
# the role fetches as its keyring. The secret key stays in <work-dir> and is never installed.
|
||||||
@@ -32,7 +32,10 @@ Description: stand-in for $name in the docker role's molecule scenario
|
|||||||
Empty package. It installs nothing from Docker.
|
Empty package. It installs nothing from Docker.
|
||||||
CONTROL
|
CONTROL
|
||||||
if [ "$name" = docker-ce ]; then
|
if [ "$name" = docker-ce ]; then
|
||||||
mkdir -p "$tree/usr/lib/systemd/system"
|
mkdir -p "$tree/usr/lib/systemd/system" "$tree/usr/bin"
|
||||||
|
# The units the role installs only run where /usr/bin/docker exists; nothing here runs it.
|
||||||
|
printf '#!/bin/sh\nexit 1\n' > "$tree/usr/bin/docker"
|
||||||
|
chmod 0755 "$tree/usr/bin/docker"
|
||||||
cat > "$tree/usr/lib/systemd/system/docker.service" <<'UNIT'
|
cat > "$tree/usr/lib/systemd/system/docker.service" <<'UNIT'
|
||||||
[Unit]
|
[Unit]
|
||||||
Description=Stand-in for the Docker Engine (molecule)
|
Description=Stand-in for the Docker Engine (molecule)
|
||||||
|
|||||||
@@ -90,6 +90,119 @@
|
|||||||
that: "'docker' in docker_verify_groups.stdout.split()"
|
that: "'docker' in docker_verify_groups.stdout.split()"
|
||||||
quiet: true
|
quiet: true
|
||||||
|
|
||||||
|
# The two units: installed, enabled, ordered as the role promises, and the shutdown unit running (its stop action runs only for an
|
||||||
|
# active unit). Their behaviour at a real boot or shutdown cannot be shown here: the container has no dockerd, no NFS and no reboot, and the
|
||||||
|
# shutdown script is not run because the container shares the runner's cgroup tree.
|
||||||
|
- name: Verify the boot and shutdown units
|
||||||
|
hosts: all
|
||||||
|
gather_facts: false
|
||||||
|
vars:
|
||||||
|
docker_verify_units: [docker-start-missed, docker-stop-at-shutdown]
|
||||||
|
tasks:
|
||||||
|
- name: Stat the scripts and the unit files
|
||||||
|
ansible.builtin.stat:
|
||||||
|
path: "{{ item }}"
|
||||||
|
loop:
|
||||||
|
- /usr/local/sbin/docker-start-missed
|
||||||
|
- /usr/local/sbin/docker-stop-at-shutdown
|
||||||
|
- /etc/systemd/system/docker-start-missed.service
|
||||||
|
- /etc/systemd/system/docker-stop-at-shutdown.service
|
||||||
|
register: docker_verify_unit_files
|
||||||
|
|
||||||
|
- name: The scripts are executable and the unit files are not
|
||||||
|
ansible.builtin.assert:
|
||||||
|
that:
|
||||||
|
- docker_verify_unit_files.results | map(attribute='stat.exists') | unique | list == [true]
|
||||||
|
- docker_verify_unit_files.results[0].stat.mode == "0755"
|
||||||
|
- docker_verify_unit_files.results[1].stat.mode == "0755"
|
||||||
|
- docker_verify_unit_files.results[2].stat.mode == "0644"
|
||||||
|
- docker_verify_unit_files.results[3].stat.mode == "0644"
|
||||||
|
quiet: true
|
||||||
|
|
||||||
|
- name: Ask systemd about the units
|
||||||
|
ansible.builtin.command:
|
||||||
|
argv:
|
||||||
|
- systemctl
|
||||||
|
- show
|
||||||
|
- --property=UnitFileState,ActiveState,After,Before
|
||||||
|
- "{{ item }}.service"
|
||||||
|
loop: "{{ docker_verify_units }}"
|
||||||
|
register: docker_verify_unit_show
|
||||||
|
changed_when: false
|
||||||
|
|
||||||
|
- name: Both units are enabled
|
||||||
|
ansible.builtin.assert:
|
||||||
|
that: "'UnitFileState=enabled' in item.stdout"
|
||||||
|
quiet: true
|
||||||
|
loop: "{{ docker_verify_unit_show.results }}"
|
||||||
|
|
||||||
|
- name: The boot unit starts after docker, the shutdown unit stops before it
|
||||||
|
ansible.builtin.assert:
|
||||||
|
that:
|
||||||
|
- "'docker.service' in (docker_verify_unit_show.results[0].stdout | regex_search('After=.*'))"
|
||||||
|
- "'docker.service' in (docker_verify_unit_show.results[1].stdout | regex_search('Before=.*'))"
|
||||||
|
- "'network-online.target' in (docker_verify_unit_show.results[1].stdout | regex_search('After=.*'))"
|
||||||
|
- "'remote-fs.target' in (docker_verify_unit_show.results[1].stdout | regex_search('After=.*'))"
|
||||||
|
quiet: true
|
||||||
|
|
||||||
|
- name: The shutdown unit is active, which is what lets its stop action run
|
||||||
|
ansible.builtin.assert:
|
||||||
|
that: "'ActiveState=active' in docker_verify_unit_show.results[1].stdout"
|
||||||
|
quiet: true
|
||||||
|
|
||||||
|
- name: Read the shutdown unit
|
||||||
|
ansible.builtin.slurp:
|
||||||
|
src: /etc/systemd/system/docker-stop-at-shutdown.service
|
||||||
|
register: docker_verify_stop_unit
|
||||||
|
|
||||||
|
- name: The timeout the converge set reaches the unit
|
||||||
|
ansible.builtin.assert:
|
||||||
|
that:
|
||||||
|
- "'Environment=DOCKER_STOP_TIMEOUT=20' in (docker_verify_stop_unit.content | b64decode)"
|
||||||
|
- "'TimeoutStopSec=50' in (docker_verify_stop_unit.content | b64decode)"
|
||||||
|
quiet: true
|
||||||
|
|
||||||
|
- name: The start script refuses an option it does not know
|
||||||
|
ansible.builtin.command: /usr/local/sbin/docker-start-missed --no-such-option
|
||||||
|
register: docker_verify_start_run
|
||||||
|
changed_when: false
|
||||||
|
failed_when: docker_verify_start_run.rc != 2
|
||||||
|
|
||||||
|
# Switching an input back to false removes that unit and script and leaves the other alone.
|
||||||
|
- name: Verify that a unit is removed when its input is false
|
||||||
|
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]
|
||||||
|
docker_start_missed: false
|
||||||
|
docker_stop_at_shutdown: true
|
||||||
|
docker_stop_at_shutdown_timeout: 20
|
||||||
|
tasks:
|
||||||
|
- name: Apply the role with the boot unit off
|
||||||
|
ansible.builtin.include_role:
|
||||||
|
name: mortis.kamino.docker
|
||||||
|
|
||||||
|
- name: Stat the boot unit's files and the shutdown unit's script
|
||||||
|
ansible.builtin.stat:
|
||||||
|
path: "{{ item }}"
|
||||||
|
loop:
|
||||||
|
- /usr/local/sbin/docker-start-missed
|
||||||
|
- /etc/systemd/system/docker-start-missed.service
|
||||||
|
- /usr/local/sbin/docker-stop-at-shutdown
|
||||||
|
register: docker_verify_off
|
||||||
|
|
||||||
|
- name: The boot unit is gone and the shutdown unit is still there
|
||||||
|
ansible.builtin.assert:
|
||||||
|
that: docker_verify_off.results | map(attribute='stat.exists') | list == [false, false, true]
|
||||||
|
quiet: true
|
||||||
|
|
||||||
|
- name: Apply the role again with both inputs on
|
||||||
|
ansible.builtin.include_role:
|
||||||
|
name: mortis.kamino.docker
|
||||||
|
vars:
|
||||||
|
docker_start_missed: true
|
||||||
|
|
||||||
# docker_remove_data is set, so this also covers the destructive path: the packages are
|
# 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
|
# 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
|
# before the package takes it away, so it can only run once; a second run would fail on the
|
||||||
@@ -114,9 +227,13 @@
|
|||||||
- /etc/apt/keyrings/docker.asc
|
- /etc/apt/keyrings/docker.asc
|
||||||
- /var/lib/docker
|
- /var/lib/docker
|
||||||
- /usr/lib/systemd/system/docker.service
|
- /usr/lib/systemd/system/docker.service
|
||||||
|
- /usr/local/sbin/docker-start-missed
|
||||||
|
- /usr/local/sbin/docker-stop-at-shutdown
|
||||||
|
- /etc/systemd/system/docker-start-missed.service
|
||||||
|
- /etc/systemd/system/docker-stop-at-shutdown.service
|
||||||
register: docker_verify_gone
|
register: docker_verify_gone
|
||||||
|
|
||||||
- name: The source list, the keyring, the data and the unit are gone
|
- name: The source list, the keyring, the data, the unit and the two extra units are gone
|
||||||
ansible.builtin.assert:
|
ansible.builtin.assert:
|
||||||
that: docker_verify_gone.results | map(attribute='stat.exists') | unique | list == [false]
|
that: docker_verify_gone.results | map(attribute='stat.exists') | unique | list == [false]
|
||||||
quiet: true
|
quiet: true
|
||||||
|
|||||||
@@ -31,5 +31,10 @@
|
|||||||
when: not (docker_remove | default(false) | bool)
|
when: not (docker_remove | default(false) | bool)
|
||||||
tags: [docker, configure]
|
tags: [docker, configure]
|
||||||
|
|
||||||
|
- name: Install or remove the boot and shutdown units
|
||||||
|
ansible.builtin.include_tasks: units.yml
|
||||||
|
when: not (docker_remove | default(false) | bool)
|
||||||
|
tags: [docker, configure]
|
||||||
|
|
||||||
- name: Flush handlers
|
- name: Flush handlers
|
||||||
ansible.builtin.meta: flush_handlers
|
ansible.builtin.meta: flush_handlers
|
||||||
@@ -8,6 +8,20 @@
|
|||||||
enabled: false
|
enabled: false
|
||||||
tags: [docker, remove]
|
tags: [docker, remove]
|
||||||
|
|
||||||
|
- name: Take out the start-at-boot unit
|
||||||
|
ansible.builtin.include_tasks: unit_absent.yml
|
||||||
|
vars:
|
||||||
|
__docker_unit_name: docker-start-missed
|
||||||
|
__docker_unit_script: /usr/local/sbin/docker-start-missed
|
||||||
|
tags: [docker, remove]
|
||||||
|
|
||||||
|
- name: Take out the stop-at-shutdown unit
|
||||||
|
ansible.builtin.include_tasks: unit_absent.yml
|
||||||
|
vars:
|
||||||
|
__docker_unit_name: docker-stop-at-shutdown
|
||||||
|
__docker_unit_script: /usr/local/sbin/docker-stop-at-shutdown
|
||||||
|
tags: [docker, remove]
|
||||||
|
|
||||||
- name: Remove Docker Engine packages
|
- name: Remove Docker Engine packages
|
||||||
become: true
|
become: true
|
||||||
ansible.builtin.apt:
|
ansible.builtin.apt:
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
---
|
||||||
|
# Takes one of the role's units out: disable it, delete its files, tell systemd. A running unit is not stopped, because stopping
|
||||||
|
# docker-stop-at-shutdown runs its stop action and ends every container. Needs __docker_unit_name and __docker_unit_script.
|
||||||
|
- name: Disable {{ __docker_unit_name }}
|
||||||
|
become: true
|
||||||
|
ansible.builtin.systemd:
|
||||||
|
name: "{{ __docker_unit_name }}.service"
|
||||||
|
enabled: false
|
||||||
|
register: __docker_unit_disabled
|
||||||
|
# The unit may not exist (systemd: "Could not find the requested service"): there is nothing to disable.
|
||||||
|
failed_when:
|
||||||
|
- __docker_unit_disabled.failed | default(false)
|
||||||
|
- "'Could not find the requested service' not in (__docker_unit_disabled.msg | default(''))"
|
||||||
|
when: not ansible_check_mode
|
||||||
|
tags: [docker, configure, remove]
|
||||||
|
|
||||||
|
- name: Remove the files of {{ __docker_unit_name }}
|
||||||
|
become: true
|
||||||
|
ansible.builtin.file:
|
||||||
|
path: "{{ item }}"
|
||||||
|
state: absent
|
||||||
|
loop:
|
||||||
|
- "/etc/systemd/system/{{ __docker_unit_name }}.service"
|
||||||
|
- "{{ __docker_unit_script }}"
|
||||||
|
register: __docker_unit_removed
|
||||||
|
tags: [docker, configure, remove]
|
||||||
|
|
||||||
|
- name: Reload systemd after removing {{ __docker_unit_name }}
|
||||||
|
become: true
|
||||||
|
ansible.builtin.systemd:
|
||||||
|
daemon_reload: true
|
||||||
|
when:
|
||||||
|
- __docker_unit_removed is changed
|
||||||
|
- not ansible_check_mode
|
||||||
|
tags: [docker, configure, remove]
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
---
|
||||||
|
# The two opt-in units for a host that runs Docker with live-restore. Each is installed when its input is true and removed when it is false.
|
||||||
|
- name: Install the boot unit that starts containers Docker skipped
|
||||||
|
when: docker_start_missed | bool
|
||||||
|
tags: [docker, configure]
|
||||||
|
block:
|
||||||
|
- name: Install the script that starts containers Docker skipped at boot
|
||||||
|
become: true
|
||||||
|
ansible.builtin.copy:
|
||||||
|
src: docker-start-missed
|
||||||
|
dest: /usr/local/sbin/docker-start-missed
|
||||||
|
owner: root
|
||||||
|
group: root
|
||||||
|
mode: "0755"
|
||||||
|
tags: [docker, configure]
|
||||||
|
|
||||||
|
# Type=simple, not oneshot: a oneshot unit in multi-user.target holds the boot until it finishes, which can take minutes. A failure
|
||||||
|
# still shows in `systemctl --failed`, and the target only Wants this unit, so it never fails the boot. No Wants= on Docker: a host
|
||||||
|
# whose operator keeps Docker disabled must not get it started by this unit.
|
||||||
|
- name: Install the unit that starts containers Docker skipped at boot
|
||||||
|
become: true
|
||||||
|
ansible.builtin.copy:
|
||||||
|
dest: /etc/systemd/system/docker-start-missed.service
|
||||||
|
owner: root
|
||||||
|
group: root
|
||||||
|
mode: "0644"
|
||||||
|
content: |
|
||||||
|
[Unit]
|
||||||
|
Description=Start containers that Docker skipped at boot
|
||||||
|
After={{ docker_service }}.service
|
||||||
|
ConditionPathExists=/usr/bin/docker
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
ExecStart=/usr/local/sbin/docker-start-missed --settle {{ docker_start_missed_settle_seconds }}
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
register: __docker_start_missed_unit
|
||||||
|
tags: [docker, configure]
|
||||||
|
|
||||||
|
# Not in check mode: on the first run the unit file above is only simulated, so systemd would not find it.
|
||||||
|
- name: Enable the unit that starts containers Docker skipped at boot
|
||||||
|
become: true
|
||||||
|
ansible.builtin.systemd:
|
||||||
|
name: docker-start-missed.service
|
||||||
|
enabled: true
|
||||||
|
daemon_reload: true
|
||||||
|
when: not ansible_check_mode
|
||||||
|
tags: [docker, configure]
|
||||||
|
|
||||||
|
- name: Take out the unit that starts containers Docker skipped
|
||||||
|
ansible.builtin.include_tasks: unit_absent.yml
|
||||||
|
vars:
|
||||||
|
__docker_unit_name: docker-start-missed
|
||||||
|
__docker_unit_script: /usr/local/sbin/docker-start-missed
|
||||||
|
when: not (docker_start_missed | bool)
|
||||||
|
tags: [docker, configure]
|
||||||
|
|
||||||
|
- name: Install the shutdown unit that ends containers while the network is up
|
||||||
|
when: docker_stop_at_shutdown | bool
|
||||||
|
tags: [docker, configure]
|
||||||
|
block:
|
||||||
|
- name: Install the script that ends containers at shutdown
|
||||||
|
become: true
|
||||||
|
ansible.builtin.copy:
|
||||||
|
src: docker-stop-at-shutdown
|
||||||
|
dest: /usr/local/sbin/docker-stop-at-shutdown
|
||||||
|
owner: root
|
||||||
|
group: root
|
||||||
|
mode: "0755"
|
||||||
|
tags: [docker, configure]
|
||||||
|
|
||||||
|
# Stop order is the reverse of start order: Before= makes docker stop first, so no restart policy can interfere, and After= the network
|
||||||
|
# and remote file systems makes this unit stop before them, while NFS can still be reached. The work is the stop action, which systemd
|
||||||
|
# runs only for a unit that is active: RemainAfterExit keeps it active after its start action, and the role starts it below.
|
||||||
|
- name: Install the unit that ends containers at shutdown
|
||||||
|
become: true
|
||||||
|
ansible.builtin.copy:
|
||||||
|
dest: /etc/systemd/system/docker-stop-at-shutdown.service
|
||||||
|
owner: root
|
||||||
|
group: root
|
||||||
|
mode: "0644"
|
||||||
|
content: |
|
||||||
|
[Unit]
|
||||||
|
Description=Stop containers while the network and NFS shares are still up
|
||||||
|
After=network-online.target remote-fs.target
|
||||||
|
Before={{ docker_service }}.service
|
||||||
|
ConditionPathExists=/usr/bin/docker
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
RemainAfterExit=yes
|
||||||
|
ExecStart=/bin/true
|
||||||
|
Environment=DOCKER_STOP_TIMEOUT={{ docker_stop_at_shutdown_timeout }}
|
||||||
|
ExecStop=/usr/local/sbin/docker-stop-at-shutdown
|
||||||
|
TimeoutStopSec={{ (docker_stop_at_shutdown_timeout | int) + 30 }}
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
register: __docker_stop_at_shutdown_unit
|
||||||
|
tags: [docker, configure]
|
||||||
|
|
||||||
|
# Started now, so the first shutdown after this run is covered without a reboot. Not in check mode: the unit file above is only
|
||||||
|
# simulated there, and a dry run must not start anything. A changed unit is not restarted, because stopping it runs its stop action,
|
||||||
|
# which ends every container.
|
||||||
|
- name: Enable and start the unit that ends containers at shutdown
|
||||||
|
become: true
|
||||||
|
ansible.builtin.systemd:
|
||||||
|
name: docker-stop-at-shutdown.service
|
||||||
|
enabled: true
|
||||||
|
state: started
|
||||||
|
daemon_reload: true
|
||||||
|
when: not ansible_check_mode
|
||||||
|
tags: [docker, configure]
|
||||||
|
|
||||||
|
- name: Take out the shutdown unit that ends containers
|
||||||
|
ansible.builtin.include_tasks: unit_absent.yml
|
||||||
|
vars:
|
||||||
|
__docker_unit_name: docker-stop-at-shutdown
|
||||||
|
__docker_unit_script: /usr/local/sbin/docker-stop-at-shutdown
|
||||||
|
when: not (docker_stop_at_shutdown | bool)
|
||||||
|
tags: [docker, configure]
|
||||||
@@ -21,3 +21,13 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
quiet: true
|
quiet: true
|
||||||
tags: always
|
tags: always
|
||||||
|
|
||||||
|
- name: Check the unit timings
|
||||||
|
ansible.builtin.assert:
|
||||||
|
that:
|
||||||
|
- docker_start_missed_settle_seconds | int(-1) >= 0
|
||||||
|
- docker_stop_at_shutdown_timeout | int(0) >= 1
|
||||||
|
fail_msg: >-
|
||||||
|
docker_start_missed_settle_seconds must be a whole number of at least 0 and docker_stop_at_shutdown_timeout a whole number of at least 1.
|
||||||
|
quiet: true
|
||||||
|
tags: always
|
||||||
@@ -4,7 +4,9 @@ Installs Fail2Ban, writes `/etc/fail2ban/jail.local` from `fail2ban_jails`, ensu
|
|||||||
|
|
||||||
## Supported platforms
|
## 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.
|
Ubuntu 24.04 (noble), the platform 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.
|
||||||
|
|
||||||
|
Ubuntu hosts only: the role targets the Ubuntu guests whose `system_baseline` profiles install `fail2ban`; Proxmox hosts are not targeted.
|
||||||
|
|
||||||
## Requirements and run order
|
## Requirements and run order
|
||||||
|
|
||||||
@@ -13,6 +15,7 @@ Ubuntu 24.04 (noble), the image the molecule scenario runs on. The default `sshd
|
|||||||
- Main entry point: apply it after `ufw` in the play that hardens a host.
|
- 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.
|
- `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.
|
- A file named by a jail's `logpath` must exist when `fail2ban-client -t` runs, or the configuration test fails.
|
||||||
|
- Role dependencies: none.
|
||||||
|
|
||||||
## Role variables
|
## Role variables
|
||||||
|
|
||||||
@@ -35,6 +38,18 @@ Main entry point:
|
|||||||
| `fail2ban_service_filter` | none | yes | Filter mapping; needs `failregex`, optional `ignoreregex`. |
|
| `fail2ban_service_filter` | none | yes | Filter mapping; needs `failregex`, optional `ignoreregex`. |
|
||||||
| `fail2ban_package_name`, `fail2ban_defaults` | as above | no | Read from the role defaults. |
|
| `fail2ban_package_name`, `fail2ban_defaults` | as above | no | Read from the role defaults. |
|
||||||
|
|
||||||
|
## Entry points
|
||||||
|
|
||||||
|
- `main`: writes `jail.local` from `fail2ban_jails` and runs the service, as in the first play of the example.
|
||||||
|
- `service_jail`: a service role's own jail and filter, see [`service_jail`](#service_jail).
|
||||||
|
|
||||||
|
### `service_jail`
|
||||||
|
|
||||||
|
It deploys the service's jail and filter into `jail.d`. Its inputs are in the second table under [Role variables](#role-variables), and the second play of the example calls it.
|
||||||
|
|
||||||
|
- Each service owns `jail.d/<name>.local`, so one play cannot overwrite another service's jail. `jail.local` only holds `fail2ban_jails`.
|
||||||
|
- `fail2ban_service_jail` and `fail2ban_service_filter` must be passed as a single templated expression so they stay mappings, not strings or lists.
|
||||||
|
|
||||||
## Tags
|
## Tags
|
||||||
|
|
||||||
Main entry point: `fail2ban` (everything), `fail2ban_install`, `fail2ban_validate`, `fail2ban_configure`, `fail2ban_service`.
|
Main entry point: `fail2ban` (everything), `fail2ban_install`, `fail2ban_validate`, `fail2ban_configure`, `fail2ban_service`.
|
||||||
@@ -65,9 +80,20 @@ Main entry point: `fail2ban` (everything), `fail2ban_install`, `fail2ban_validat
|
|||||||
fail2ban_service_filter: "{{ gitea_fail2ban_filter }}"
|
fail2ban_service_filter: "{{ gitea_fail2ban_filter }}"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
The scenario `molecule/default/` runs in CI only, on one platform: `${MOLECULE_IMAGE}`, an Ubuntu 24.04 (noble) container. The sequence runs prepare, converge, idempotence, side effect and verify; it has no check-mode step.
|
||||||
|
|
||||||
|
- Converge applies the main entry point with an extra `fail2ban_ignoreip` network and calls `service_jail` twice, one jail with a `logpath` and one with a `journalmatch`.
|
||||||
|
- Converge also runs inputs that must be refused: a service filter without `failregex`, and a `fail2ban_ignoreip` entry with whitespace, a plain string instead of a list, and an entry starting with `;`. The `fail2ban_ignoreip` refusals are matched on their message.
|
||||||
|
- Verify checks that the `sshd` jail does not read `/var/log/auth.log`, that `jail.local` holds the configured `ignoreip` in `[DEFAULT]` and none of the refused values, that each service jail has its own `jail.d` file and the refused one left no file, that `fail2ban-client -t` passes, and that the running daemon loaded `sshd`, `svc-a` and `svc-b` and applies the `ignoreip` network to both a base jail and a service jail.
|
||||||
|
- The side effect bans an address and rewrites `jail.local` with a new `maxretry`; verify checks the new value is active, the ban is still in force and the daemon PID is unchanged, so the change reloaded Fail2Ban instead of restarting it.
|
||||||
|
|
||||||
|
Not covered: no failure is sent through a jail, so a ban triggered by `failregex` is not tested, and the reload behaviours read from the Fail2Ban source (see Notes) are not run.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
|
|
||||||
- Each service owns `jail.d/<name>.local`, so one play cannot overwrite another service's jail. `jail.local` only holds `fail2ban_jails`.
|
- Idempotent: yes.
|
||||||
- `fail2ban_ignoreip` lives in the `[DEFAULT]` section of `jail.local`, so it also applies to the jails that `service_jail` writes to `jail.d`. The exemption only exists once the main entry point has written `jail.local` on that host: `service_jail` does not read `fail2ban_ignoreip`, so a host that uses only `service_jail` has none.
|
- `fail2ban_ignoreip` lives in the `[DEFAULT]` section of `jail.local`, so it also applies to the jails that `service_jail` writes to `jail.d`. The exemption only exists once the main entry point has written `jail.local` on that host: `service_jail` does not read `fail2ban_ignoreip`, so a host that uses only `service_jail` has none.
|
||||||
- `fail2ban_ignoreip` replaces an `ignoreip` set in `jail.conf` or `jail.d/*.conf`, which Fail2Ban reads before `jail.local`; a `jail.d/*.local` file is read after it and can still override it for one jail. Entries must not contain whitespace, `;` or `%` (a `;` after whitespace starts a comment in Fail2Ban's config files and a `%` is interpolation syntax).
|
- `fail2ban_ignoreip` replaces an `ignoreip` set in `jail.conf` or `jail.d/*.conf`, which Fail2Ban reads before `jail.local`; a `jail.d/*.local` file is read after it and can still override it for one jail. Entries must not contain whitespace, `;` or `%` (a `;` after whitespace starts a comment in Fail2Ban's config files and a `%` is interpolation syntax).
|
||||||
- Prefer IP addresses and CIDR networks in `fail2ban_ignoreip`. Fail2Ban resolves a hostname when the jail starts, and a failed lookup leaves that entry ineffective with only a log warning. The validation of `fail2ban_ignoreip` runs under the `fail2ban_validate` tag, so `--tags fail2ban_configure` skips it.
|
- Prefer IP addresses and CIDR networks in `fail2ban_ignoreip`. Fail2Ban resolves a hostname when the jail starts, and a failed lookup leaves that entry ineffective with only a log warning. The validation of `fail2ban_ignoreip` runs under the `fail2ban_validate` tag, so `--tags fail2ban_configure` skips it.
|
||||||
@@ -75,5 +101,4 @@ Main entry point: `fail2ban` (everything), `fail2ban_install`, `fail2ban_validat
|
|||||||
- What a reload does not do, compared with the restart it replaces (read from the Fail2Ban 1.1.0 source, not run here): it does not unban an address that a widened `fail2ban_ignoreip` now covers (only a restart skips ignored addresses when it restores bans, so run `fail2ban-client unban <address>` to release one at once, or wait for the ban to expire); it does not change bans that already exist when `bantime` changes; and it does not apply server-level settings (`loglevel`, `dbfile`, `socket`, `pidfile`), which this role does not write. A changed `backend` restarts that jail by itself.
|
- What a reload does not do, compared with the restart it replaces (read from the Fail2Ban 1.1.0 source, not run here): it does not unban an address that a widened `fail2ban_ignoreip` now covers (only a restart skips ignored addresses when it restores bans, so run `fail2ban-client unban <address>` to release one at once, or wait for the ban to expire); it does not change bans that already exist when `bantime` changes; and it does not apply server-level settings (`loglevel`, `dbfile`, `socket`, `pidfile`), which this role does not write. A changed `backend` restarts that jail by itself.
|
||||||
- With `--tags fail2ban_configure` only, `fail2ban-client -t` does not run before the reload; the reload (`fail2ban-client reload` in the upstream unit) still rejects a bad configuration and leaves the running daemon alone.
|
- With `--tags fail2ban_configure` only, `fail2ban-client -t` does not run before the reload; the reload (`fail2ban-client reload` in the upstream unit) still rejects a bad configuration and leaves the running daemon alone.
|
||||||
- `fail2ban-client -t` runs on every invocation of both entry points, not only when a file changed, so a broken file fails every run until fixed. It also runs in check mode.
|
- `fail2ban-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.
|
- `no_log` is not used: the role handles no secrets.
|
||||||
+29
-4
@@ -4,18 +4,21 @@ Installs the Gitea git service as a systemd-managed binary with a GPG-verified d
|
|||||||
|
|
||||||
## Supported platforms
|
## Supported platforms
|
||||||
|
|
||||||
Ubuntu 24.04 (noble), the image the molecule scenario runs on. The role uses `ansible.builtin.apt`, so Debian-family hosts only, and needs outbound access to dl.gitea.com for the binary and signature and to `gitea_gpg_key_url` (keys.openpgp.org over HTTPS by default) for the signing key. A molecule scenario covers the guard and no-op paths of the mint entry point, the remove path and the signature check of the download (nothing is installed; see `molecule/default`).
|
Ubuntu 24.04 (noble), the platform the molecule scenario runs on. The role uses `ansible.builtin.apt`, so Debian-family hosts only, and needs outbound access to dl.gitea.com for the binary and signature and to `gitea_gpg_key_url` (keys.openpgp.org over HTTPS by default) for the signing key.
|
||||||
|
|
||||||
|
The role targets Ubuntu hosts that serve Gitea, not Proxmox nodes, so it does not cover Debian trixie.
|
||||||
|
|
||||||
## Requirements and run order
|
## Requirements and run order
|
||||||
|
|
||||||
- Use it by its fully qualified name, `mortis.kamino.gitea`.
|
- Use it by its fully qualified name, `mortis.kamino.gitea`.
|
||||||
|
- Role dependencies: it includes `mortis.kamino.ufw` (`service_rules`), `mortis.kamino.fail2ban` (`service_jail`) and `mortis.kamino._binary_update`, all of this Collection.
|
||||||
- Run the `system_baseline` and `ufw` roles of this Collection first. The configure tasks pass `gitea_ufw_service_rules` (allow from 127.0.0.1 and ::1, then deny, on `gitea_http_port`) to the `service_rules` entry point of `mortis.kamino.ufw`, owner `gitea`, which needs ufw installed and active and the SSH rule in place. See the README of `mortis.kamino.ufw`.
|
- Run the `system_baseline` and `ufw` roles of this Collection first. The configure tasks pass `gitea_ufw_service_rules` (allow from 127.0.0.1 and ::1, then deny, on `gitea_http_port`) to the `service_rules` entry point of `mortis.kamino.ufw`, owner `gitea`, which needs ufw installed and active and the SSH rule in place. See the README of `mortis.kamino.ufw`.
|
||||||
- Coupling with `mortis.kamino.fail2ban`: the same file runs its `service_jail` entry point, passing `fail2ban_service_name: gitea`, `fail2ban_service_jail: "{{ gitea_fail2ban_jail }}"` and `fail2ban_service_filter: "{{ gitea_fail2ban_filter }}"`. The jail reads journald (`journalmatch`), because Gitea logs to the console. See the README of `mortis.kamino.fail2ban`.
|
- Coupling with `mortis.kamino.fail2ban`: the same file runs its `service_jail` entry point, passing `fail2ban_service_name: gitea`, `fail2ban_service_jail: "{{ gitea_fail2ban_jail }}"` and `fail2ban_service_filter: "{{ gitea_fail2ban_filter }}"`. The jail reads journald (`journalmatch`), because Gitea logs to the console. See the README of `mortis.kamino.fail2ban`.
|
||||||
- Secrets have no role defaults: `gitea_admin_email`, `gitea_admin_password`, `gitea_secret_key`, `gitea_internal_token`, `gitea_jwt_secret` and `gitea_api_token`. Map them from vaulted variables in inventory; the role never holds the values itself.
|
- Secrets have no role defaults: `gitea_admin_email`, `gitea_admin_password`, `gitea_secret_key`, `gitea_internal_token`, `gitea_jwt_secret` and `gitea_api_token`. Map them from vaulted variables in inventory; the role never holds the values itself.
|
||||||
- The argument spec marks `gitea_domain`, `gitea_admin_user`, `gitea_admin_email`, `gitea_admin_password`, `gitea_secret_key`, `gitea_internal_token` and `gitea_ssh_keys` required, so a missing one fails the role at its start, before the remove path: `gitea_remove=true` needs them too. `gitea_jwt_secret` is asserted at role start (defined and non-empty) by the tasks, also before the remove path, so `--tags remove` needs it as well.
|
- The argument spec marks `gitea_domain`, `gitea_admin_user`, `gitea_admin_email`, `gitea_admin_password`, `gitea_secret_key`, `gitea_internal_token` and `gitea_ssh_keys` required, so a missing one fails the role at its start, before the remove path: `gitea_remove=true` needs them too. `gitea_jwt_secret` is asserted at role start (defined and non-empty) by the tasks, also before the remove path, so `--tags remove` needs it as well.
|
||||||
- `gitea_version` is asserted at role start to be a plain `X.Y.Z` release number, with no leading `v`.
|
- `gitea_version` is asserted at role start to be a plain `X.Y.Z` release number, with no leading `v`.
|
||||||
- `gitea_domain`, `gitea_admin_user` and `gitea_ssh_keys` have no role default and must be set in inventory.
|
- `gitea_domain`, `gitea_admin_user` and `gitea_ssh_keys` have no role default and must be set in inventory.
|
||||||
- Token: `tasks/configure.yml` asserts `gitea_api_token` after the service has started and before the SSH-key API call, and never mints it. See Minting secrets.
|
- Token: `tasks/configure.yml` asserts `gitea_api_token` after the service has started and before the SSH-key API call, and never mints it. See [Entry points](#entry-points).
|
||||||
- A reverse proxy in front terminates TLS: `app.ini` serves plain HTTP on the listener and renders `ROOT_URL` as `https://<gitea_domain>/`.
|
- A reverse proxy in front terminates TLS: `app.ini` serves plain HTTP on the listener and renders `ROOT_URL` as `https://<gitea_domain>/`.
|
||||||
- Updates: the update path stages the verified binary and hands the swap to `mortis.kamino._binary_update`, an internal role of this Collection.
|
- Updates: the update path stages the verified binary and hands the swap to `mortis.kamino._binary_update`, an internal role of this Collection.
|
||||||
- Pin `gitea_version` in inventory to move Gitea independently of Collection releases; the role default changes only with a release.
|
- Pin `gitea_version` in inventory to move Gitea independently of Collection releases; the role default changes only with a release.
|
||||||
@@ -75,11 +78,16 @@ Inputs with role defaults:
|
|||||||
| `gitea_default_email_notifications` | `enabled` | `DEFAULT_EMAIL_NOTIFICATIONS` in `[admin]`: the notification mail setting new users start with (`enabled`, `onmention`, `disabled`). Rendered only with the mailer on. |
|
| `gitea_default_email_notifications` | `enabled` | `DEFAULT_EMAIL_NOTIFICATIONS` in `[admin]`: the notification mail setting new users start with (`enabled`, `onmention`, `disabled`). Rendered only with the mailer on. |
|
||||||
| `gitea_register_email_confirm` | `false` | `REGISTER_EMAIL_CONFIRM`: new accounts and added e-mail addresses must be confirmed by mail. Requires `gitea_mailer_enabled` (asserted). |
|
| `gitea_register_email_confirm` | `false` | `REGISTER_EMAIL_CONFIRM`: new accounts and added e-mail addresses must be confirmed by mail. Requires `gitea_mailer_enabled` (asserted). |
|
||||||
|
|
||||||
## Minting secrets
|
## Entry points
|
||||||
|
|
||||||
|
- `main`: install, configure, update or remove Gitea, as above.
|
||||||
|
- `mint` (`tasks_from: mint`, opt-in): creates the admin API token, see [`mint`](#mint).
|
||||||
|
|
||||||
The normal flow never creates a credential. `tasks/configure.yml` asserts `gitea_api_token` right before the first task that uses it, after the service has started. On a fresh host the first run installs Gitea, creates the admin user and starts the service, then fails at that assert with what to do; the operator mints the token with the entry point below, stores it in inventory and runs the role again. `gitea_jwt_secret` is likewise assert-only.
|
The normal flow never creates a credential. `tasks/configure.yml` asserts `gitea_api_token` right before the first task that uses it, after the service has started. On a fresh host the first run installs Gitea, creates the admin user and starts the service, then fails at that assert with what to do; the operator mints the token with the entry point below, stores it in inventory and runs the role again. `gitea_jwt_secret` is likewise assert-only.
|
||||||
|
|
||||||
The token is created by the opt-in `mint` entry point (`tasks_from: mint`), run by hand from an operator play, never from CI:
|
### `mint`
|
||||||
|
|
||||||
|
Run it by hand from an operator play, never from CI:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
- name: Mint the Gitea admin API token
|
- name: Mint the Gitea admin API token
|
||||||
@@ -100,6 +108,12 @@ Run it with `-e gitea_mint_confirm=true`.
|
|||||||
- The role writes no vault file. The calling play encrypts the fact and stores it in inventory.
|
- The role writes no vault file. The calling play encrypts the fact and stores it in inventory.
|
||||||
- Gitea shows the token once. If the play fails after the token was created and before it was persisted, the token is lost: delete `ansible-provisioning` for the admin user in the Gitea UI (a second token with that name cannot be told apart) and mint again.
|
- Gitea shows the token once. If the play fails after the token was created and before it was persisted, the token is lost: delete `ansible-provisioning` for the admin user in the Gitea UI (a second token with that name cannot be told apart) and mint again.
|
||||||
|
|
||||||
|
## Variables set by the role
|
||||||
|
|
||||||
|
Only by the `mint` entry point, and only when a token was created; `no_log`, not cacheable:
|
||||||
|
|
||||||
|
- `gitea_minted_api_token` (string): the new admin API token, to store in inventory as `gitea_api_token` (see [mint](#mint)).
|
||||||
|
|
||||||
## Tags
|
## Tags
|
||||||
|
|
||||||
`gitea` (everything), `mint` (carried by the mint entry point's tasks, but not selectable on its own: its guards are tagged `gitea, always`, so select the mint play with `--tags gitea`), `remove`, `prereqs`, `install`, `configure`, `health`, `update`, `ufw`, `fail2ban`. `prereqs` tasks and the input asserts are also tagged `always`. `ufw` and `fail2ban` only take effect together with `configure`, `health` or `gitea`: their `include_role` tasks live in `tasks/configure.yml`, which `main.yml` includes only under those tags, so on their own they select nothing. The ufw rule removal in `tasks/remove.yml` also carries `ufw` and `remove`, but `main.yml` includes `remove.yml` only under `gitea` and `remove`.
|
`gitea` (everything), `mint` (carried by the mint entry point's tasks, but not selectable on its own: its guards are tagged `gitea, always`, so select the mint play with `--tags gitea`), `remove`, `prereqs`, `install`, `configure`, `health`, `update`, `ufw`, `fail2ban`. `prereqs` tasks and the input asserts are also tagged `always`. `ufw` and `fail2ban` only take effect together with `configure`, `health` or `gitea`: their `include_role` tasks live in `tasks/configure.yml`, which `main.yml` includes only under those tags, so on their own they select nothing. The ufw rule removal in `tasks/remove.yml` also carries `ufw` and `remove`, but `main.yml` includes `remove.yml` only under `gitea` and `remove`.
|
||||||
@@ -126,8 +140,19 @@ Run it with `-e gitea_mint_confirm=true`.
|
|||||||
|
|
||||||
Update or remove: pass `-e gitea_update=true`, or `-e "gitea_remove=true gitea_remove_data=true" --tags remove`.
|
Update or remove: pass `-e gitea_update=true`, or `-e "gitea_remove=true gitea_remove_data=true" --tags remove`.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
The `default` molecule scenario runs on one platform, Ubuntu 24.04 (noble) (`${MOLECULE_IMAGE}`). It never installs Gitea: converge applies nothing and every check is in `verify.yml` (see `molecule/default`). It covers:
|
||||||
|
|
||||||
|
- The guard and no-op paths of the `mint` entry point: the confirm guard, the CI refusal under each of `GITHUB_ACTIONS`, `GITEA_ACTIONS` and `CI`, the no-op when `gitea_api_token` is set, and an empty token treated as missing under `--check`. All but the confirm guard run as child processes with a controlled environment.
|
||||||
|
- The signature check of the download, against local files and throwaway keys: a signature by the pinned key places the binary; a signature by another key, a tampered binary and a key file without the pinned key each fail at the expected task; no download directory is left behind.
|
||||||
|
- The remove path, against a stub unit and binary: both are deleted, the service is no longer active, only the Gitea ufw rules are removed (the SSH rule and a rule without an owner tag stay), and no config or data directory or `gitea_user` account is created.
|
||||||
|
|
||||||
|
Not covered: install, configure, the admin user, the SSH-key API calls, the update path, the normal-flow assert on `gitea_api_token` (after the service starts) and a mint that creates a token.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
|
|
||||||
|
- Idempotent: yes, by design. The scenario does not show it: its converge applies nothing, so its idempotence step has nothing to repeat.
|
||||||
- The role is not a state selector. `main.yml` runs prerequisites and configure unless `gitea_remove` is true; install runs only when the binary is absent; update only when `gitea_update` is true; remove only when `gitea_remove` is true, and then every other task in `main.yml` is skipped.
|
- The role is not a state selector. `main.yml` runs prerequisites and configure unless `gitea_remove` is true; install runs only when the binary is absent; update only when `gitea_update` is true; remove only when `gitea_remove` is true, and then every other task in `main.yml` is skipped.
|
||||||
- Updates roll back the binary, not the database. Gitea migrates its database when the new version starts, so after a failure past that point the previous binary may refuse the newer schema and the service may not come back up (the failure message of `_binary_update` then says it did not). Back up the database before an update across releases; to recover, restore it or move forward to `gitea_version`.
|
- Updates roll back the binary, not the database. Gitea migrates its database when the new version starts, so after a failure past that point the previous binary may refuse the newer schema and the service may not come back up (the failure message of `_binary_update` then says it did not). Back up the database before an update across releases; to recover, restore it or move forward to `gitea_version`.
|
||||||
- The signature check fails closed when Gitea's release key expires, is revoked or is replaced, so every install and update of the role stops. The `Gitea release key` workflow of this repository (`.gitea/workflows/gitea-release-key.yml`, running `scripts/check_gitea_release_key.py`) checks the key from `gitea_gpg_key_url` and the signature of the pinned `gitea_version` weekly and on changes to `defaults/main.yml`, and fails 60 days before the key expires; the script's docstring says what to do on a failure. Neither file ships in the Collection.
|
- The signature check fails closed when Gitea's release key expires, is revoked or is replaced, so every install and update of the role stops. The `Gitea release key` workflow of this repository (`.gitea/workflows/gitea-release-key.yml`, running `scripts/check_gitea_release_key.py`) checks the key from `gitea_gpg_key_url` and the signature of the pinned `gitea_version` weekly and on changes to `defaults/main.yml`, and fails 60 days before the key expires; the script's docstring says what to do on a failure. Neither file ships in the Collection.
|
||||||
|
|||||||
@@ -4,11 +4,14 @@ Installs a Gitea Actions runner (`gitea-runner`) with Docker as a systemd servic
|
|||||||
|
|
||||||
## Supported platforms
|
## Supported platforms
|
||||||
|
|
||||||
Ubuntu 24.04 (noble), the image the molecule scenario runs on. The role uses `ansible.builtin.apt` and installs `docker.io`, so Debian-family hosts only, and needs outbound access to dl.gitea.com and Docker Hub (the Docker check pulls `ubuntu:24.04`). On an unprivileged LXC host, Docker needs nesting enabled on the container.
|
Ubuntu 24.04 (noble), the platform the molecule scenario runs on. The role uses `ansible.builtin.apt` and installs `docker.io`, so Debian-family hosts only, and needs outbound access to dl.gitea.com and Docker Hub (the Docker check pulls `ubuntu:24.04`). On an unprivileged LXC host, Docker needs nesting enabled on the container.
|
||||||
|
|
||||||
|
The role targets Ubuntu hosts that run CI jobs, not Proxmox nodes, so it does not cover Debian trixie.
|
||||||
|
|
||||||
## Requirements and run order
|
## Requirements and run order
|
||||||
|
|
||||||
- Use it by its fully qualified name, `mortis.kamino.gitea_runner`.
|
- Use it by its fully qualified name, `mortis.kamino.gitea_runner`.
|
||||||
|
- Role dependencies: it includes `mortis.kamino._binary_update` of this Collection.
|
||||||
- Hard dependency on the token host: `tasks/mint_token.yml` delegates `gitea actions generate-runner-token` to the inventory host named by `gitea_runner_token_host`. That host must be in the inventory and must already have Gitea installed (for example by `mortis.kamino.gitea`), with `app.ini` in place. A first install of the runner fails when it is down or has no Gitea. Registration only runs when `<gitea_runner_work_dir>/.runner` does not exist, so later runs do not need it. Under `--check` the registration is reported and not run.
|
- Hard dependency on the token host: `tasks/mint_token.yml` delegates `gitea actions generate-runner-token` to the inventory host named by `gitea_runner_token_host`. That host must be in the inventory and must already have Gitea installed (for example by `mortis.kamino.gitea`), with `app.ini` in place. A first install of the runner fails when it is down or has no Gitea. Registration only runs when `<gitea_runner_work_dir>/.runner` does not exist, so later runs do not need it. Under `--check` the registration is reported and not run.
|
||||||
- Registration inputs: `gitea_runner_token_host`, `gitea_runner_instance_url` and `gitea_runner_name` have empty role defaults and are asserted non-empty only in `tasks/mint_token.yml`, so a run that never registers is not blocked.
|
- Registration inputs: `gitea_runner_token_host`, `gitea_runner_instance_url` and `gitea_runner_name` have empty role defaults and are asserted non-empty only in `tasks/mint_token.yml`, so a run that never registers is not blocked.
|
||||||
- Keep in step with the Gitea installation on the token host: the delegated command uses `gitea_runner_gitea_user`, `gitea_runner_gitea_install_dir` and `gitea_runner_gitea_app_dir` (defaults `git`, `/usr/local/bin`, `/etc/gitea`, the same as the defaults of `mortis.kamino.gitea`). They are separate variables from the `gitea` role's: changing the `gitea` role's values on the token host does not change these, and registration then runs the wrong path or user there. Set both.
|
- Keep in step with the Gitea installation on the token host: the delegated command uses `gitea_runner_gitea_user`, `gitea_runner_gitea_install_dir` and `gitea_runner_gitea_app_dir` (defaults `git`, `/usr/local/bin`, `/etc/gitea`, the same as the defaults of `mortis.kamino.gitea`). They are separate variables from the `gitea` role's: changing the `gitea` role's values on the token host does not change these, and registration then runs the wrong path or user there. Set both.
|
||||||
@@ -86,7 +89,7 @@ Change the registration scope of a registered runner: set `gitea_runner_registra
|
|||||||
|
|
||||||
## Tests
|
## Tests
|
||||||
|
|
||||||
The `default` molecule scenario runs without a Gitea server and without Docker: a stub `docker.service`, a stub runner binary and a seeded `.runner` stand in for them, and the downloads come from local `file://` URLs. It covers the converge with the prune timer and an update through `_binary_update` (and its idempotence), the rendered `config.yaml` and unit, the prune gate script, the count prune and the disk check against a stub `docker` CLI, turning the pressure prune off, a failed checksum that leaves the runner running, the input asserts, the CI refusal of a forced re-registration and the mint-before-drop order, and the remove path. Registration, the Docker install and the host packages of the host-executor label are not covered.
|
The `default` molecule scenario runs on one platform, Ubuntu 24.04 (noble) (`${MOLECULE_IMAGE}`), without a Gitea server and without Docker: a stub `docker.service`, a stub runner binary and a seeded `.runner` stand in for them, and the downloads come from local `file://` URLs. It covers the converge with the prune timer and an update through `_binary_update` (and its idempotence), the rendered `config.yaml` and unit, the prune gate script, the count prune and the disk check against a stub `docker` CLI, turning the pressure prune off, a failed checksum that leaves the runner running, the input asserts, the CI refusal of a forced re-registration and the mint-before-drop order, and the remove path. Registration, the Docker install and the host packages of the host-executor label are not covered.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
|
|
||||||
|
|||||||
@@ -4,13 +4,18 @@ Renders `/etc/network/interfaces` from a list of manual interfaces and bridges,
|
|||||||
|
|
||||||
## Supported platforms
|
## 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.
|
The role targets Debian-based hosts using `ifupdown2` (`ifreload`), such as Proxmox hosts. No platform it targets is verified by a test: the molecule scenario runs on Ubuntu 24.04 (noble) with stubs in place of `ifupdown2` (see [Tests](#tests)).
|
||||||
|
|
||||||
|
Untested platforms: Debian `all`, as declared in `meta/main.yml`.
|
||||||
|
|
||||||
|
It does not cover Ubuntu hosts: it writes the `ifupdown2` bridge configuration of a hypervisor.
|
||||||
|
|
||||||
## Requirements and run order
|
## Requirements and run order
|
||||||
|
|
||||||
- `ifupdown2` must be installed, because the validate and apply commands call `ifreload`.
|
- `ifupdown2` must be installed, because the validate and apply commands call `ifreload`.
|
||||||
- Use it by its fully qualified name, `mortis.kamino.network_interfaces`.
|
- 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.
|
- 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.
|
||||||
|
- Role dependencies: none.
|
||||||
- Gathered facts are not read. The tasks use `become` where they write.
|
- 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.
|
- `network_interfaces_layout` normally comes from inventory (group_vars or host_vars), so each host can have its own layout.
|
||||||
|
|
||||||
@@ -50,9 +55,23 @@ None. The role does not tag its tasks, so only a play-level tag applies.
|
|||||||
vlan_aware: true
|
vlan_aware: true
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
`molecule/default` runs in CI only, on one platform: Ubuntu 24.04 (noble), the `molecule-ubuntu2404` image (`${MOLECULE_IMAGE}`). The image has no `ifupdown2`, and a real reload could cut the container's own network, so the validate command is `/bin/true` and the apply command appends to a marker file; the rest of the role runs unchanged. Prepare seeds `/etc/network/interfaces` with a legacy body, so the converge has a change to make and a backup to take.
|
||||||
|
|
||||||
|
Verify checks:
|
||||||
|
|
||||||
|
- The rendered file holds the loopback, the manual interface and both bridges with their options (address, netmask, gateway, ports, STP, forward delay, VLAN awareness and `bridge_vids 2-4094`), and no legacy line is left.
|
||||||
|
- The backup holds the legacy body.
|
||||||
|
- The reload ran once across the converge and the idempotence run.
|
||||||
|
- With a failing validate command (`/bin/false`), the role fails with "Previous config restored", and the previous file is back.
|
||||||
|
|
||||||
|
It does not test `ifreload`, so no Debian release or `ifupdown2` version is verified by a test.
|
||||||
|
|
||||||
## Notes
|
## 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.
|
- 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.
|
||||||
|
- Idempotent: yes.
|
||||||
- Only a content difference triggers work. Idempotent runs change nothing.
|
- 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.
|
- 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.
|
- 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.
|
||||||
|
|||||||
+19
-3
@@ -4,16 +4,21 @@ Writes a hardened sshd drop-in, selected by a profile, and refuses configuration
|
|||||||
|
|
||||||
## Supported platforms
|
## Supported platforms
|
||||||
|
|
||||||
Ubuntu 24.04 (noble), the image the molecule scenario runs on. 22.04 (jammy) and Debian trixie (Proxmox VE 9 nodes, the `pve` profile) are listed in `meta/main.yml` but not converged by a test; the `pve` drop-in is parsed by `sshd -T` in the scenario. The role uses `ansible.builtin` modules only.
|
Ubuntu 24.04 (noble), the platform the molecule scenario runs on.
|
||||||
|
|
||||||
|
Untested platforms: Ubuntu 22.04 (jammy) and Debian trixie (Proxmox VE 9 nodes, the `pve` profile), listed in `meta/main.yml` but not converged by a test.
|
||||||
|
|
||||||
|
The role targets Ubuntu guests (the `ubuntu_lxc` and `ubuntu_vm` profiles) and Proxmox VE nodes (the `pve` profile).
|
||||||
|
|
||||||
## Requirements and run order
|
## Requirements and run order
|
||||||
|
|
||||||
|
- The role uses `ansible.builtin` modules only.
|
||||||
- Use it by its fully qualified name, `mortis.kamino.sshd`.
|
- Use it by its fully qualified name, `mortis.kamino.sshd`.
|
||||||
- The target must be reachable over SSH and have `ssh-keygen` and `sshd` installed. The role uses `become`.
|
- The target must be reachable over SSH and have `ssh-keygen` and `sshd` installed. The role uses `become`.
|
||||||
- Install the public key of `ansible_user` before this role runs (for example with a user-management role earlier in the play), so key login works before password authentication is turned off. The role does not install keys.
|
- Install the public key of `ansible_user` before this role runs (for example with a user-management role earlier in the play), so key login works before password authentication is turned off. The role does not install keys.
|
||||||
- `sshd_profile` is set by the calling play: `pve`, `ubuntu_lxc` or `ubuntu_vm`.
|
- `sshd_profile` is set by the calling play: `pve`, `ubuntu_lxc` or `ubuntu_vm`.
|
||||||
- The role reads `ansible_user` and sets `ansible_ssh_user` to it for the rest of the play, in case the connection was bootstrapped as root.
|
- The role reads `ansible_user` and sets `ansible_ssh_user` to it for the rest of the play, in case the connection was bootstrapped as root.
|
||||||
- Role dependencies are not declared in `meta/main.yml`; the order above is the contract.
|
- Role dependencies: none. The run order above is not declared in `meta/main.yml`; it is the contract.
|
||||||
|
|
||||||
## Role variables
|
## Role variables
|
||||||
|
|
||||||
@@ -52,12 +57,23 @@ The role defines none.
|
|||||||
MaxAuthTries: "5"
|
MaxAuthTries: "5"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
The scenario `molecule/default/`, run by the Collection's CI, runs on one platform: `${MOLECULE_IMAGE}`, an Ubuntu 24.04 (noble) container that ships openssh-server. The sequence runs converge, idempotence and verify; it has no check-mode step.
|
||||||
|
|
||||||
|
- Converge applies the `ubuntu_lxc` profile. It then loads the defaults through `tasks_from: validate.yml` without changing the host: every profile (`pve`, `ubuntu_lxc`, `ubuntu_vm`) passes validation and keeps its root login policy and key algorithms, a consumer `sshd_settings` override wins over the profile, and the `pve` guard accepts each value that allows root key login.
|
||||||
|
- Verify first checks the refusals: a run without `sshd_profile`, `PubkeyAuthentication no` (lock-out), a `pve` profile with `PermitRootLogin no` or `forced-commands-only`, a `pve` profile without `rsa-sha2-512`, SHA-1 `ssh-rsa`, and an unknown profile. Each but the missing profile is matched on its message.
|
||||||
|
- Verify then checks the converged host: the drop-in exists, `sshd -t` passes, the `ssh` unit is active, and `sshd -T` shows key login on and password and root login off.
|
||||||
|
- The `pve` profile is checked by rendering its drop-in to a scratch file and parsing it with `sshd -T -f`: root logs in with keys only and passwords stay off.
|
||||||
|
|
||||||
|
Not covered: the `pve` profile is not converged and no SSH login is attempted.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
|
|
||||||
|
- Idempotent: yes.
|
||||||
- `tasks/validate.yml` fails the play for an unknown profile, an empty merged result, `PasswordAuthentication no` without `PubkeyAuthentication yes`, a `pve` profile whose `PermitRootLogin` does not allow root key login (`prohibit-password`, its alias `without-password`, or `yes`; `no` and `forced-commands-only` are refused), a `pve` profile whose `HostKeyAlgorithms` or `PubkeyAcceptedAlgorithms` lacks `rsa-sha2-512` (the `+`/`-`/`^` list forms are not parsed and fail; write the full list), and any profile that lists SHA-1 `ssh-rsa` in either.
|
- `tasks/validate.yml` fails the play for an unknown profile, an empty merged result, `PasswordAuthentication no` without `PubkeyAuthentication yes`, a `pve` profile whose `PermitRootLogin` does not allow root key login (`prohibit-password`, its alias `without-password`, or `yes`; `no` and `forced-commands-only` are refused), a `pve` profile whose `HostKeyAlgorithms` or `PubkeyAcceptedAlgorithms` lacks `rsa-sha2-512` (the `+`/`-`/`^` list forms are not parsed and fail; write the full list), and any profile that lists SHA-1 `ssh-rsa` in either.
|
||||||
- The drop-in is installed with `validate: sshd -t -f %s`. The handler named `Restart SSH` reloads the service, and is skipped in check mode or when `sshd_reload` is false.
|
- The drop-in is installed with `validate: sshd -t -f %s`. The handler named `Restart SSH` reloads the service, and is skipped in check mode or when `sshd_reload` is false.
|
||||||
- `ssh-keygen -A` runs on every play and always reports ok.
|
- `ssh-keygen -A` runs on every play and always reports ok.
|
||||||
- `meta/argument_specs.yml` has only the `main` entry point. `tasks_from: validate.yml` is used by the molecule scenario to load defaults and exercise the guards, not by consumers, so it has no spec.
|
- `meta/argument_specs.yml` has only the `main` entry point. `tasks_from: validate.yml` is used by the molecule scenario to load defaults and exercise the guards, not by consumers, so it has no spec.
|
||||||
- The `pve` profile sets `PermitRootLogin prohibit-password`. Proxmox cluster SSH (migration, console proxy, replication) logs in as root with keys only. Passwords are already off through `PasswordAuthentication no`; this keeps root key-only if they are ever turned back on. Join nodes through the default API join, not `pvecm add --use_ssh`, which needs root password SSH.
|
- The `pve` profile sets `PermitRootLogin prohibit-password`. Proxmox cluster SSH (migration, console proxy, replication) logs in as root with keys only. Passwords are already off through `PasswordAuthentication no`; this keeps root key-only if they are ever turned back on. Join nodes through the default API join, not `pvecm add --use_ssh`, which needs root password SSH.
|
||||||
- Host key and public key algorithms are `ssh-ed25519` only, except in the `pve` profile, which allows `ssh-ed25519,rsa-sha2-512,rsa-sha2-256` for both: Proxmox cluster SSH (migration, console proxy) checks each node's RSA host key against `/etc/pve/nodes/<node>/ssh_known_hosts` and logs in with root's RSA key. SHA-1 `ssh-rsa` stays refused.
|
- Host key and public key algorithms are `ssh-ed25519` only, except in the `pve` profile, which allows `ssh-ed25519,rsa-sha2-512,rsa-sha2-256` for both: Proxmox cluster SSH (migration, console proxy) checks each node's RSA host key against `/etc/pve/nodes/<node>/ssh_known_hosts` and logs in with root's RSA key. SHA-1 `ssh-rsa` stays refused.
|
||||||
- Molecule: `molecule/default`, run by the Collection's CI. It converges the `ubuntu_lxc` profile; the `pve` profile is checked by rendering its drop-in to a scratch file and parsing it with `sshd -T -f`.
|
|
||||||
@@ -4,7 +4,11 @@ Applies an OS baseline chosen by `system_baseline_system_type`: apt upgrade, pac
|
|||||||
|
|
||||||
## Supported platforms
|
## Supported platforms
|
||||||
|
|
||||||
Ubuntu 24.04 (noble, covered by the molecule scenario) 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; Debian 13 is not verified by a test, and Ubuntu 22.04 (jammy) is listed in `meta/main.yml` but neither supported nor tested.
|
Ubuntu 24.04 (noble) passes the molecule scenario. The tasks use apt and the reboot check is limited to the Debian family. See `meta/main.yml`.
|
||||||
|
|
||||||
|
Untested platforms: Debian 13 (trixie, Proxmox hosts), not verified by a test; Ubuntu 22.04 (jammy), listed in `meta/main.yml` but neither supported nor tested.
|
||||||
|
|
||||||
|
The role targets Ubuntu guests (the `ubuntu_lxc` and `ubuntu_vm` profiles) and Proxmox VE hosts on Debian (the `pve` profile).
|
||||||
|
|
||||||
## Requirements and run order
|
## Requirements and run order
|
||||||
|
|
||||||
@@ -13,7 +17,7 @@ Ubuntu 24.04 (noble, covered by the molecule scenario) and Debian 13 (trixie, Pr
|
|||||||
- Use it by its fully qualified name, `mortis.kamino.system_baseline`.
|
- Use it by its fully qualified name, `mortis.kamino.system_baseline`.
|
||||||
- Collections: `community.general` (locale, timezone) and `ansible.posix` (sysctl, mount).
|
- 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.
|
- 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 dependencies: none.
|
||||||
|
|
||||||
## Role variables
|
## Role variables
|
||||||
|
|
||||||
@@ -61,10 +65,11 @@ system_baseline_profile_overrides:
|
|||||||
|
|
||||||
## Entry points
|
## 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.
|
- `main`: the whole baseline, as in the example play.
|
||||||
|
- `tasks_from: update`: see [`update`](#update).
|
||||||
|
- `tasks_from: reboot`: see [`reboot`](#reboot).
|
||||||
|
|
||||||
- `tasks_from: update`: apt update, upgrade, autoremove and autoclean, nothing else. It does not read `system_baseline_update`: calling the entry point is the request to update. In check mode it previews the upgrade; the main flow does not (see "Check mode").
|
The two task files besides `main` 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: 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. It reads `system_baseline_reboot_throttle` and `system_baseline_reboot_post_delay` as the main flow does, and refuses a bad value before anything runs. On other families the fact is not set, so read it with `default(false)`.
|
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
- name: Upgrade packages
|
- name: Upgrade packages
|
||||||
@@ -86,6 +91,20 @@ Besides `main`, two task files are a supported interface, for a caller that driv
|
|||||||
|
|
||||||
`validate.yml` has no spec and is not an entry point; the molecule scenario calls it to load the defaults.
|
`validate.yml` has no spec and is not an entry point; the molecule scenario calls it to load the defaults.
|
||||||
|
|
||||||
|
### `update`
|
||||||
|
|
||||||
|
`tasks_from: update`: apt update, upgrade, autoremove and autoclean, nothing else. It does not read `system_baseline_update`: calling the entry point is the request to update. In check mode it previews the upgrade; the main flow does not (see "Check mode").
|
||||||
|
|
||||||
|
### `reboot`
|
||||||
|
|
||||||
|
`tasks_from: reboot`: sets the fact `system_baseline_reboot_required` (see [Variables set by the role](#variables-set-by-the-role)) 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. It reads `system_baseline_reboot_throttle` and `system_baseline_reboot_post_delay` as the main flow does, and refuses a bad value before anything runs.
|
||||||
|
|
||||||
|
## Variables set by the role
|
||||||
|
|
||||||
|
| Name | Type | Set by | Description |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `system_baseline_reboot_required` | bool | `tasks_from: reboot` | True when `/var/run/reboot-required` exists. Set on Debian family hosts only; on other families the fact is not set, so read it with `default(false)`. |
|
||||||
|
|
||||||
## Tags
|
## Tags
|
||||||
|
|
||||||
`always` (validation), `update` (apt upgrade and the reboot), `packages`, `unattended-upgrades`, `locale`, `timezone`, `journald`, `apt-daily-timeout`, `sysctl`, `secure_tmp`, `tmux`.
|
`always` (validation), `update` (apt upgrade and the reboot), `packages`, `unattended-upgrades`, `locale`, `timezone`, `journald`, `apt-daily-timeout`, `sysctl`, `secure_tmp`, `tmux`.
|
||||||
@@ -102,7 +121,29 @@ Besides `main`, two task files are a supported interface, for a caller that driv
|
|||||||
- role: mortis.kamino.system_baseline
|
- role: mortis.kamino.system_baseline
|
||||||
```
|
```
|
||||||
|
|
||||||
## tmux on SSH login
|
## Tests
|
||||||
|
|
||||||
|
The scenario `molecule/default/` runs in CI only, on one platform: `${MOLECULE_IMAGE}`, an Ubuntu 24.04 (noble) container. It installs packages from the Ubuntu mirrors, so the runner needs outbound network. The sequence runs prepare, converge, idempotence and verify; it has no check-mode step.
|
||||||
|
|
||||||
|
- Converge first checks that the role refuses a bad input with its own message before any change: an unknown `system_baseline_system_type`, an unknown `system_baseline_apt_upgrade` (main flow and `update` entry point), a negative reboot throttle or a negative or boolean post-reboot delay (main flow and `reboot` entry point), a line break in `system_baseline_apt_daily_timeout`, and a bad package blacklist (a quote, a null item, a bare string).
|
||||||
|
- Converge then applies the `ubuntu_lxc` profile, with tmux autostart and `system_baseline_apt_daily_timeout: 1h`, and only resolves the `pve` and `ubuntu_vm` profiles and a consumer override, asserting the resolved inputs.
|
||||||
|
- Verify checks the installed and removed packages, the journal size cap, the apt settings in `20auto-upgrades` and `50unattended-upgrades`, the locale, and that systemd loaded the `apt-daily.service` timeout.
|
||||||
|
- Verify checks the tmux snippet: root-owned, valid shell, the session and quoted window command, no effect without a terminal, a session name or window command ending in a newline refused, and the file removed when autostart is off.
|
||||||
|
- Verify runs the `reboot` entry point with `system_baseline_reboot_if_required: false`, without and with `/var/run/reboot-required`, and checks the fact and that the host did not reboot.
|
||||||
|
- The `pve` origins pin is applied to the Ubuntu container and read back with `apt-config dump`, then removed again. The package blacklist is written, read back as a list, left alone by a second run and removed by an empty list.
|
||||||
|
|
||||||
|
Not covered: Molecule skips `sysctl`, `secure_tmp`, `update` and `timezone` (no privileged container); see `molecule/default/molecule.yml`. So `system_baseline_update` is checked only for its default; the skip itself is not exercised by a test. No host reboots, and the `pve` profile is not converged: Debian 13 is not verified by a test.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- Idempotent: yes.
|
||||||
|
- 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).
|
||||||
|
- 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.
|
||||||
|
|
||||||
|
### tmux on SSH login
|
||||||
|
|
||||||
With `system_baseline_tmux_autostart: true` an interactive SSH login attaches to the session `system_baseline_tmux_session` (created when missing), so a dropped connection loses nothing. The `ubuntu_lxc` and `ubuntu_vm` profiles install `tmux`; `pve` never gets the snippet.
|
With `system_baseline_tmux_autostart: true` an interactive SSH login attaches to the session `system_baseline_tmux_session` (created when missing), so a dropped connection loses nothing. The `ubuntu_lxc` and `ubuntu_vm` profiles install `tmux`; `pve` never gets the snippet.
|
||||||
|
|
||||||
@@ -120,7 +161,7 @@ system_baseline_tmux_windows:
|
|||||||
- The windows are made when the session is created; a login that re-attaches adds none, so a change applies from the next new session. A window closes when its command exits. A window command runs with `sh -c` from the tmux server of the first login, before `~/.profile` is read, so it does not see `~/.local/bin` and other additions made there: use absolute paths.
|
- The windows are made when the session is created; a login that re-attaches adds none, so a change applies from the next new session. A window closes when its command exits. A window command runs with `sh -c` from the tmux server of the first login, before `~/.profile` is read, so it does not see `~/.local/bin` and other additions made there: use absolute paths.
|
||||||
- Security: the name and commands are validated (`A-Za-z0-9_-`, one line) and shell-quoted, and come from the inventory, never from a user. The file is root-owned and not writable by its users. The commands run as the user who logs in, are readable by every user and show in `ps`: no secrets in a command. A session outlives the SSH connection, so a root session stays open until it is closed.
|
- Security: the name and commands are validated (`A-Za-z0-9_-`, one line) and shell-quoted, and come from the inventory, never from a user. The file is root-owned and not writable by its users. The commands run as the user who logs in, are readable by every user and show in `ps`: no secrets in a command. A session outlives the SSH connection, so a root session stays open until it is closed.
|
||||||
|
|
||||||
## Rebooting one host at a time
|
### Rebooting one host at a time
|
||||||
|
|
||||||
`system_baseline_reboot_throttle` is the `throttle` of the reboot task: how many hosts of the play reboot at once. The default `0` is no limit, which is what the role did before. `1` makes the hosts reboot one after the other, for a group whose members must not be down together (a cluster, a replicated pair). `system_baseline_reboot_post_delay` is the `post_reboot_delay` of the same task: the seconds to wait after a host answers again, so a service on it can settle before the next host goes down. Both are whole numbers, 0 or more; anything else stops the run before a host reboots, in the main flow and in `tasks_from: reboot`.
|
`system_baseline_reboot_throttle` is the `throttle` of the reboot task: how many hosts of the play reboot at once. The default `0` is no limit, which is what the role did before. `1` makes the hosts reboot one after the other, for a group whose members must not be down together (a cluster, a replicated pair). `system_baseline_reboot_post_delay` is the `post_reboot_delay` of the same task: the seconds to wait after a host answers again, so a service on it can settle before the next host goes down. Both are whole numbers, 0 or more; anything else stops the run before a host reboots, in the main flow and in `tasks_from: reboot`.
|
||||||
|
|
||||||
@@ -131,7 +172,7 @@ system_baseline_reboot_post_delay: 45
|
|||||||
|
|
||||||
The throttle applies to the reboot task only, and to hosts that need a reboot: it does not serialise the rest of the role. A play-level `serial` still works as before.
|
The throttle applies to the reboot task only, and to hosts that need a reboot: it does not serialise the rest of the role. A play-level `serial` still works as before.
|
||||||
|
|
||||||
## Bounding a hung apt-daily.service
|
### Bounding a hung apt-daily.service
|
||||||
|
|
||||||
With `system_baseline_apt_daily_timeout: 1h` the role writes `/etc/systemd/system/apt-daily.service.d/10-timeout.conf` (`[Service]`, `TimeoutStartSec=1h`) and runs `systemctl daemon-reload` when it changed. A hung `apt-daily.service` (a stuck mirror, a lock that never frees) is then stopped after that time instead of blocking every later apt run. Only `apt-daily.service` is changed, not `apt-daily-upgrade.service`.
|
With `system_baseline_apt_daily_timeout: 1h` the role writes `/etc/systemd/system/apt-daily.service.d/10-timeout.conf` (`[Service]`, `TimeoutStartSec=1h`) and runs `systemctl daemon-reload` when it changed. A hung `apt-daily.service` (a stuck mirror, a lock that never frees) is then stopped after that time instead of blocking every later apt run. Only `apt-daily.service` is changed, not `apt-daily-upgrade.service`.
|
||||||
|
|
||||||
@@ -140,11 +181,11 @@ With `system_baseline_apt_daily_timeout: 1h` the role writes `/etc/systemd/syste
|
|||||||
- `0` is accepted but means no timeout to systemd (the same as `infinity`), the opposite of a bound; set a real time span.
|
- `0` is accepted but means no timeout to systemd (the same as `infinity`), the opposite of a bound; set a real time span.
|
||||||
- Run only this step with `--tags apt-daily-timeout`.
|
- Run only this step with `--tags apt-daily-timeout`.
|
||||||
|
|
||||||
## Skipping the package update
|
### Skipping the package update
|
||||||
|
|
||||||
`system_baseline_update: false` skips the package update of the main flow, for hosts patched by a separate, operator-run flow (for example a full upgrade with a rolling reboot). Everything else, unattended-upgrades included, still runs. The reboot check still runs as well, so set `system_baseline_reboot_if_required: false` too when that flow owns the reboot. Running the play with `--skip-tags update` skips the same task for one run only, and also the reboot.
|
`system_baseline_update: false` skips the package update of the main flow, for hosts patched by a separate, operator-run flow (for example a full upgrade with a rolling reboot). Everything else, unattended-upgrades included, still runs. The reboot check still runs as well, so set `system_baseline_reboot_if_required: false` too when that flow owns the reboot. Running the play with `--skip-tags update` skips the same task for one run only, and also the reboot.
|
||||||
|
|
||||||
## Apt upgrade mode
|
### Apt upgrade mode
|
||||||
|
|
||||||
The profile key `apt_upgrade` (`safe` or `dist`, resolved to `system_baseline_apt_upgrade`) sets how the `update` flow upgrades packages. `safe` is `apt-get upgrade --with-new-pkgs`: it installs new dependencies but never removes a package, so an update that needs one removed is held back. `dist` is `apt-get dist-upgrade` (the same as `apt full-upgrade`), which can also remove packages. The `pve` profile uses `dist`, because the Proxmox VE documentation updates a node with `apt full-upgrade` and warns that a plain `apt upgrade` can leave a partially upgraded state; the Ubuntu profiles keep `safe`. Set `system_baseline_apt_upgrade` (or override the profile key) to change one host.
|
The profile key `apt_upgrade` (`safe` or `dist`, resolved to `system_baseline_apt_upgrade`) sets how the `update` flow upgrades packages. `safe` is `apt-get upgrade --with-new-pkgs`: it installs new dependencies but never removes a package, so an update that needs one removed is held back. `dist` is `apt-get dist-upgrade` (the same as `apt full-upgrade`), which can also remove packages. The `pve` profile uses `dist`, because the Proxmox VE documentation updates a node with `apt full-upgrade` and warns that a plain `apt upgrade` can leave a partially upgraded state; the Ubuntu profiles keep `safe`. Set `system_baseline_apt_upgrade` (or override the profile key) to change one host.
|
||||||
|
|
||||||
@@ -152,11 +193,11 @@ The profile key `apt_upgrade` (`safe` or `dist`, resolved to `system_baseline_ap
|
|||||||
- The `update` entry point follows the same input: it upgrades with `dist` when `system_baseline_system_type` is `pve`. Without a `system_baseline_system_type` (the entry point does not require one) it stays on `safe`.
|
- The `update` entry point follows the same input: it upgrades with `dist` when `system_baseline_system_type` is `pve`. Without a `system_baseline_system_type` (the entry point does not require one) it stays on `safe`.
|
||||||
- Only the apt upgrade changes. Autoremove and autoclean, the check-mode skip and unattended-upgrades are as before; the example blacklist below keeps unattended-upgrades away from the Proxmox packages.
|
- Only the apt upgrade changes. Autoremove and autoclean, the check-mode skip and unattended-upgrades are as before; the example blacklist below keeps unattended-upgrades away from the Proxmox packages.
|
||||||
|
|
||||||
## Check mode
|
### Check mode
|
||||||
|
|
||||||
In a dry run (`--check`) the main flow does not run the apt upgrade: a package that is only waiting for the next patch run, or a package cache older than an hour, is not drift, and the package module reports both as `changed`, so a scheduled dry run would flag every host whenever a package landed in between. The autoremove and autoclean step still runs, and is checked: a leftover package it would remove is reported as `changed`, on purpose. `apt-get autoclean` runs in this step in a real run, in the main flow and in the `update` entry point. The `update` entry point is unchanged: it is an explicit request to update, so in check mode it still previews the upgrade.
|
In a dry run (`--check`) the main flow does not run the apt upgrade: a package that is only waiting for the next patch run, or a package cache older than an hour, is not drift, and the package module reports both as `changed`, so a scheduled dry run would flag every host whenever a package landed in between. The autoremove and autoclean step still runs, and is checked: a leftover package it would remove is reported as `changed`, on purpose. `apt-get autoclean` runs in this step in a real run, in the main flow and in the `update` entry point. The `update` entry point is unchanged: it is an explicit request to update, so in check mode it still previews the upgrade.
|
||||||
|
|
||||||
## Unattended-upgrades origins
|
### Unattended-upgrades origins
|
||||||
|
|
||||||
A profile's `unattended_upgrade_origins` list pins the origins unattended-upgrades may install from. apt merges every file in `/etc/apt/apt.conf.d` and appends list entries across files, so a later file that only lists origins would widen the distribution's `50unattended-upgrades`, never narrow it. A non-empty list is therefore written to `/etc/apt/apt.conf.d/90unattended-upgrades-origins`, which sorts after `50unattended-upgrades`, clears `Unattended-Upgrade::Allowed-Origins` and `Unattended-Upgrade::Origins-Pattern` (apt's `#clear` directive) and sets only the listed patterns. The origin lists in `50unattended-upgrades` itself are not edited. An empty or missing list removes the drop-in.
|
A profile's `unattended_upgrade_origins` list pins the origins unattended-upgrades may install from. apt merges every file in `/etc/apt/apt.conf.d` and appends list entries across files, so a later file that only lists origins would widen the distribution's `50unattended-upgrades`, never narrow it. A non-empty list is therefore written to `/etc/apt/apt.conf.d/90unattended-upgrades-origins`, which sorts after `50unattended-upgrades`, clears `Unattended-Upgrade::Allowed-Origins` and `Unattended-Upgrade::Origins-Pattern` (apt's `#clear` directive) and sets only the listed patterns. The origin lists in `50unattended-upgrades` itself are not edited. An empty or missing list removes the drop-in.
|
||||||
|
|
||||||
@@ -166,7 +207,7 @@ A profile's `unattended_upgrade_origins` list pins the origins unattended-upgrad
|
|||||||
- A file in `/etc/apt/apt.conf.d` that sorts after `90unattended-upgrades-origins` can still add origins, and so can `/etc/apt/apt.conf`, which apt reads after `apt.conf.d`.
|
- A file in `/etc/apt/apt.conf.d` that sorts after `90unattended-upgrades-origins` can still add origins, and so can `/etc/apt/apt.conf`, which apt reads after `apt.conf.d`.
|
||||||
- Check the merged result on a host with `apt-config dump | grep -E 'Unattended-Upgrade::(Origins-Pattern|Allowed-Origins)'`.
|
- Check the merged result on a host with `apt-config dump | grep -E 'Unattended-Upgrade::(Origins-Pattern|Allowed-Origins)'`.
|
||||||
|
|
||||||
## Unattended-upgrades package blacklist
|
### Unattended-upgrades package blacklist
|
||||||
|
|
||||||
`system_baseline_unattended_upgrade_package_blacklist` keeps individual packages out of unattended-upgrades, for a host whose kernel or drivers must not change (for example one with hardware passthrough). Each entry is a regular expression matched against the package name, so `linux-image-.*` covers every kernel image; anchor an entry (`^name$`) when it must not match longer names too. A non-empty list is written to `/etc/apt/apt.conf.d/90unattended-upgrades-blacklist` as `Unattended-Upgrade::Package-Blacklist`. apt appends list entries across files, so the entries are added to those of `50unattended-upgrades`, which is not edited. An empty list removes the file. An entry may not hold a double quote, a backslash or a line break.
|
`system_baseline_unattended_upgrade_package_blacklist` keeps individual packages out of unattended-upgrades, for a host whose kernel or drivers must not change (for example one with hardware passthrough). Each entry is a regular expression matched against the package name, so `linux-image-.*` covers every kernel image; anchor an entry (`^name$`) when it must not match longer names too. A non-empty list is written to `/etc/apt/apt.conf.d/90unattended-upgrades-blacklist` as `Unattended-Upgrade::Package-Blacklist`. apt appends list entries across files, so the entries are added to those of `50unattended-upgrades`, which is not edited. An empty list removes the file. An entry may not hold a double quote, a backslash or a line break.
|
||||||
|
|
||||||
@@ -185,12 +226,3 @@ A profile's `unattended_upgrade_origins` list pins the origins unattended-upgrad
|
|||||||
- Like the other unattended-upgrades settings, it is applied only when `unattended-upgrades` is in the profile's packages.
|
- Like the other unattended-upgrades settings, it is applied only when `unattended-upgrades` is in the profile's packages.
|
||||||
- This is unattended-upgrades only. The role's own apt upgrade (`update` tag, and the `update` entry point) is not limited by it; set `system_baseline_update: false` for a host that is patched by a separate flow.
|
- This is unattended-upgrades only. The role's own apt upgrade (`update` tag, and the `update` entry point) is not limited by it; set `system_baseline_update: false` for a host that is patched by a separate flow.
|
||||||
- Check the merged result on a host with `apt-config dump | grep Package-Blacklist`.
|
- Check the merged result on a host with `apt-config dump | grep Package-Blacklist`.
|
||||||
|
|
||||||
## Notes
|
|
||||||
|
|
||||||
- The `pve` profile has no `ufw`; the `ubuntu_*` profiles install it and `fail2ban`.
|
|
||||||
- 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`. So `system_baseline_update` is checked only for its default; the skip itself is not exercised by a test. The `pve` origins pin is applied to the Ubuntu container and read back with `apt-config dump`.
|
|
||||||
- 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.
|
|
||||||
@@ -4,7 +4,9 @@ Disables and masks risky services, writes a systemd manager hardening drop-in an
|
|||||||
|
|
||||||
## Supported platforms
|
## Supported platforms
|
||||||
|
|
||||||
Hosts with systemd: Ubuntu 24.04 (noble) LXCs, Ubuntu VMs and Debian 13 (trixie) Proxmox hosts. The role is applied to the three system types in `systemd_hardening_profiles`: `pve` (Proxmox hosts), `ubuntu_lxc` and `ubuntu_vm`. The molecule scenario (`molecule/default/`, CI only) runs the `ubuntu_lxc` profile on Ubuntu 24.04 against stub unit files (a socket and a service for the ones that ship both, a service only and a socket only for the others), because the test image installs none of the services the role disables or masks. It checks that the stub sockets and services end up stopped and disabled or masked, that a listed unit that does not exist is skipped, the manager and service drop-ins (loaded by systemd after the reload) and the refusals; it cannot show that a real `rpcbind` or similar stops. The `pve` and `ubuntu_vm` profiles and Debian 13 are not verified by a test; Ubuntu 22.04 (jammy) is listed in `meta/main.yml` but neither supported nor tested.
|
The molecule scenario passes on Ubuntu 24.04 (noble); see [Tests](#tests). The role is meant for hosts with systemd: Ubuntu 24.04 (noble) LXCs, Ubuntu 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`.
|
||||||
|
|
||||||
|
Untested platforms: Debian 13 (trixie), and Ubuntu 22.04 (jammy), which is listed in `meta/main.yml` but neither supported nor tested.
|
||||||
|
|
||||||
## Requirements and run order
|
## Requirements and run order
|
||||||
|
|
||||||
@@ -12,6 +14,7 @@ Hosts with systemd: Ubuntu 24.04 (noble) LXCs, Ubuntu VMs and Debian 13 (trixie)
|
|||||||
- Use it by its fully qualified name, `mortis.kamino.systemd_hardening`.
|
- 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.
|
- Run it after your baseline role and before the roles that manage firewalls and jails.
|
||||||
- Needs privilege escalation: tasks use `become`.
|
- Needs privilege escalation: tasks use `become`.
|
||||||
|
- Role dependencies: none.
|
||||||
|
|
||||||
## Role variables
|
## Role variables
|
||||||
|
|
||||||
@@ -47,8 +50,13 @@ Only `always` (the `systemd_hardening_system_type` assert) works as intended. `d
|
|||||||
NoNewPrivileges: true
|
NoNewPrivileges: true
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
`molecule/default` runs in CI only, on one platform: Ubuntu 24.04 (noble), the `molecule-ubuntu2404` image (`${MOLECULE_IMAGE}`). It runs the `ubuntu_lxc` profile against stub unit files (a socket and a service for the ones that ship both, a service only and a socket only for the others), because the test image installs none of the services the role disables or masks. It checks that the stub sockets and services end up stopped and disabled or masked, that a listed unit that does not exist is skipped, the manager and service drop-ins (loaded by systemd after the reload) and the refusals: a missing or unknown `systemd_hardening_system_type`, and a `systemd_hardening_services` entry or value that is not a mapping. It cannot show that a real `rpcbind` or similar stops. The `pve` and `ubuntu_vm` profiles and Debian 13 are not verified by a test.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
|
|
||||||
|
- Idempotent: yes.
|
||||||
- Every name in `systemd_hardening_disable_services` and `systemd_hardening_mask_services` is looked up as a socket and as a service, with or without the `.service` or `.socket` suffix. Only units that systemd has a unit file for (`LoadState` is not `not-found`) are disabled or masked, the socket first: a stopped service whose socket still listens is started again by the next connection. A name with only a service, only a socket, or neither is fine. The role asks about the listed units only, with one `systemctl show`, and does not list every unit file. A template name such as `[email protected]` is not supported: that call fails.
|
- Every name in `systemd_hardening_disable_services` and `systemd_hardening_mask_services` is looked up as a socket and as a service, with or without the `.service` or `.socket` suffix. Only units that systemd has a unit file for (`LoadState` is not `not-found`) are disabled or masked, the socket first: a stopped service whose socket still listens is started again by the next connection. A name with only a service, only a socket, or neither is fine. The role asks about the listed units only, with one `systemctl show`, and does not list every unit file. A template name such as `[email protected]` is not supported: that call fails.
|
||||||
- `systemctl disable` does nothing for a static unit (one with no `[Install]` section), so the systemd module can report `changed` on every run for it; list only names whose units can be enabled, and note that this now applies to a listed name's socket as well.
|
- `systemctl disable` does nothing for a static unit (one with no `[Install]` section), so the systemd module can report `changed` on every run for it; list only names whose units can be enabled, and note that this now applies to a listed name's socket as well.
|
||||||
- The manager drop-in (`DefaultLimitNOFILE`, `DefaultLimitNPROC`, `DefaultLimitCORE`, and task, memory and CPU accounting) is written verbatim by `tasks/harden_manager.yml` and has no variable.
|
- 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.
|
||||||
|
|||||||
+20
-4
@@ -4,11 +4,14 @@ Installs the Traefik reverse proxy as a systemd-managed binary, renders its stat
|
|||||||
|
|
||||||
## Supported platforms
|
## Supported platforms
|
||||||
|
|
||||||
Ubuntu 24.04 (noble), the image the molecule scenario runs on. The role uses `ansible.builtin.apt`, so Debian-family hosts only, and needs outbound access to github.com for the release archive and checksum file. Only `traefik_install_type: binary` exists.
|
Ubuntu 24.04 (noble), the platform the molecule scenario runs on. The role uses `ansible.builtin.apt`, so Debian-family hosts only, and needs outbound access to github.com for the release archive and checksum file. Only `traefik_install_type: binary` exists.
|
||||||
|
|
||||||
|
The role targets Ubuntu hosts that run the reverse proxy, not Proxmox nodes, so it does not cover Debian trixie.
|
||||||
|
|
||||||
## Requirements and run order
|
## Requirements and run order
|
||||||
|
|
||||||
- Use it by its fully qualified name, `mortis.kamino.traefik`.
|
- Use it by its fully qualified name, `mortis.kamino.traefik`.
|
||||||
|
- Role dependencies: it includes `mortis.kamino.ufw` (`service_rules`) and `mortis.kamino._binary_update`, both of this Collection.
|
||||||
- Run the `system_baseline` and `ufw` roles of this Collection first. The configure tasks pass `traefik_ufw_service_rules` (ports 80 and 443 by default) to the `service_rules` entry point of `mortis.kamino.ufw`, owner `traefik`, which needs ufw installed and active and the SSH rule in place. See the README of `mortis.kamino.ufw`.
|
- Run the `system_baseline` and `ufw` roles of this Collection first. The configure tasks pass `traefik_ufw_service_rules` (ports 80 and 443 by default) to the `service_rules` entry point of `mortis.kamino.ufw`, owner `traefik`, which needs ufw installed and active and the SSH rule in place. See the README of `mortis.kamino.ufw`.
|
||||||
- Secrets: `traefik_cloudflare_email` and `traefik_cloudflare_api_token` have no role default and are required. Map them from vaulted variables in inventory; the role never holds the values itself.
|
- Secrets: `traefik_cloudflare_email` and `traefik_cloudflare_api_token` have no role default and are required. Map them from vaulted variables in inventory; the role never holds the values itself.
|
||||||
- `traefik_domain` has no role default and must be set in inventory.
|
- `traefik_domain` has no role default and must be set in inventory.
|
||||||
@@ -74,14 +77,27 @@ Ubuntu 24.04 (noble), the image the molecule scenario runs on. The role uses `an
|
|||||||
|
|
||||||
Update or remove: pass `-e traefik_update=true`, or `-e "traefik_remove=true traefik_remove_data=true" --tags remove`.
|
Update or remove: pass `-e traefik_update=true`, or `-e "traefik_remove=true traefik_remove_data=true" --tags remove`.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
The `default` molecule scenario runs on one platform, Ubuntu 24.04 (noble) (`${MOLECULE_IMAGE}`). It needs outbound network: the role installs packages with apt and downloads real Traefik releases from GitHub. Converge runs `mortis.kamino.ufw`, then the role. Verify covers:
|
||||||
|
|
||||||
|
- The input guards, first: one play expects the failure message containing `unauthenticated Traefik dashboard` (the dashboard guard: enabled without valid `user:hash` users); the next expects `collides with the middleware`, raised by the dashboard-auth collision assert, which runs whenever users are set, also with the dashboard off.
|
||||||
|
- The install: the pinned version runs, and only the binary is left from the archive.
|
||||||
|
- Files: `traefik.env` mode 0600 owned by root, `dynamic.yml` mode 0600 owned by `traefik`, `traefik.yml` mode 0600, the binary mode 0755; the logrotate configuration, which `logrotate --debug` parses.
|
||||||
|
- Rendering: the ACME resolvers render when set and are absent when empty; the dashboard is off by default with the extra app routed, and renders behind basicAuth when enabled (a template render, not a running dashboard).
|
||||||
|
- The service: running and enabled with `NoNewPrivileges`, `MemoryDenyWriteExecute` and `CAP_NET_BIND_SERVICE`, listening on 80 and 443 and redirecting http to https; ufw allows 80 and 443 next to SSH, with the traefik owner tag, in order.
|
||||||
|
- The update path: it updates to another release and back with `traefik_update` (a real download, checksum check and swap) and asserts the version, an active unit and no leftovers.
|
||||||
|
- The remove path, last: unit and binary are deleted, the service is no longer active, and only the traefik ufw rules are removed.
|
||||||
|
|
||||||
|
The scenario disables the namespace-based sandboxing and the `User=` switch with a drop-in because its container is unprivileged, so that sandboxing is not covered by CI. Certificate issuance is not covered: the Cloudflare credentials are dummies.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
|
|
||||||
|
- Idempotent: yes.
|
||||||
- The role is not a state selector. `main.yml` runs prerequisites and configure unless `traefik_remove` is true; install runs only when the binary is absent; update only when `traefik_update` is true; remove only when `traefik_remove` is true, and then every other task in `main.yml` is skipped.
|
- The role is not a state selector. `main.yml` runs prerequisites and configure unless `traefik_remove` is true; install runs only when the binary is absent; update only when `traefik_update` is true; remove only when `traefik_remove` is true, and then every other task in `main.yml` is skipped.
|
||||||
- Download integrity: the archive SHA-256 must appear in the release's checksum file or the play fails.
|
- Download integrity: the archive SHA-256 must appear in the release's checksum file or the play fails.
|
||||||
- Secrets: `traefik.env` (mode 0600, root) and `dynamic.yml` are rendered with `no_log: true`, and no backups are kept, so `--diff` never shows them. `dynamic.yml` may hold dashboard htpasswd hashes.
|
- Secrets: `traefik.env` (mode 0600, root) and `dynamic.yml` are rendered with `no_log: true`, and no backups are kept, so `--diff` never shows them. `dynamic.yml` may hold dashboard htpasswd hashes.
|
||||||
- The unit sets `NoNewPrivileges`, `ProtectSystem=full`, `ProtectHome`, `PrivateTmp`, `PrivateDevices`, `ProtectKernelModules`, `ProtectKernelTunables`, `MemoryDenyWriteExecute` and `CAP_NET_BIND_SERVICE`. The molecule scenario disables the namespace-based sandboxing and the `User=` switch with a drop-in because its container is unprivileged, so that sandboxing is not covered by CI.
|
- The unit sets `NoNewPrivileges`, `ProtectSystem=full`, `ProtectHome`, `PrivateTmp`, `PrivateDevices`, `ProtectKernelModules`, `ProtectKernelTunables`, `MemoryDenyWriteExecute` and `CAP_NET_BIND_SERVICE`; see Tests for what CI covers of them.
|
||||||
- The role fails early (assert at the top of `tasks/main.yml`, runs under any tag and before the `remove` include) when `traefik_dns_challenge_resolvers` is not a list of `host:port` (or `[ipv6]:port`) strings, when `traefik_bin_path` is not an absolute path ending in `traefik`, or when `traefik_config_dir` or `traefik_service_unit` is not absolute.
|
- The role fails early (assert at the top of `tasks/main.yml`, runs under any tag and before the `remove` include) when `traefik_dns_challenge_resolvers` is not a list of `host:port` (or `[ipv6]:port`) strings, when `traefik_bin_path` is not an absolute path ending in `traefik`, or when `traefik_config_dir` or `traefik_service_unit` is not absolute.
|
||||||
- The DNS-challenge resolvers are environment-specific, so the role default is empty, which omits the `resolvers` block.
|
- The DNS-challenge resolvers are environment-specific, so the role default is empty, which omits the `resolvers` block.
|
||||||
- The play fails when the service is not `active` after start.
|
- The play fails when the service is not `active` after start.
|
||||||
- Molecule's verify also updates to another release and back with `traefik_update` (a real download, checksum check and swap) and asserts the version, an active unit and no leftovers.
|
|
||||||
- Molecule's second play expects the failure message containing `unauthenticated Traefik dashboard` (the dashboard guard: enabled without valid `user:hash` users); its third play expects `collides with the middleware`, raised by the dashboard-auth collision assert, which runs whenever users are set, also with the dashboard off.
|
|
||||||
+46
-20
@@ -4,16 +4,22 @@ Installs UFW and applies sysctl overrides, `/etc/ufw/before.rules`, default poli
|
|||||||
|
|
||||||
## Supported platforms
|
## Supported platforms
|
||||||
|
|
||||||
Ubuntu 24.04 (noble), the image the molecule scenario runs on. 22.04 (jammy) is listed in `meta/main.yml` but not verified by a test. The role uses `ansible.builtin.package` and the `community.general.ufw` module; `community.general` is a dependency of the Collection.
|
Ubuntu 24.04 (noble), the platform the molecule scenario runs on.
|
||||||
|
|
||||||
|
Untested platforms: Ubuntu 22.04 (jammy), listed in `meta/main.yml` but not verified by a test.
|
||||||
|
|
||||||
|
Ubuntu hosts only: the role firewalls Ubuntu guests; the `pve` profile of `system_baseline` does not install ufw, so Proxmox hosts are not targeted.
|
||||||
|
|
||||||
## Requirements and run order
|
## Requirements and run order
|
||||||
|
|
||||||
|
- The role uses `ansible.builtin.package` and the `community.general.ufw` module; `community.general` is a dependency of the Collection.
|
||||||
- Use it by its fully qualified name, `mortis.kamino.ufw`.
|
- Use it by its fully qualified name, `mortis.kamino.ufw`.
|
||||||
- Run the `system_baseline` role of this Collection before this role. UFW's stock `/etc/ufw/sysctl.conf` re-applies sysctl values when UFW is enabled, which undoes baseline hardening. Mirror the baseline values in `ufw_sysctl_overrides`.
|
- Run the `system_baseline` role of this Collection before this role. UFW's stock `/etc/ufw/sysctl.conf` re-applies sysctl values when UFW is enabled, which undoes baseline hardening. Mirror the baseline values in `ufw_sysctl_overrides`.
|
||||||
- Main entry point: apply it in the play that hardens a host, after `system_baseline` and `systemd_hardening`, before `fail2ban`.
|
- Main entry point: apply it in the play that hardens a host, after `system_baseline` and `systemd_hardening`, before `fail2ban`.
|
||||||
- `service_rules` entry point: called by each service role that owns firewall rules (`include_role` with `tasks_from: service_rules`), after the main entry point has run, passing `ufw_service_name` and `ufw_service_rules`.
|
- `service_rules` entry point: called by each service role that owns firewall rules (`include_role` with `tasks_from: service_rules`), after the main entry point has run, passing `ufw_service_name` and `ufw_service_rules`.
|
||||||
- `orphan_rules` entry point: called once per host after every service role ran, with `ufw_managed_owners` set to the owners that are still managed.
|
- `orphan_rules` entry point: called once per host after every service role ran, with `ufw_managed_owners` set to the owners that are still managed.
|
||||||
- `ufw_rules` must contain an allow or limit rule for the SSH port (see Notes).
|
- `ufw_rules` must contain an allow or limit rule for the SSH port (see Notes).
|
||||||
|
- Role dependencies: none.
|
||||||
|
|
||||||
## Role variables
|
## Role variables
|
||||||
|
|
||||||
@@ -33,26 +39,13 @@ Main entry point:
|
|||||||
|
|
||||||
There is no discovery by variable name, and a variable that looks like one fails the play: at the start of the role, a guard refuses any variable whose name matches `^.+_ufw_(before_)?rules$` (a `foo_ufw_rules` or `foo_ufw_before_rules` defined as any variable visible to the host: inventory, play and role vars, extra vars, set_fact and registered variables) and names it in the error. Pass service rules through `tasks_from: service_rules` (`ufw_service_name`, `ufw_service_rules`; a caller's own `<role>_ufw_service_rules` does not match), or put base rules in `ufw_rules`. The guard is unconditional, has no switch, and carries the tags `ufw` and `always`. `ufw_before_rules` is base-only: no entry point adds before-rules.
|
There is no discovery by variable name, and a variable that looks like one fails the play: at the start of the role, a guard refuses any variable whose name matches `^.+_ufw_(before_)?rules$` (a `foo_ufw_rules` or `foo_ufw_before_rules` defined as any variable visible to the host: inventory, play and role vars, extra vars, set_fact and registered variables) and names it in the error. Pass service rules through `tasks_from: service_rules` (`ufw_service_name`, `ufw_service_rules`; a caller's own `<role>_ufw_service_rules` does not match), or put base rules in `ufw_rules`. The guard is unconditional, has no switch, and carries the tags `ufw` and `always`. `ufw_before_rules` is base-only: no entry point adds before-rules.
|
||||||
|
|
||||||
## Tags
|
## Entry points
|
||||||
|
|
||||||
`ufw` (everything), `ufw_install`, `ufw_sysctl`, `ufw_aggregate`, `ufw_validate`, `ufw_before_rules`, `ufw_defaults`, `ufw_rules`, `ufw_enable`.
|
- `main`: applies `ufw_rules` and the base configuration, as in the example play.
|
||||||
|
- `service_rules`: a service role's own rules, see [`service_rules`](#service_rules).
|
||||||
|
- `orphan_rules`: cleans up the rules of owners no longer managed, see [`orphan_rules`](#orphan_rules).
|
||||||
|
|
||||||
Skipping `ufw_aggregate` leaves the lists the later tasks read (`ufw_aggregated_rules`, `ufw_aggregated_before_rules`) undefined or stale, so do not select a later tag alone.
|
### `service_rules`
|
||||||
|
|
||||||
## Example play
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
- name: Harden and firewall the servers
|
|
||||||
hosts: servers
|
|
||||||
roles:
|
|
||||||
- role: mortis.kamino.ufw
|
|
||||||
vars:
|
|
||||||
ufw_rules:
|
|
||||||
- {rule: allow, port: 22, proto: tcp, comment: ssh}
|
|
||||||
- {rule: allow, port: 8080, proto: tcp, from: 10.0.0.0/8, comment: web}
|
|
||||||
```
|
|
||||||
|
|
||||||
## `service_rules` entry point
|
|
||||||
|
|
||||||
A service role that owns firewall rules calls the role with `include_role` and `tasks_from: service_rules` after the main entry has run, with `apply: {tags: [...]}` so `--tags <role>` reaches these tasks. The entry point installs nothing and touches no default policy, no `before.rules` and no base rule. Outside check mode (`--check` or the `check_mode` keyword; the role detects it with a skipped probe task, not `ansible_check_mode`) it fails when ufw is not installed and active. In check mode it skips the reconcile only when `ufw status` fails (ufw not installed yet, the main entry may not have reached the host); a host with ufw installed but inactive is reconciled as usual.
|
A service role that owns firewall rules calls the role with `include_role` and `tasks_from: service_rules` after the main entry has run, with `apply: {tags: [...]}` so `--tags <role>` reaches these tasks. The entry point installs nothing and touches no default policy, no `before.rules` and no base rule. Outside check mode (`--check` or the `check_mode` keyword; the role detects it with a skipped probe task, not `ansible_check_mode`) it fails when ufw is not installed and active. In check mode it skips the reconcile only when `ufw status` fails (ufw not installed yet, the main entry may not have reached the host); a host with ufw installed but inactive is reconciled as usual.
|
||||||
|
|
||||||
@@ -91,7 +84,7 @@ Tags: `ufw`, `ufw_service_rules`. They select the entry point's tasks under `--t
|
|||||||
|
|
||||||
**Limitations.** Two owners cannot hold the same spec: a shared rule such as 80/443 aborts the second owner. A service rule with the same spec as a rule of the base `ufw_rules` list is retagged by the service call and rewritten by the next base run, back and forth, so keep the two lists disjoint.
|
**Limitations.** Two owners cannot hold the same spec: a shared rule such as 80/443 aborts the second owner. A service rule with the same spec as a rule of the base `ufw_rules` list is retagged by the service call and rewritten by the next base run, back and forth, so keep the two lists disjoint.
|
||||||
|
|
||||||
## `orphan_rules` entry point
|
### `orphan_rules`
|
||||||
|
|
||||||
`service_rules` cleans up the rules of an owner only while that owner's role still runs. A service removed from a host leaves its tagged rules behind, and nothing calls `service_rules` for it again. `include_role` with `tasks_from: orphan_rules` finds those rules.
|
`service_rules` cleans up the rules of an owner only while that owner's role still runs. A service removed from a host leaves its tagged rules behind, and nothing calls `service_rules` for it again. `include_role` with `tasks_from: orphan_rules` finds those rules.
|
||||||
|
|
||||||
@@ -124,8 +117,41 @@ An **orphan** is a rule tagged `ansible-ufw[<owner>:<key>]` whose owner is neith
|
|||||||
tags: [ufw, ufw_orphan_rules]
|
tags: [ufw, ufw_orphan_rules]
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Tags
|
||||||
|
|
||||||
|
`ufw` (everything), `ufw_install`, `ufw_sysctl`, `ufw_aggregate`, `ufw_validate`, `ufw_before_rules`, `ufw_defaults`, `ufw_rules`, `ufw_enable`.
|
||||||
|
|
||||||
|
Skipping `ufw_aggregate` leaves the lists the later tasks read (`ufw_aggregated_rules`, `ufw_aggregated_before_rules`) undefined or stale, so do not select a later tag alone.
|
||||||
|
|
||||||
|
## Example play
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- name: Harden and firewall the servers
|
||||||
|
hosts: servers
|
||||||
|
roles:
|
||||||
|
- role: mortis.kamino.ufw
|
||||||
|
vars:
|
||||||
|
ufw_rules:
|
||||||
|
- {rule: allow, port: 22, proto: tcp, comment: ssh}
|
||||||
|
- {rule: allow, port: 8080, proto: tcp, from: 10.0.0.0/8, comment: web}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
The scenario `molecule/default/` runs in CI only, on one platform: `${MOLECULE_IMAGE}`, an Ubuntu 24.04 (noble) container with `NET_ADMIN`. The sequence runs prepare, converge, idempotence and verify; it has no check-mode step.
|
||||||
|
|
||||||
|
- Prepare installs ufw and stores rules the role must handle: an untagged manual rule, a manual rule the base list deletes, and tagged rules of service owners that are stale, removed or orphaned, some of them looking like an SSH path (port 22 with a source, no port, a range, an application profile named like SSH).
|
||||||
|
- Converge applies the base `ufw_rules` (one entry with `delete: true`), then calls `service_rules` for several owners (purge on, purge off, `absent`), and `orphan_rules` with no list, an empty list, report only and purge.
|
||||||
|
- Verify first checks that each refusal stops the run with its message and changes nothing: default deny without an SSH rule (also when the SSH rule is only deleted, or added and deleted), a stray `*_ufw_rules` or `*_ufw_before_rules` variable, the invalid `service_rules` inputs (owner name, reserved `base`, a quote in a comment, a rule another owner holds, a rule that would retag the SSH rule, an unknown key, an interface without a direction, a purge with an empty list), and an invalid managed owner for `orphan_rules`.
|
||||||
|
- Verify then reads `ufw status verbose` and `ufw show added`: ufw is active with default deny incoming, the base rules are loaded, the deleted rule is gone, the manual and SSH rules are untouched, the service rules carry their owner tag, stale and orphan rules are deleted only where purging was on and only when they cannot carry SSH.
|
||||||
|
- Verify checks `before.rules`: the loopback accept, the INVALID-state drop behind its logging rule and in its place among the input rules.
|
||||||
|
- Verify runs `service_rules` under the `check_mode` keyword and checks that the rule list did not change.
|
||||||
|
|
||||||
|
Not covered: `ufw_before_rules` entries and `ufw_sysctl_overrides` are never set, and `orphan_rules` is not run in check mode.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
|
|
||||||
|
- Idempotent: yes.
|
||||||
- Lock-out guard: `defaults.yml` sets the deny policy before `rules.yml` adds any rule. When `ufw_enabled`, `ufw_manage_rules` and `ufw_require_ssh_allow` are true and the incoming default is deny or reject, the play fails unless `ufw_rules` holds an allow or limit rule for `ufw_ssh_port` that is TCP (or has no `proto`) and has `direction: in` or no `direction`. `direction: incoming`, which the module accepts, is not counted, so write `in`. Any `from`, `to` or `interface` restriction still counts; the guard cannot know the control host's address. An entry with `delete: true` never counts.
|
- Lock-out guard: `defaults.yml` sets the deny policy before `rules.yml` adds any rule. When `ufw_enabled`, `ufw_manage_rules` and `ufw_require_ssh_allow` are true and the incoming default is deny or reject, the play fails unless `ufw_rules` holds an allow or limit rule for `ufw_ssh_port` that is TCP (or has no `proto`) and has `direction: in` or no `direction`. `direction: incoming`, which the module accepts, is not counted, so write `in`. Any `from`, `to` or `interface` restriction still counts; the guard cannot know the control host's address. An entry with `delete: true` never counts.
|
||||||
- Replacing a base rule: list the new rule and the old one with `delete: true` (a boolean). Deletes are applied after every other rule, whatever their place in the list, so the replacement exists before the old rule goes, which matters when narrowing the SSH rule. The comment of a delete entry is not sent, so the rule matches whatever its comment, and a delete of a rule that is already gone changes nothing. An entry that deletes a rule the same list adds (same `rule`, `port`, `proto`, `from`, `to`, `interface` and `direction`, where no `direction` is `in` and no `from` or `to` is `any`) fails the play. A delete without an address removes the IPv4 and the IPv6 rule; a replacement with an IPv4 `from` allows IPv4 only, so check that the hosts you connect from are covered before narrowing SSH. `delete` is for `ufw_rules` only; `service_rules` removes its own stale rules.
|
- Replacing a base rule: list the new rule and the old one with `delete: true` (a boolean). Deletes are applied after every other rule, whatever their place in the list, so the replacement exists before the old rule goes, which matters when narrowing the SSH rule. The comment of a delete entry is not sent, so the rule matches whatever its comment, and a delete of a rule that is already gone changes nothing. An entry that deletes a rule the same list adds (same `rule`, `port`, `proto`, `from`, `to`, `interface` and `direction`, where no `direction` is `in` and no `from` or `to` is `any`) fails the play. A delete without an address removes the IPv4 and the IPv6 rule; a replacement with an IPv4 `from` allows IPv4 only, so check that the hosts you connect from are covered before narrowing SSH. `delete` is for `ufw_rules` only; `service_rules` removes its own stale rules.
|
||||||
- `before.rules` is a template derived from UFW's own `before.rules` (GPL-3.0-only, see `NOTICE`) that fully replaces the stock file, including a loopback accept, conntrack (established accept and INVALID-state drop), ICMP and mDNS/UPnP entries. It is deployed whenever `ufw_enabled` is true, even with no before-rules.
|
- `before.rules` is a template derived from UFW's own `before.rules` (GPL-3.0-only, see `NOTICE`) that fully replaces the stock file, including a loopback accept, conntrack (established accept and INVALID-state drop), ICMP and mDNS/UPnP entries. It is deployed whenever `ufw_enabled` is true, even with no before-rules.
|
||||||
|
|||||||
@@ -4,7 +4,9 @@ Manages the primary ansible user and additional users, their `authorized_keys`,
|
|||||||
|
|
||||||
## Supported platforms
|
## Supported platforms
|
||||||
|
|
||||||
Ubuntu 24.04 (noble, covered by the molecule scenario) and 22.04 (jammy) and Debian trixie (Proxmox VE nodes), listed in `meta/main.yml`; only 24.04 is converged by a test. The role installs sudo with apt.
|
Ubuntu 24.04 (noble), the only platform converged by a test (see [Tests](#tests)). The role installs sudo with apt.
|
||||||
|
|
||||||
|
Untested platforms: Ubuntu 22.04 (jammy) and Debian trixie (Proxmox VE nodes), listed in `meta/main.yml`.
|
||||||
|
|
||||||
## Requirements and run order
|
## Requirements and run order
|
||||||
|
|
||||||
@@ -14,7 +16,7 @@ Ubuntu 24.04 (noble, covered by the molecule scenario) and 22.04 (jammy) and Deb
|
|||||||
- Set `gather_facts: false` on the play. On a fresh guest the configured user cannot log in yet, so fact gathering would mark the host unreachable before the role's root fallback runs. The role uses no facts.
|
- Set `gather_facts: false` on the play. On a fresh guest the configured user cannot log in yet, so fact gathering would mark the host unreachable before the role's root fallback runs. The role uses no facts.
|
||||||
- The bootstrap tries `wait_for_connection` as the configured user, and on failure switches `ansible_ssh_user` to `root` and pings, with the same deploy key (`ansible_ssh_private_key_file`); no password is ever used. Once the users and keys are written it switches back to the configured user and checks the new connection (`tasks/handback.yml`; skipped in check mode), because the fact would otherwise last for the rest of the run and later plays would connect as root after the `sshd` role of this Collection refused it. Where the fallback applies: a new LXC, whose root gets the deploy key from the provisioning step and whose stock Ubuntu sshd admits root by key on first boot. A VM never needs it: cloud-init creates the configured user with the key (`ciuser`/`sshkeys`), and root is not given the key. A freshly installed Proxmox node needs the deploy key in root's `authorized_keys` first. After the `sshd` role has run, root login is refused (`PermitRootLogin: no` on `ubuntu_lxc` and `ubuntu_vm`, `prohibit-password` on `pve`), so a host whose configured user broke later is recovered from its Proxmox node: `pct enter` for an LXC, `qm terminal` or the console for a VM, the node's own console for a Proxmox host.
|
- The bootstrap tries `wait_for_connection` as the configured user, and on failure switches `ansible_ssh_user` to `root` and pings, with the same deploy key (`ansible_ssh_private_key_file`); no password is ever used. Once the users and keys are written it switches back to the configured user and checks the new connection (`tasks/handback.yml`; skipped in check mode), because the fact would otherwise last for the rest of the run and later plays would connect as root after the `sshd` role of this Collection refused it. Where the fallback applies: a new LXC, whose root gets the deploy key from the provisioning step and whose stock Ubuntu sshd admits root by key on first boot. A VM never needs it: cloud-init creates the configured user with the key (`ciuser`/`sshkeys`), and root is not given the key. A freshly installed Proxmox node needs the deploy key in root's `authorized_keys` first. After the `sshd` role has run, root login is refused (`PermitRootLogin: no` on `ubuntu_lxc` and `ubuntu_vm`, `prohibit-password` on `pve`), so a host whose configured user broke later is recovered from its Proxmox node: `pct enter` for an LXC, `qm terminal` or the console for a VM, the node's own console for a Proxmox host.
|
||||||
- Runs before the `sshd` role, after the step that creates the guest (LXC or VM), and first in a play for Proxmox nodes, which have no provisioning step. A play for Proxmox nodes should set `user_management_disable_cloud_init: false`.
|
- Runs before the `sshd` role, after the step that creates the guest (LXC or VM), and first in a play for Proxmox nodes, which have no provisioning step. A play for Proxmox nodes should set `user_management_disable_cloud_init: false`.
|
||||||
- The role has no declared dependencies.
|
- Role dependencies: none.
|
||||||
|
|
||||||
## Role variables
|
## Role variables
|
||||||
|
|
||||||
@@ -33,6 +35,13 @@ Ubuntu 24.04 (noble, covered by the molecule scenario) and 22.04 (jammy) and Deb
|
|||||||
| `user_management_remove_home` | `true` | no | Remove home directories of absent users, passed as `remove` to every user task |
|
| `user_management_remove_home` | `true` | no | Remove home directories of absent users, passed as `remove` to every user task |
|
||||||
| `user_management_become_password_hashed` | none | yes, unless `user_management_ansible_user` is overridden | Password hash read by the primary user default |
|
| `user_management_become_password_hashed` | none | yes, unless `user_management_ansible_user` is overridden | Password hash read by the primary user default |
|
||||||
|
|
||||||
|
## Variables set by the role
|
||||||
|
|
||||||
|
- `user_management_all_users`: the managed users, primary user first, then `user_management_other_users`. The task that builds it is `no_log`.
|
||||||
|
- `user_management_managed_usernames`: the names of the managed users.
|
||||||
|
|
||||||
|
Both are set under the `always` tag.
|
||||||
|
|
||||||
## Tags
|
## Tags
|
||||||
|
|
||||||
`always` (user list facts, bootstrap and handback), `create_users`, `ssh_keys`, `lock_root_password`, `disable_cloud_init`.
|
`always` (user list facts, bootstrap and handback), `create_users`, `ssh_keys`, `lock_root_password`, `disable_cloud_init`.
|
||||||
@@ -53,16 +62,29 @@ Ubuntu 24.04 (noble, covered by the molecule scenario) and 22.04 (jammy) and Deb
|
|||||||
- "ssh-ed25519 <public-key> alice"
|
- "ssh-ed25519 <public-key> alice"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
`molecule/default` runs in the Collection's CI, on one platform: Ubuntu 24.04 (noble), the `molecule-ubuntu2404` image (`${MOLECULE_IMAGE}`). Prepare creates a stale user to remove, plants an extra key in an existing user's `authorized_keys` for authoritative mode to drop, and sets root's password before converge; the role then locks it. The converge sets the primary user explicitly instead of through the `{{ ansible_user }}` default.
|
||||||
|
|
||||||
|
Verify checks:
|
||||||
|
|
||||||
|
- The stale user and its home are gone.
|
||||||
|
- Both users are in the `sudo` group, `visudo -c` passes and `sudo -l` grants them `ALL`.
|
||||||
|
- Each `authorized_keys` file holds exactly the configured key; the planted extra key is gone.
|
||||||
|
- The primary user still has its key and a login shell.
|
||||||
|
- Root's password field is `!`, and root's key and shell are unchanged.
|
||||||
|
|
||||||
|
The scenario uses the docker connection, where `wait_for_connection` always succeeds, so the root fallback and the handback are not exercised by it. The cloud-init marker is not checked.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
|
|
||||||
- The role sets the facts `user_management_all_users` (primary user first, then `user_management_other_users`) and `user_management_managed_usernames`. Both are set under the `always` tag, and the task that builds the first is `no_log`.
|
- Idempotent: yes.
|
||||||
- `user_management_remove_home` is applied to every user task, so it also passes `remove: true` for present users, which only matters for `state: absent`.
|
- `user_management_remove_home` is applied to every user task, so it also passes `remove: true` for present users, which only matters for `state: absent`.
|
||||||
- Per-user `authorized_keys` are added to `user_management_default_authorized_keys`. Keys are written only for users whose `state` is present and whose merged list is non-empty. With `user_management_authoritative` true other keys are removed.
|
- Per-user `authorized_keys` are added to `user_management_default_authorized_keys`. Keys are written only for users whose `state` is present and whose merged list is non-empty. With `user_management_authoritative` true other keys are removed.
|
||||||
- `tasks/ssh_keys.yml` hardcodes the `.ssh` path as `/home/<name>/.ssh` and skips creating it for users with `system: true`, but the `authorized_key` task still runs for them (it uses the user's real home), so a system user with keys gets them written.
|
- `tasks/ssh_keys.yml` hardcodes the `.ssh` path as `/home/<name>/.ssh` and skips creating it for users with `system: true`, but the `authorized_key` task still runs for them (it uses the user's real home), so a system user with keys gets them written.
|
||||||
- `tasks/ssh_keys.yml` sets the `.ssh` directory's group to the user's name, and the user tasks set no primary `group`, so it assumes each user's primary group has the same name as the user (the default user-private group).
|
- `tasks/ssh_keys.yml` sets the `.ssh` directory's group to the user's name, and the user tasks set no primary `group`, so it assumes each user's primary group has the same name as the user (the default user-private group).
|
||||||
- The spec lists `user_management_become_password_hashed` as `raw` with `no_log`, so the vaulted value is never printed.
|
- The spec lists `user_management_become_password_hashed` as `raw` with `no_log`, so the vaulted value is never printed.
|
||||||
- `user_management_lock_root_password` locks root's password after the users and keys are written: `ansible.builtin.user` sets the shadow field to `!` (`update_password: always`), so the old hash is removed rather than kept behind a `!` prefix as `usermod -L` would leave it, and reports ok once it is there. Nothing else of root changes (shell, home, `authorized_keys`). It is meant for guests whose root password is not needed (for example containers created with a shared root password): recovery is `pct enter` from the Proxmox node, which needs no password. The key-only root fallback still works on a locked root, because sshd with `UsePAM yes` (the Ubuntu default and the `sshd` role's setting) does not refuse key logins for a `!` hash. Leave it false on a Proxmox node, where root's password is the web UI and PAM login. The role fails when it is true and the primary user is root, since the lock would disable that user's password. Unlocking is not automated: setting the input back to false leaves the lock in place, and there is no old password to restore (set a new one with `passwd root` by hand).
|
- `user_management_lock_root_password` locks root's password after the users and keys are written: `ansible.builtin.user` sets the shadow field to `!` (`update_password: always`), so the old hash is removed rather than kept behind a `!` prefix as `usermod -L` would leave it, and reports ok once it is there. Nothing else of root changes (shell, home, `authorized_keys`). It is meant for guests whose root password is not needed (for example containers created with a shared root password): recovery is `pct enter` from the Proxmox node, which needs no password. The key-only root fallback still works on a locked root, because sshd with `UsePAM yes` (the Ubuntu default and the `sshd` role's setting) does not refuse key logins for a `!` hash. Leave it false on a Proxmox node, where root's password is the web UI and PAM login. The role fails when it is true and the primary user is root, since the lock would disable that user's password. Unlocking is not automated: setting the input back to false leaves the lock in place, and there is no old password to restore (set a new one with `passwd root` by hand).
|
||||||
- Molecule: `molecule/default`, run by the Collection's CI, with a stale user to remove, a planted extra key to drop and root's password set before converge, then locked by the role. The scenario uses the docker connection, where `wait_for_connection` always succeeds, so the root fallback and the handback are not exercised by it.
|
|
||||||
- The root fallback requires the primary user's name to equal `ansible_user` (set as a variable): the role fails before switching to root when they differ, because the user it would create is not the one Ansible connects as. The handback then switches to that user.
|
- The root fallback requires the primary user's name to equal `ansible_user` (set as a variable): the role fails before switching to root when they differ, because the user it would create is not the one Ansible connects as. The handback then switches to that user.
|
||||||
- The bootstrap and the handback carry the `always` tag. Running only some tags (for example `--tags ssh_keys`) on a fresh host falls back to root, creates no user, and then fails the host when the handback cannot log in as the configured user.
|
- The bootstrap and the handback carry the `always` tag. Running only some tags (for example `--tags ssh_keys`) on a fresh host falls back to root, creates no user, and then fails the host when the handback cannot log in as the configured user.
|
||||||
- Nothing stops the primary user's `state` from being set to `absent`, which (with `user_management_remove_home` true) deletes the account Ansible connects as.
|
- Nothing stops the primary user's `state` from being set to `absent`, which (with `user_management_remove_home` true) deletes the account Ansible connects as.
|
||||||
@@ -3,3 +3,5 @@ LICENSES/EUPL-1.2.txt no-smart-quotes
|
|||||||
LICENSES/GPL-3.0-only.txt no-smart-quotes
|
LICENSES/GPL-3.0-only.txt no-smart-quotes
|
||||||
LICENSES/GPL-3.0-or-later.txt no-smart-quotes
|
LICENSES/GPL-3.0-or-later.txt no-smart-quotes
|
||||||
roles/docker/molecule/default/files/build-stub-repo.sh shebang # run by the docker scenario, not by Ansible
|
roles/docker/molecule/default/files/build-stub-repo.sh shebang # run by the docker scenario, not by Ansible
|
||||||
|
roles/docker/files/docker-start-missed shebang # a command the role installs on the host, run by systemd, not an Ansible module
|
||||||
|
roles/docker/files/docker-stop-at-shutdown shebang # a command the role installs on the host, run by systemd, not an Ansible module
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
# SPDX-FileCopyrightText: Defame1297 and contributors
|
||||||
|
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
"""Run with: python3 -m unittest discover -s tests/scripts"""
|
||||||
|
|
||||||
|
import importlib.machinery
|
||||||
|
import importlib.util
|
||||||
|
import json
|
||||||
|
import pathlib
|
||||||
|
import re
|
||||||
|
import unittest
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
ROLE_FILES = pathlib.Path(__file__).resolve().parents[2] / "roles/docker/files"
|
||||||
|
# The script has no .py suffix (it is installed as a command), so name the loader.
|
||||||
|
loader = importlib.machinery.SourceFileLoader(
|
||||||
|
"docker_start_missed", str(ROLE_FILES / "docker-start-missed")
|
||||||
|
)
|
||||||
|
spec = importlib.util.spec_from_loader("docker_start_missed", loader)
|
||||||
|
m = importlib.util.module_from_spec(spec)
|
||||||
|
loader.exec_module(m)
|
||||||
|
|
||||||
|
BOOT = datetime(2026, 11, 17, 14, 40, 14, tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def container(
|
||||||
|
name,
|
||||||
|
policy="unless-stopped",
|
||||||
|
code=255,
|
||||||
|
finished="2026-11-17T14:40:16.660987249Z",
|
||||||
|
running=False,
|
||||||
|
status="exited",
|
||||||
|
):
|
||||||
|
return {
|
||||||
|
"Name": f"/{name}",
|
||||||
|
"HostConfig": {"RestartPolicy": {"Name": policy}},
|
||||||
|
"State": {
|
||||||
|
"Running": running,
|
||||||
|
"Status": "running" if running else status,
|
||||||
|
"ExitCode": code,
|
||||||
|
"FinishedAt": finished,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class Missed(unittest.TestCase):
|
||||||
|
def test_the_skipped_container_is_selected(self):
|
||||||
|
self.assertEqual(m.missed([container("prometheus")], BOOT), ["prometheus"])
|
||||||
|
|
||||||
|
def test_running_container_is_left_alone(self):
|
||||||
|
self.assertEqual(
|
||||||
|
m.missed([container("grafana", running=True, code=0)], BOOT), []
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_a_manual_stop_stays_stopped(self):
|
||||||
|
for code in (0, 137, 143, 1):
|
||||||
|
self.assertEqual(m.missed([container("x", code=code)], BOOT), [], code)
|
||||||
|
|
||||||
|
def test_died_before_this_boot_is_not_ours(self):
|
||||||
|
self.assertEqual(
|
||||||
|
m.missed([container("x", finished="2026-11-16T10:00:00.1Z")], BOOT), []
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_boot_tolerance(self):
|
||||||
|
self.assertEqual(
|
||||||
|
m.missed([container("x", finished="2026-11-17T14:40:10Z")], BOOT),
|
||||||
|
["x"],
|
||||||
|
"within 5 s before the computed boot time",
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
m.missed([container("x", finished="2026-11-17T14:40:08Z")], BOOT), []
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_only_unless_stopped_and_always(self):
|
||||||
|
for policy, expected in (
|
||||||
|
("unless-stopped", ["x"]),
|
||||||
|
("always", ["x"]),
|
||||||
|
("on-failure", []),
|
||||||
|
("no", []),
|
||||||
|
("", []),
|
||||||
|
):
|
||||||
|
self.assertEqual(
|
||||||
|
m.missed([container("x", policy=policy)], BOOT), expected, policy
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_never_started_container_has_no_finish_time(self):
|
||||||
|
self.assertEqual(
|
||||||
|
m.missed([container("x", finished="0001-01-01T00:00:00Z")], BOOT), []
|
||||||
|
)
|
||||||
|
self.assertEqual(m.missed([container("x", finished="")], BOOT), [])
|
||||||
|
|
||||||
|
def test_a_restarting_container_is_left_to_docker(self):
|
||||||
|
self.assertEqual(m.missed([container("x", status="restarting")], BOOT), [])
|
||||||
|
|
||||||
|
def test_names_are_sorted_and_stripped(self):
|
||||||
|
self.assertEqual(
|
||||||
|
m.missed(
|
||||||
|
[
|
||||||
|
container("blackbox"),
|
||||||
|
container("prometheus"),
|
||||||
|
container("grafana", running=True),
|
||||||
|
],
|
||||||
|
BOOT,
|
||||||
|
),
|
||||||
|
["blackbox", "prometheus"],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ParseTime(unittest.TestCase):
|
||||||
|
def test_nanoseconds(self):
|
||||||
|
self.assertEqual(
|
||||||
|
m.parse_time("2026-11-17T14:40:16.660987249Z"),
|
||||||
|
datetime(2026, 11, 17, 14, 40, 16, 660987, tzinfo=UTC),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_no_fraction(self):
|
||||||
|
self.assertEqual(
|
||||||
|
m.parse_time("2026-11-17T14:40:16Z"),
|
||||||
|
datetime(2026, 11, 17, 14, 40, 16, tzinfo=UTC),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeDocker:
|
||||||
|
"""Stands in for the docker CLI: `exited` is what `ps` and `inspect` report, `start_rc` the exit code per name."""
|
||||||
|
|
||||||
|
def __init__(self, exited, start_rc=None, info_rc=0, stays_up=True):
|
||||||
|
self.exited, self.start_rc, self.info_rc, self.stays_up = (
|
||||||
|
exited,
|
||||||
|
start_rc or {},
|
||||||
|
info_rc,
|
||||||
|
stays_up,
|
||||||
|
)
|
||||||
|
self.calls = []
|
||||||
|
|
||||||
|
def __call__(self, *args):
|
||||||
|
self.calls.append(args)
|
||||||
|
out = SimpleNamespace(returncode=0, stdout="", stderr="")
|
||||||
|
if args[0] == "info":
|
||||||
|
out.returncode = self.info_rc
|
||||||
|
elif args[0] == "ps":
|
||||||
|
out.stdout = " ".join(f"id{i}" for i, _container in enumerate(self.exited))
|
||||||
|
elif args[0] == "inspect" and args[1] != "-f":
|
||||||
|
out.stdout = json.dumps(self.exited)
|
||||||
|
elif args[0] == "inspect":
|
||||||
|
out.stdout = "true\n" if self.stays_up else "false\n"
|
||||||
|
elif args[0] == "start":
|
||||||
|
out.returncode = self.start_rc.get(args[1], 0)
|
||||||
|
out.stderr = "boom" if out.returncode else ""
|
||||||
|
return out
|
||||||
|
|
||||||
|
def started(self):
|
||||||
|
return [c[1] for c in self.calls if c[0] == "start"]
|
||||||
|
|
||||||
|
|
||||||
|
class RunOnce(unittest.TestCase):
|
||||||
|
def run_it(self, fake):
|
||||||
|
logs = []
|
||||||
|
rc = m.run_once(
|
||||||
|
0, run=fake, sleep=lambda _s: None, boot_time=BOOT, log=logs.append
|
||||||
|
)
|
||||||
|
return rc, logs
|
||||||
|
|
||||||
|
def test_starts_the_skipped_ones_only(self):
|
||||||
|
fake = FakeDocker([container("prometheus"), container("manual", code=0)])
|
||||||
|
rc, logs = self.run_it(fake)
|
||||||
|
self.assertEqual((rc, fake.started()), (0, ["prometheus"]))
|
||||||
|
self.assertTrue(any("prometheus" in line for line in logs))
|
||||||
|
|
||||||
|
def test_nothing_to_do(self):
|
||||||
|
fake = FakeDocker([])
|
||||||
|
self.assertEqual(self.run_it(fake)[0], 0)
|
||||||
|
self.assertEqual(fake.started(), [])
|
||||||
|
|
||||||
|
def test_a_failed_start_fails_the_unit_but_the_others_still_start(self):
|
||||||
|
fake = FakeDocker([container("a"), container("b")], start_rc={"a": 1})
|
||||||
|
rc, logs = self.run_it(fake)
|
||||||
|
self.assertEqual((rc, fake.started()), (1, ["a", "b"]))
|
||||||
|
self.assertTrue(any("could not start a" in line for line in logs))
|
||||||
|
|
||||||
|
def test_a_container_that_does_not_stay_up_fails_the_unit(self):
|
||||||
|
rc, logs = self.run_it(FakeDocker([container("a")], stays_up=False))
|
||||||
|
self.assertEqual(rc, 1)
|
||||||
|
self.assertTrue(any("did not stay up" in line for line in logs))
|
||||||
|
|
||||||
|
def test_dry_run_reports_and_starts_nothing(self):
|
||||||
|
fake = FakeDocker([container("prometheus")])
|
||||||
|
logs = []
|
||||||
|
rc = m.run_once(
|
||||||
|
0,
|
||||||
|
run=fake,
|
||||||
|
sleep=lambda _s: None,
|
||||||
|
boot_time=BOOT,
|
||||||
|
log=logs.append,
|
||||||
|
dry_run=True,
|
||||||
|
)
|
||||||
|
self.assertEqual((rc, fake.started()), (0, []))
|
||||||
|
self.assertEqual(logs, ["would start: prometheus"])
|
||||||
|
|
||||||
|
def test_inspect_failing_is_a_docker_problem(self):
|
||||||
|
class Fake(FakeDocker):
|
||||||
|
def __call__(self, *args):
|
||||||
|
out = super().__call__(*args)
|
||||||
|
if args[0] == "inspect":
|
||||||
|
out.returncode, out.stdout, out.stderr = 1, "", "daemon error"
|
||||||
|
return out
|
||||||
|
|
||||||
|
rc, logs = self.run_it(Fake([container("a")]))
|
||||||
|
self.assertEqual(rc, 2)
|
||||||
|
self.assertTrue(any("inspect failed" in line for line in logs))
|
||||||
|
|
||||||
|
def test_a_removed_container_does_not_stop_the_rest(self):
|
||||||
|
class Fake(FakeDocker):
|
||||||
|
def __call__(self, *args):
|
||||||
|
out = super().__call__(*args)
|
||||||
|
if args[0] == "inspect" and args[1] != "-f":
|
||||||
|
out.returncode = 1 # docker prints the containers it found and exits 1 for the missing one
|
||||||
|
return out
|
||||||
|
|
||||||
|
fake = Fake([container("a")])
|
||||||
|
self.assertEqual((self.run_it(fake)[0], fake.started()), (0, ["a"]))
|
||||||
|
|
||||||
|
def test_unreadable_inspect_output_is_a_docker_problem(self):
|
||||||
|
class Fake(FakeDocker):
|
||||||
|
def __call__(self, *args):
|
||||||
|
out = super().__call__(*args)
|
||||||
|
if args[0] == "inspect" and args[1] != "-f":
|
||||||
|
out.stdout = "not json"
|
||||||
|
return out
|
||||||
|
|
||||||
|
fake = Fake([container("a")])
|
||||||
|
self.assertEqual((self.run_it(fake)[0], fake.started()), (2, []))
|
||||||
|
|
||||||
|
def test_a_timestamp_in_an_unexpected_format_is_a_docker_problem(self):
|
||||||
|
fake = FakeDocker([container("a", finished="Nov 17 14:40:16 2026")])
|
||||||
|
self.assertEqual((self.run_it(fake)[0], fake.started()), (2, []))
|
||||||
|
|
||||||
|
def test_ps_failing_is_a_docker_problem(self):
|
||||||
|
class Fake(FakeDocker):
|
||||||
|
def __call__(self, *args):
|
||||||
|
out = super().__call__(*args)
|
||||||
|
if args[0] == "ps":
|
||||||
|
out.returncode, out.stderr = 1, "denied"
|
||||||
|
return out
|
||||||
|
|
||||||
|
self.assertEqual(self.run_it(Fake([container("a")]))[0], 2)
|
||||||
|
|
||||||
|
def test_docker_never_answers(self):
|
||||||
|
fake = FakeDocker([container("a")], info_rc=1)
|
||||||
|
rc, _logs = self.run_it(fake)
|
||||||
|
self.assertEqual((rc, fake.started()), (2, []))
|
||||||
|
|
||||||
|
|
||||||
|
class StopAtShutdownScript(unittest.TestCase):
|
||||||
|
def test_it_never_calls_docker_stop_or_kill(self):
|
||||||
|
# Both set the manually-stopped marker, so a container with restart policy unless-stopped would not start at the next boot.
|
||||||
|
code = [
|
||||||
|
line
|
||||||
|
for line in (ROLE_FILES / "docker-stop-at-shutdown")
|
||||||
|
.read_text()
|
||||||
|
.splitlines()
|
||||||
|
if not line.lstrip().startswith("#")
|
||||||
|
]
|
||||||
|
self.assertEqual(
|
||||||
|
[line for line in code if re.search(r"\bdocker\s+(stop|kill)\b", line)], []
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user