From e308683431e7b675ee0c1daa761014d0dd6b3df8 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Mon, 23 Nov 2026 14:11:55 +0000 Subject: [PATCH] feat(cloudflared): add the cloudflared role Installs cloudflared as a systemd service for a locally managed Cloudflare Tunnel: checks that the tunnel exists, manages its proxied CNAMEs, renders config.yml and the credentials file, and updates the binary through the internal _binary_update role. The opt-in mint entry point creates the tunnel and registers its id and credentials as no_log facts for the calling play to persist. Validation runs first under always and asserts the tunnel secrets with the mint instructions; the secrets stay optional in the argument spec on purpose. cloudflared_manage_dns lets the records be managed elsewhere. A removal now ends the role. Assisted-by: Claude Code:claude-opus-5-5 --- changelogs/fragments/cloudflared-role.yml | 13 ++ roles/cloudflared/README.md | 115 ++++++++++ roles/cloudflared/defaults/main.yml | 48 ++++ roles/cloudflared/handlers/main.yml | 6 + roles/cloudflared/meta/argument_specs.yml | 227 +++++++++++++++++++ roles/cloudflared/meta/main.yml | 18 ++ roles/cloudflared/tasks/configure.yml | 262 ++++++++++++++++++++++ roles/cloudflared/tasks/download.yml | 18 ++ roles/cloudflared/tasks/install.yml | 21 ++ roles/cloudflared/tasks/main.yml | 32 +++ roles/cloudflared/tasks/mint.yml | 95 ++++++++ roles/cloudflared/tasks/prereqs.yml | 39 ++++ roles/cloudflared/tasks/remove.yml | 88 ++++++++ roles/cloudflared/tasks/update.yml | 106 +++++++++ roles/cloudflared/tasks/validate.yml | 81 +++++++ roles/cloudflared/templates/config.yml.j2 | 13 ++ 16 files changed, 1182 insertions(+) create mode 100644 changelogs/fragments/cloudflared-role.yml create mode 100644 roles/cloudflared/README.md create mode 100644 roles/cloudflared/defaults/main.yml create mode 100644 roles/cloudflared/handlers/main.yml create mode 100644 roles/cloudflared/meta/argument_specs.yml create mode 100644 roles/cloudflared/meta/main.yml create mode 100644 roles/cloudflared/tasks/configure.yml create mode 100644 roles/cloudflared/tasks/download.yml create mode 100644 roles/cloudflared/tasks/install.yml create mode 100644 roles/cloudflared/tasks/main.yml create mode 100644 roles/cloudflared/tasks/mint.yml create mode 100644 roles/cloudflared/tasks/prereqs.yml create mode 100644 roles/cloudflared/tasks/remove.yml create mode 100644 roles/cloudflared/tasks/update.yml create mode 100644 roles/cloudflared/tasks/validate.yml create mode 100644 roles/cloudflared/templates/config.yml.j2 diff --git a/changelogs/fragments/cloudflared-role.yml b/changelogs/fragments/cloudflared-role.yml new file mode 100644 index 0000000..2c03bb1 --- /dev/null +++ b/changelogs/fragments/cloudflared-role.yml @@ -0,0 +1,13 @@ +--- +minor_changes: + - >- + cloudflared - New role. Installs cloudflared as a systemd service for a locally managed Cloudflare Tunnel, with a + sha256-verified binary, checks that the tunnel still exists, renders ``config.yml`` from ``cloudflared_ingress``, + writes the tunnel credentials, and with ``cloudflared_manage_dns`` (default true) points a proxied CNAME for every + ingress hostname at the tunnel, refusing to overwrite a record that does not point at a tunnel and pruning CNAMEs + of this tunnel that are no longer listed. With ``cloudflared_update`` it downloads and verifies a new release + before stopping anything and swaps it in through the internal ``_binary_update`` role, with rollback on failure. + ``cloudflared_remove`` removes the daemon and ends the role; with ``cloudflared_remove_data`` it also deletes the + tunnel and its records on Cloudflare. The opt-in ``mint`` entry point creates the tunnel with a secret generated in + memory and registers its id and credentials as ``no_log`` facts for the calling play to persist; it is refused + under CI and does nothing when a tunnel is already set. diff --git a/roles/cloudflared/README.md b/roles/cloudflared/README.md new file mode 100644 index 0000000..d3b4646 --- /dev/null +++ b/roles/cloudflared/README.md @@ -0,0 +1,115 @@ +# cloudflared + +Installs cloudflared as a systemd service for a locally managed Cloudflare Tunnel. The role checks that the tunnel exists, manages its proxied DNS CNAMEs through the Cloudflare API, renders `config.yml` from a hostname-to-service list, and optionally updates or removes everything. A separate `mint` entry point creates the tunnel. Variables and their types are defined in [`meta/argument_specs.yml`](meta/argument_specs.yml), which is the source of truth. + +## Supported platforms + +Ubuntu 24.04 (noble), the image the molecule scenario runs on. The role downloads the `cloudflared-linux-amd64` binary only, so other architectures are unsupported, and it needs `systemd`. The tasks that call the Cloudflare API run on the controller (`delegate_to: localhost`) and need the `community.general` collection (`cloudflare_dns`) there; the `mint` entry point also needs the `openssl` command on the controller. The target needs outbound access to github.com and to Cloudflare's edge; the role defines no firewall rules because the daemon only connects outbound. + +## Requirements and run order + +- Use it by its fully qualified name, `mortis.kamino.cloudflared`. +- Before the first run: set `cloudflared_account_id` and `cloudflared_tunnel_api_token` (vaulted), and, while `cloudflared_manage_dns` is true, `cloudflared_zone_name`; list the routed hostnames in `cloudflared_ingress`. The token needs Cloudflare Tunnel Edit, DNS Edit and Zone Read; do not reuse a token that serves another purpose (for example an ACME DNS-challenge token). +- First run versus later runs: `cloudflared_tunnel_id` and `cloudflared_credentials_json` have no role default and the main entry point never creates them. Validation asserts both are defined and non-empty before anything changes and fails with the mint instructions otherwise. On a new host run the `mint` entry point first, persist its output facts into inventory under these two names, then run the role (see Entry points). +- The secrets are not `required` in the argument spec, on purpose, as an exception to the rule that a secret is a required input: argument validation would stop a first run with a generic "missing required arguments" message, where the role's own assert names the mint entry point that creates the tunnel, and the `mint` entry point must run while `cloudflared_tunnel_id` is still undefined. All four (`cloudflared_tunnel_id`, `cloudflared_credentials_json`, `cloudflared_account_id`, `cloudflared_tunnel_api_token`) have no default and are asserted non-empty before any change. +- An origin behind the tunnel on the same host (for example a reverse proxy on `https://127.0.0.1:443`) must be serving before cloudflared can reach it; the role does not check it. +- Updates: the update path stages the verified binary and hands the swap to `mortis.kamino._binary_update`, an internal role of this Collection. +- `cloudflared_version` is asserted at role start to be a `YYYY.M.P` release tag, with no leading `v`, and `cloudflared_sha256_amd64` to be 64 hex digits. Pin both in inventory to move the daemon independently of Collection releases; the role defaults change only with a release. + +## Role variables + +| Variable | Default | Description | +|---|---|---| +| `cloudflared_ingress` | `[]` | List of `hostname`, `service` and optional `originRequest`. A catch-all `http_status:404` rule is appended. | +| `cloudflared_tunnel_id` | none (asserted) | Vaulted tunnel id, from the `mint` entry point. | +| `cloudflared_credentials_json` | none (asserted) | Vaulted tunnel credentials JSON, written to `/.json`, mode 0600. | +| `cloudflared_account_id` | none (asserted) | Account id for the tunnel API. | +| `cloudflared_tunnel_api_token` | none (asserted) | API token, `no_log`. | +| `cloudflared_manage_dns` | `true` | Manage the proxied CNAMEs of the ingress hostnames; false makes no DNS call. | +| `cloudflared_zone_name` | `""` (asserted while `cloudflared_manage_dns`) | Zone of the ingress hostnames. | +| `cloudflared_allow_dns_overwrite` | `[]` | Hostnames whose existing non-tunnel DNS record may be overwritten. | +| `cloudflared_api_base_url` | `https://api.cloudflare.com/client/v4` | Cloudflare API base URL for the role's `uri` calls, no trailing slash. | +| `cloudflared_tunnel_name` | `{{ inventory_hostname }}-tunnel` | Tunnel name used by the `mint` entry point. | +| `cloudflared_version` | pinned in `defaults/main.yml` | Release tag, `YYYY.M.P`. | +| `cloudflared_sha256_amd64` | pinned | SHA-256 of the amd64 binary. Update with the version. | +| `cloudflared_download_url` | github.com release URL built from the version | Binary download URL. | +| `cloudflared_update` | `true` | Run the update tasks when the installed version differs: download and verify to a staging path, then `mortis.kamino._binary_update` swaps it in with rollback. | +| `cloudflared_remove` | `false` | Stop and disable the service, remove the unit and the binary. The role ends there. | +| `cloudflared_remove_data` | `false` | With `cloudflared_remove`, also remove the config directory and the user, and delete the tunnel (and, with `cloudflared_manage_dns`, its DNS records) on Cloudflare. | +| `cloudflared_user`, `cloudflared_group` | `cloudflared` | Service account. | +| `cloudflared_install_dir` | `/usr/local/bin` | Binary location. | +| `cloudflared_config_dir` | `/etc/cloudflared` | Configuration and credentials directory. | +| `cloudflared_service_unit` | `/etc/systemd/system/cloudflared.service` | Unit file path. | +| `cloudflared_mint_confirm` | `false` | Opt-in for the `mint` entry point. | + +## Entry points + +- `main`: install, configure, update or remove cloudflared, as above. +- `mint` (`tasks_from: mint`): creates the tunnel. Run it by hand from an operator play, never from CI: + + ```yaml + - name: Mint the Cloudflare Tunnel + hosts: tunnel_hosts + tasks: + - name: Mint + ansible.builtin.include_role: + name: mortis.kamino.cloudflared + tasks_from: mint + # Then vault-encrypt cloudflared_minted_tunnel_id and cloudflared_minted_credentials_json + # (when defined) into inventory as cloudflared_tunnel_id and cloudflared_credentials_json. + ``` + + Run it with `-e cloudflared_mint_confirm=true`. + + - Guards: `cloudflared_mint_confirm` must be true, and the entry point fails when `GITHUB_ACTIONS`, `GITEA_ACTIONS` or `CI` is set in the controller environment. This guards against accidents; it is not a security boundary. + - When `cloudflared_tunnel_id` is already defined and non-empty (undefined, null and `""` count as missing) it only reports that and creates nothing, so a re-run is safe. It creates nothing in check mode. + - Otherwise it asserts `cloudflared_account_id`, `cloudflared_tunnel_api_token` and `cloudflared_tunnel_name`, generates the tunnel secret in memory with `openssl rand -base64 32` on the controller, creates the tunnel through the API with `config_src: local` and registers `cloudflared_minted_tunnel_id` and `cloudflared_minted_credentials_json` as `no_log` facts. The secret and the API response are cleared from the host's variables afterwards. + - Persisting the facts is the calling play's job. The credentials are shown nowhere else, so a mint whose result is not persisted must be repeated, and leaves an orphan tunnel on Cloudflare to delete by hand. + +## Variables set by the role + +Only by the `mint` entry point, and only when a tunnel was created; `no_log`, not cacheable: + +- `cloudflared_minted_tunnel_id` (string): the new tunnel's id. +- `cloudflared_minted_credentials_json` (string, JSON text): the tunnel credentials file content, including the tunnel secret. + +## Tags + +`cloudflared` (everything), `prereqs`, `install`, `configure`, `health`, `update`, `remove`, `mint` (carried by the mint entry point's tasks, but not selectable on its own: its guards are tagged `cloudflared, always`, so select a mint play with `--tags cloudflared`). The input asserts and the `prereqs` tasks are also tagged `always`. The download (`tasks/download.yml`, shared by install and update) is tagged `install` and `update`, so `--tags update` alone reaches it. + +## Example play + +```yaml +- name: Run a Cloudflare Tunnel + hosts: tunnel_hosts + roles: + - role: mortis.kamino.cloudflared + vars: + cloudflared_zone_name: example.com + cloudflared_ingress: + - hostname: git.example.com + service: https://127.0.0.1:443 + originRequest: + originServerName: git.example.com +``` + +`cloudflared_account_id`, `cloudflared_tunnel_api_token`, `cloudflared_tunnel_id` and `cloudflared_credentials_json` come from vaulted inventory variables. + +Remove with `-e "cloudflared_remove=true cloudflared_remove_data=true"`; only `cloudflared_remove_data` touches Cloudflare. + +## Tests + +The `default` molecule scenario runs without Cloudflare: a stub cloudflared binary stands in for the daemon, the downloads come from local `file://` URLs, and a stub of the Cloudflare API on the controller's loopback (`molecule/default/files/cloudflare_api_stub.py`, reached through `cloudflared_api_base_url`) answers the tunnel, zone and DNS record calls. It covers the converge with `cloudflared_manage_dns` false and an update through `_binary_update` (and its idempotence), the rendered `config.yml`, credentials file and unit, a stale credentials file, a failed checksum that leaves the daemon running, the input asserts, the deleted-tunnel and DNS guards, the `mint` entry point (confirm guard, CI refusal, no-op, check mode and a mint against the stub, run as child processes) and the remove path. The `community.general.cloudflare_dns` calls, which cannot be pointed at the stub, are not covered: creating, pruning and deleting records. + +## Notes + +- Idempotent: yes. +- The role is not a state selector. `main.yml` always runs validation, prerequisites and configure unless `cloudflared_remove` is true; the binary install only when it is absent; the update only when the installed version differs; remove only when `cloudflared_remove` is true, and then every later task is skipped. +- Secrets: the tasks that create the secrets, the `uri` calls that put the token in the Authorization header, the `cloudflare_dns` calls and the credentials file write use `no_log` (the credentials write also sets `diff: false`). A failure of those tasks therefore shows only as "censored": to debug a failed DNS change, check the Cloudflare audit log or set `no_log: false` on a throwaway run against a non-secret zone. The tunnel id itself is not masked: it shows in `config.yml` diffs, DNS record values and failure messages. +- Safety guards: the role fails if the tunnel no longer exists on Cloudflare (retrying a 404 three times first), if the zone is not found, or if an existing record for an ingress hostname does not point at some `cfargotunnel.com` tunnel and the hostname is not in `cloudflared_allow_dns_overwrite`. A record that already points at a tunnel, including a deleted one, is repointed without an allowlist entry. +- Pruning: CNAMEs pointing at this tunnel whose name is not in `cloudflared_ingress` are deleted. The lookup is filtered by the tunnel's `cfargotunnel.com` target, so other records in the zone are not touched. +- Re-mint after a tunnel was deleted out of band: remove the stale `cloudflared_tunnel_id` and `cloudflared_credentials_json` from inventory, run the `mint` entry point and persist its output. +- Stale credentials: files named `.json` in the config directory other than the current tunnel's are removed. +- The `Restart cloudflared` handler runs when `config.yml` or the credentials file changes. cloudflared's own ingress check (`ingress validate`) runs after `config.yml` is written. +- Update: the version is compared as `YYYY.M.P` against `cloudflared --version`. The new binary is downloaded and checksum-verified into `cloudflared.new` before the service is stopped, so a failed download leaves it running; a configured hash that equals the installed binary's is refused with a message, since it means the hash was not bumped with the version. A binary that reports no version is replaced too. +- The play fails when `cloudflared` is not `active` after start. diff --git a/roles/cloudflared/defaults/main.yml b/roles/cloudflared/defaults/main.yml new file mode 100644 index 0000000..3c52855 --- /dev/null +++ b/roles/cloudflared/defaults/main.yml @@ -0,0 +1,48 @@ +--- +cloudflared_update: true +cloudflared_remove_data: false +cloudflared_remove: false + +# cloudflared publishes no checksum file: the hash is the sha256 of the cloudflared-linux-amd64 +# release asset, and it moves together with the version. Pin both in inventory to move the +# daemon independently of Collection releases. +cloudflared_version: "2026.11.1" +cloudflared_sha256_amd64: "97bb3b02d23a5980fc9c15a1a270e692da1923f103f920d5b16d4931d5ab55e7" +cloudflared_download_url: "https://github.com/cloudflare/cloudflared/releases/download/{{ cloudflared_version }}/cloudflared-linux-amd64" + +cloudflared_user: "cloudflared" +cloudflared_group: "cloudflared" +cloudflared_install_dir: "/usr/local/bin" +cloudflared_config_dir: "/etc/cloudflared" +cloudflared_service_unit: "/etc/systemd/system/cloudflared.service" + +cloudflared_api_base_url: "https://api.cloudflare.com/client/v4" + +cloudflared_tunnel_name: "{{ inventory_hostname }}-tunnel" + +# Set false when the tunnel's DNS records are managed elsewhere: the role then makes no DNS +# call and needs no zone. +cloudflared_manage_dns: true + +# Every zone differs, so there is no useful default; asserted non-empty while +# cloudflared_manage_dns is true. +cloudflared_zone_name: "" + +# Hostnames routed through the tunnel; each gets a proxied CNAME while cloudflared_manage_dns +# is true. A catch-all http_status:404 rule is always appended. +cloudflared_ingress: [] + +# The role owns no firewall rule: the daemon only connects outbound to Cloudflare's edge. + +# No default for cloudflared_tunnel_id, cloudflared_credentials_json, cloudflared_account_id or +# cloudflared_tunnel_api_token: they are secrets. The main entry point asserts them and, for the +# tunnel, names the mint entry point that creates it; the mint entry point creates a tunnel only +# while cloudflared_tunnel_id is undefined, null or empty. + +# Hostnames from cloudflared_ingress whose existing DNS record may be overwritten although it does +# not point at a cfargotunnel.com tunnel. Without an entry the play fails instead. Per hostname, so +# unblocking one does not authorise overwriting the others. +cloudflared_allow_dns_overwrite: [] + +# Opt-in for the mint entry point. +cloudflared_mint_confirm: false diff --git a/roles/cloudflared/handlers/main.yml b/roles/cloudflared/handlers/main.yml new file mode 100644 index 0000000..4c6c880 --- /dev/null +++ b/roles/cloudflared/handlers/main.yml @@ -0,0 +1,6 @@ +--- +- name: Restart cloudflared + become: true + ansible.builtin.systemd: + name: cloudflared + state: restarted diff --git a/roles/cloudflared/meta/argument_specs.yml b/roles/cloudflared/meta/argument_specs.yml new file mode 100644 index 0000000..07966e6 --- /dev/null +++ b/roles/cloudflared/meta/argument_specs.yml @@ -0,0 +1,227 @@ +--- +argument_specs: + main: + short_description: Install and run cloudflared for a locally managed Cloudflare Tunnel, with its DNS records + description: + - >- + Validates the inputs, then either removes cloudflared (C(cloudflared_remove), which ends the role) or creates + the C(cloudflared) system user, group and configuration directory, downloads and checksum-verifies the pinned + binary when it is missing and runs the configure tasks. Optionally updates the binary + (C(cloudflared_update)) with rollback through the internal C(mortis.kamino._binary_update) role. + - >- + This entry point never creates the tunnel (see the C(mint) entry point). Validation asserts that + C(cloudflared_tunnel_id) and C(cloudflared_credentials_json) are defined and non-empty, and fails with the + mint instructions otherwise. The configure tasks then check, from the controller, that the tunnel still + exists, and, with C(cloudflared_manage_dns), point a proxied CNAME for every C(cloudflared_ingress) hostname + at the tunnel and prune CNAMEs that point at this tunnel but are no longer listed. They write C(config.yml) + and the credentials file, remove stale credentials files, write the systemd unit and start the service. + - >- + The four secrets (C(cloudflared_tunnel_id), C(cloudflared_credentials_json), C(cloudflared_account_id), + C(cloudflared_tunnel_api_token)) are deliberately not C(required) in this spec: argument validation would + stop a first run with a generic message, where the role's own assert names the mint entry point that + creates the tunnel, and the mint entry point must run while the tunnel variables are still undefined. + They have no role default and are asserted non-empty before any change. + options: + cloudflared_remove: + type: bool + default: false + description: + - >- + When true the service is stopped and disabled and the unit file and the binary are removed. The role ends + there: nothing is installed or configured in the same run. + cloudflared_remove_data: + type: bool + default: false + description: + - >- + Only read while C(cloudflared_remove) is true. When true C(cloudflared_config_dir) and the + C(cloudflared) user are removed and, when C(cloudflared_tunnel_id) is non-empty, the tunnel is deleted on + Cloudflare, together with the DNS records of every C(cloudflared_ingress) hostname while + C(cloudflared_manage_dns) is true. Destructive on the Cloudflare side. + cloudflared_update: + type: bool + default: true + description: + - >- + When true the update tasks run after configuration. The installed version is compared with + C(cloudflared_version) and only a difference triggers a verified download to a staging path next to the + live binary. The swap is then handed to C(mortis.kamino._binary_update), which stops the service, backs + up the live binary, swaps, restarts, checks the version and rolls back on failure. A failed download + leaves the daemon running. + cloudflared_version: + type: str + description: + - >- + cloudflared release tag, for example C(2026.11.1). The role default is a pinned tag, see + C(defaults/main.yml); pin it in inventory, together with C(cloudflared_sha256_amd64), to move the daemon + independently of Collection releases. + - Asserted at role start to be C(YYYY.M.P) digits only, with no leading C(v). + cloudflared_sha256_amd64: + type: str + description: + - >- + SHA-256 of the C(cloudflared-linux-amd64) binary of C(cloudflared_version). Upstream publishes no checksum + file, so it must be updated together with the version. The role default is the pinned value. Asserted at + role start to be 64 hex digits. + cloudflared_download_url: + type: raw + description: + - >- + Download URL of the binary. The role default is a Jinja expression built from C(cloudflared_version) + for C(cloudflared-linux-amd64) on github.com. + cloudflared_user: + type: str + default: cloudflared + description: + - System user that owns the configuration and runs the service. + cloudflared_group: + type: str + default: cloudflared + description: + - System group that owns the configuration and runs the service. + cloudflared_install_dir: + type: str + default: /usr/local/bin + description: + - Directory that receives the C(cloudflared) binary. + cloudflared_config_dir: + type: str + default: /etc/cloudflared + description: + - Directory for C(config.yml) and the tunnel credentials file C(.json), mode 0750. + cloudflared_service_unit: + type: str + default: /etc/systemd/system/cloudflared.service + description: + - Path of the systemd unit file. + cloudflared_api_base_url: + type: str + default: https://api.cloudflare.com/client/v4 + description: + - >- + Base URL of the Cloudflare API, without a trailing slash. Prefixed to every request the role makes with + C(ansible.builtin.uri) (tunnel lookup and delete, zone lookup and DNS record listing). The + C(community.general.cloudflare_dns) tasks always use the public endpoint. + cloudflared_tunnel_name: + type: raw + description: + - >- + Name given to the tunnel when it is created. The role default is the Jinja expression + C(-tunnel). Only used by the C(mint) entry point. + cloudflared_tunnel_id: + type: raw + no_log: true + description: + - >- + Tunnel id, supplied as a vaulted variable from the output of the C(mint) entry point. No role default and + not C(required) in this spec, on purpose: the C(mint) entry point creates the tunnel only while this is + undefined, null or empty, and this entry point asserts it non-empty with the mint instructions. + cloudflared_credentials_json: + type: raw + no_log: true + description: + - >- + Tunnel credentials JSON as a vaulted string, written to C(/.json) with + mode 0600. No role default and not C(required), for the same reason as C(cloudflared_tunnel_id); + asserted non-empty. + cloudflared_manage_dns: + type: bool + default: true + description: + - >- + When true the role looks up C(cloudflared_zone_name), points a proxied CNAME for every + C(cloudflared_ingress) hostname at the tunnel, prunes CNAMEs that point at this tunnel and are no longer + listed, and deletes the records on a removal with C(cloudflared_remove_data). When false it makes no DNS + call and C(cloudflared_zone_name) is not read: the records are managed elsewhere. + cloudflared_zone_name: + type: str + default: "" + description: + - >- + DNS zone of the C(cloudflared_ingress) hostnames. Asserted non-empty while C(cloudflared_manage_dns) is + true. The play fails when no zone of this name exists. + cloudflared_ingress: + type: list + elements: dict + default: [] + description: + - >- + Routed hostnames. Each item is a mapping with C(hostname), C(service) and optionally C(originRequest) + (rendered as YAML). A catch-all C(http_status:404) rule is appended. With C(cloudflared_manage_dns) a + CNAME is created for every C(hostname), and CNAMEs that point at this tunnel and are not listed are + deleted. + cloudflared_allow_dns_overwrite: + type: list + elements: str + default: [] + description: + - >- + Hostnames from C(cloudflared_ingress) whose existing DNS record may be overwritten although it does not + point at a C(cfargotunnel.com) tunnel. Without an entry the play fails instead of replacing the record. + Add a hostname only after confirming the record should be replaced. + cloudflared_account_id: + type: raw + description: + - >- + Cloudflare account id used in the tunnel API URLs. Read by the tunnel existence check and the removal. + No role default and not C(required) (see the secrets note above); asserted non-empty. + cloudflared_tunnel_api_token: + type: raw + no_log: true + description: + - >- + Cloudflare API token with Cloudflare Tunnel Edit, DNS Edit and Zone Read permissions, sent as a Bearer + header and as C(api_token) of C(community.general.cloudflare_dns). A secret: supply it from a vaulted + variable. No role default and not C(required) (see the secrets note above); asserted non-empty. + mint: + short_description: Create the Cloudflare Tunnel and register its secrets as facts (opt-in, operator only) + description: + - >- + Opt-in entry point (C(tasks_from=mint)), run by hand from an operator play, never from CI. Requires + C(cloudflared_mint_confirm=true) and refuses to run when C(GITHUB_ACTIONS), C(GITEA_ACTIONS) or C(CI) is set + on the controller. Does nothing but report when C(cloudflared_tunnel_id) is already defined and non-empty. + - >- + Otherwise, and never in check mode, it generates the tunnel secret in memory (C(openssl rand) on the + controller), creates the tunnel through the Cloudflare API from the controller and registers + C(cloudflared_minted_tunnel_id) and C(cloudflared_minted_credentials_json) (JSON text) as C(no_log) facts. + They are not cacheable, never printed and only defined when a tunnel was created. The role writes no file and + runs no vault command: persisting the facts, for example vault-encrypted into inventory as + C(cloudflared_tunnel_id) and C(cloudflared_credentials_json), is the calling play's job. Cloudflare shows the + credentials once. + - >- + C(cloudflared_account_id) and C(cloudflared_tunnel_api_token) are not C(required) in this spec, as in the + C(main) entry point; they are asserted non-empty before a tunnel is created. + options: + cloudflared_mint_confirm: + type: bool + default: false + description: + - Must be true, otherwise the entry point fails. Pass it as C(-e cloudflared_mint_confirm=true). + cloudflared_api_base_url: + type: str + default: https://api.cloudflare.com/client/v4 + description: + - Base URL of the Cloudflare API, without a trailing slash. + cloudflared_tunnel_name: + type: raw + description: + - >- + Name given to the tunnel. The role default is the Jinja expression C(-tunnel). + cloudflared_account_id: + type: raw + description: + - Cloudflare account id used in the tunnel API URL. No role default; asserted non-empty before a mint. + cloudflared_tunnel_api_token: + type: raw + no_log: true + description: + - >- + Cloudflare API token with Cloudflare Tunnel Edit permission, from a vaulted variable. No role default; + asserted non-empty before a mint. + cloudflared_tunnel_id: + type: raw + no_log: true + description: + - >- + Existing tunnel id. When defined and non-empty nothing is minted (undefined, null and the empty string + count as missing). No role default. diff --git a/roles/cloudflared/meta/main.yml b/roles/cloudflared/meta/main.yml new file mode 100644 index 0000000..ce972e9 --- /dev/null +++ b/roles/cloudflared/meta/main.yml @@ -0,0 +1,18 @@ +--- +galaxy_info: + role_name: cloudflared + namespace: mortis + author: Defame1297 + license: GPL-3.0-or-later + description: Install, update and remove cloudflared for a locally managed Cloudflare Tunnel, with its DNS records, and mint the tunnel on request. + min_ansible_version: "2.19" + platforms: + - name: Ubuntu + versions: + - noble + galaxy_tags: + - cloudflared + - cloudflare + - tunnel + - systemd +dependencies: [] diff --git a/roles/cloudflared/tasks/configure.yml b/roles/cloudflared/tasks/configure.yml new file mode 100644 index 0000000..2976f8c --- /dev/null +++ b/roles/cloudflared/tasks/configure.yml @@ -0,0 +1,262 @@ +--- +# validate.yml has asserted the minted tunnel secrets and the API credentials. The tunnel can +# still be gone on Cloudflare's side: cloudflared then loops on "Tunnel not found" while systemd +# reports the unit active, so check it first. +- name: Install and start cloudflared + become: true + tags: [cloudflared, configure] + block: + - name: Verify the tunnel still exists on Cloudflare + delegate_to: localhost + become: false + ansible.builtin.uri: + url: "{{ cloudflared_api_base_url }}/accounts/{{ cloudflared_account_id }}/cfd_tunnel/{{ cloudflared_tunnel_id }}" + method: GET + headers: + Authorization: "Bearer {{ cloudflared_tunnel_api_token }}" + status_code: [200, 404] + register: __cloudflared_tunnel_lookup + # Right after a mint a 404 can be read-after-write lag rather than a deletion: retry + # briefly before trusting it. + until: __cloudflared_tunnel_lookup.status == 200 + retries: 3 + delay: 5 + # Read-only GET: runs in --check too, so a deleted tunnel is caught in the preview. + check_mode: false + # The Authorization header carries the API token. + no_log: true + tags: [cloudflared, configure, health] + + - name: Fail if the tunnel was deleted on Cloudflare's side + ansible.builtin.fail: + msg: >- + Tunnel {{ cloudflared_tunnel_id }} no longer exists on Cloudflare + (HTTP {{ __cloudflared_tunnel_lookup.status }}). Re-mint it: remove the stale + cloudflared_tunnel_id and cloudflared_credentials_json from your inventory, run the mint + entry point with -e cloudflared_mint_confirm=true, persist the minted values and run the + role again. A hostname whose record still points at a cfargotunnel.com tunnel is repointed + without a cloudflared_allow_dns_overwrite entry. + when: >- + __cloudflared_tunnel_lookup.status == 404 or + (__cloudflared_tunnel_lookup.json.result.deleted_at | default(None)) is not none + tags: [cloudflared, configure, health] + + - name: Manage the tunnel's DNS records + when: cloudflared_manage_dns | bool + block: + - name: Look up Cloudflare zone ID for DNS pruning + delegate_to: localhost + become: false + ansible.builtin.uri: + url: "{{ cloudflared_api_base_url }}/zones?name={{ cloudflared_zone_name }}" + method: GET + headers: + Authorization: "Bearer {{ cloudflared_tunnel_api_token }}" + status_code: [200] + register: __cloudflared_zone_lookup + # Read-only GET: runs in --check too, so the guards below can report. + check_mode: false + # The Authorization header carries the API token. + no_log: true + + - name: Fail if Cloudflare zone lookup returned no results + ansible.builtin.fail: + msg: "No Cloudflare zone found named {{ cloudflared_zone_name }}" + when: __cloudflared_zone_lookup.json.result | length == 0 + + # One bulk fetch of the zone, filtered locally per hostname below. Unfiltered by type, + # so an existing A or AAAA record at a hostname is caught too. + - name: List all DNS records in the zone + delegate_to: localhost + become: false + vars: + __cloudflared_zone_dns_query: "per_page=100" + ansible.builtin.uri: + url: >- + {{ cloudflared_api_base_url }}/zones/{{ __cloudflared_zone_lookup.json.result[0].id }}/dns_records?{{ __cloudflared_zone_dns_query }} + method: GET + headers: + Authorization: "Bearer {{ cloudflared_tunnel_api_token }}" + status_code: [200] + register: __cloudflared_zone_dns_records + # Read-only GET: runs in --check too, so the guard below fails before anything is written. + check_mode: false + # The Authorization header carries the API token. + no_log: true + + # Fail closed: a record that does not point at a Cloudflare Tunnel belongs to something + # else and is replaced only with an explicit cloudflared_allow_dns_overwrite entry. A record + # that points at some cfargotunnel.com tunnel (this one, or one replaced by a re-mint) is + # this role's own and is repointed. + - name: Fail if an existing record doesn't already point at a tunnel + ansible.builtin.fail: + msg: >- + Existing DNS record(s) for {{ __cloudflared_ingress_item.hostname }} + ({{ __cloudflared_existing_targets }}) do not point at a Cloudflare + Tunnel. Verify manually and add + {{ __cloudflared_ingress_item.hostname }} to + cloudflared_allow_dns_overwrite to proceed if this is expected. + loop: "{{ cloudflared_ingress }}" + loop_control: + loop_var: __cloudflared_ingress_item + label: "{{ __cloudflared_ingress_item.hostname }}" + vars: + __cloudflared_existing_records: >- + {{ __cloudflared_zone_dns_records.json.result | selectattr('name', 'equalto', __cloudflared_ingress_item.hostname) | list }} + __cloudflared_existing_targets: "{{ __cloudflared_existing_records | map(attribute='content') | map('lower') | map('trim', '.') | list }}" + when: >- + __cloudflared_ingress_item.hostname not in cloudflared_allow_dns_overwrite and + __cloudflared_existing_targets | length > 0 and + __cloudflared_existing_targets | select('match', '^.*\.cfargotunnel\.com$') | list | length == 0 + + - name: Point public DNS at the tunnel + delegate_to: localhost + become: false + loop: "{{ cloudflared_ingress }}" + loop_control: + loop_var: __cloudflared_ingress_item + label: "{{ __cloudflared_ingress_item.hostname }}" + community.general.cloudflare_dns: + zone: "{{ cloudflared_zone_name }}" + record: "{{ __cloudflared_ingress_item.hostname }}" + type: CNAME + value: "{{ cloudflared_tunnel_id }}.cfargotunnel.com" + proxied: true + api_token: "{{ cloudflared_tunnel_api_token }}" + state: present + # api_token is a module parameter and would show in the task's output. + no_log: true + + # Filtered by content=.cfargotunnel.com, so the prune below only ever sees + # CNAMEs of this tunnel, never records of other services or tunnels in the zone. + - name: List existing DNS records pointing at this tunnel + delegate_to: localhost + become: false + vars: + __cloudflared_prune_query: "type=CNAME&content={{ cloudflared_tunnel_id }}.cfargotunnel.com&per_page=100" + ansible.builtin.uri: + url: "{{ cloudflared_api_base_url }}/zones/{{ __cloudflared_zone_lookup.json.result[0].id }}/dns_records?{{ __cloudflared_prune_query }}" + method: GET + headers: + Authorization: "Bearer {{ cloudflared_tunnel_api_token }}" + status_code: [200] + register: __cloudflared_existing_tunnel_records + # Read-only GET: runs in --check too, so the prune can report. + check_mode: false + # The Authorization header carries the API token. + no_log: true + + - name: Prune DNS records for hostnames no longer in cloudflared_ingress + delegate_to: localhost + become: false + loop: "{{ __cloudflared_existing_tunnel_records.json.result }}" + loop_control: + loop_var: __cloudflared_dns_record_item + label: "{{ __cloudflared_dns_record_item.name }}" + community.general.cloudflare_dns: + zone: "{{ cloudflared_zone_name }}" + record: "{{ __cloudflared_dns_record_item.name }}" + type: CNAME + api_token: "{{ cloudflared_tunnel_api_token }}" + state: absent + when: __cloudflared_dns_record_item.name not in (cloudflared_ingress | map(attribute='hostname') | list) + # api_token is a module parameter and would show in the task's output. + no_log: true + + - name: Create cloudflared config file + ansible.builtin.template: + src: config.yml.j2 + dest: "{{ cloudflared_config_dir }}/config.yml" + owner: "{{ cloudflared_user }}" + group: "{{ cloudflared_group }}" + mode: "0640" + notify: Restart cloudflared + + - name: Validate cloudflared ingress config + ansible.builtin.command: + argv: + - "{{ cloudflared_install_dir }}/cloudflared" + - tunnel + - --config + - "{{ cloudflared_config_dir }}/config.yml" + - ingress + - validate + register: __cloudflared_ingress_validate + changed_when: false + failed_when: __cloudflared_ingress_validate.rc != 0 + tags: [cloudflared, configure, health] + + - name: Write tunnel credentials file + ansible.builtin.copy: + content: "{{ cloudflared_credentials_json }}" + dest: "{{ cloudflared_config_dir }}/{{ cloudflared_tunnel_id }}.json" + owner: "{{ cloudflared_user }}" + group: "{{ cloudflared_group }}" + mode: "0600" + notify: Restart cloudflared + # The content is the tunnel credentials JSON. + no_log: true + diff: false + + # A prior tunnel's credentials file would otherwise stay on disk after a re-mint. + - name: Find stale tunnel credentials files + ansible.builtin.find: + paths: "{{ cloudflared_config_dir }}" + # Tunnel ids are UUIDs, so credentials files are .json; an unrelated JSON file in + # the directory is left alone. + patterns: "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\.json$" + use_regex: true + excludes: "{{ cloudflared_tunnel_id }}.json" + register: __cloudflared_stale_credentials + + - name: Remove stale tunnel credentials left by a prior tunnel + ansible.builtin.file: + path: "{{ __cloudflared_stale_credential_item.path }}" + state: absent + loop: "{{ __cloudflared_stale_credentials.files }}" + loop_control: + loop_var: __cloudflared_stale_credential_item + label: "{{ __cloudflared_stale_credential_item.path }}" + + - name: Create systemd service file for cloudflared + ansible.builtin.copy: + dest: "{{ cloudflared_service_unit }}" + content: | + [Unit] + Description=Cloudflare Tunnel + After=network.target + + [Service] + User={{ cloudflared_user }} + Group={{ cloudflared_group }} + ExecStart={{ cloudflared_install_dir }}/cloudflared tunnel \ + --config {{ cloudflared_config_dir }}/config.yml run + Restart=always + + [Install] + WantedBy=multi-user.target + owner: root + group: root + mode: "0644" + + - name: Reload systemd daemon + ansible.builtin.systemd: + daemon_reload: true + + - name: Enable and start cloudflared + ansible.builtin.systemd: + name: cloudflared + enabled: true + state: started + + - name: Check cloudflared service status + ansible.builtin.systemd: + name: cloudflared + register: __cloudflared_service_status + tags: [cloudflared, configure, health] + + - name: Fail if cloudflared service is not running + ansible.builtin.fail: + msg: "cloudflared service is not running" + when: __cloudflared_service_status.status.ActiveState != "active" + tags: [cloudflared, configure, health] diff --git a/roles/cloudflared/tasks/download.yml b/roles/cloudflared/tasks/download.yml new file mode 100644 index 0000000..7b1f0f2 --- /dev/null +++ b/roles/cloudflared/tasks/download.yml @@ -0,0 +1,18 @@ +--- +# The one download of the cloudflared binary, shared by install.yml (straight onto the live +# path, since nothing runs yet) and update.yml (into a staging path next to it, before +# mortis.kamino._binary_update stops the daemon and swaps it in). get_url checks +# cloudflared_sha256_amd64 before it moves the file to __cloudflared_download_dest, so a failed or +# mismatching download leaves that path as it was. +# Tagged install and update: an include does not pass its tags on to the tasks it includes, +# so under --tags update a task tagged install only would be skipped. +- name: Download and verify the cloudflared binary + become: true + ansible.builtin.get_url: + url: "{{ cloudflared_download_url }}" + dest: "{{ __cloudflared_download_dest }}" + checksum: "sha256:{{ cloudflared_sha256_amd64 }}" + owner: root + group: root + mode: "0755" + tags: [cloudflared, install, update] diff --git a/roles/cloudflared/tasks/install.yml b/roles/cloudflared/tasks/install.yml new file mode 100644 index 0000000..a5f0283 --- /dev/null +++ b/roles/cloudflared/tasks/install.yml @@ -0,0 +1,21 @@ +--- +- name: Download and install cloudflared binary + ansible.builtin.include_tasks: download.yml + vars: + __cloudflared_download_dest: "{{ cloudflared_install_dir }}/cloudflared" + tags: [cloudflared, install] + +- name: Ensure cloudflared binary exists + ansible.builtin.stat: + path: "{{ cloudflared_install_dir }}/cloudflared" + register: __cloudflared_binary + tags: [cloudflared, install, health] + +- name: Fail if cloudflared binary missing + ansible.builtin.assert: + that: + - __cloudflared_binary.stat.exists + fail_msg: "cloudflared binary not found after download" + # Nothing is downloaded under --check. + when: not ansible_check_mode + tags: [cloudflared, install, health] diff --git a/roles/cloudflared/tasks/main.yml b/roles/cloudflared/tasks/main.yml new file mode 100644 index 0000000..8808925 --- /dev/null +++ b/roles/cloudflared/tasks/main.yml @@ -0,0 +1,32 @@ +--- +- name: Validate the role inputs + ansible.builtin.import_tasks: validate.yml + tags: [cloudflared, always] + +# The removal ends the role: none of the tasks below runs, so a removed daemon is not +# installed and configured again in the same run. +- name: Remove cloudflared (explicit only) + ansible.builtin.include_tasks: remove.yml + when: cloudflared_remove | bool + tags: [cloudflared, remove] + +- name: Install, configure and update cloudflared + when: not (cloudflared_remove | bool) + block: + - name: Include prerequisites + ansible.builtin.include_tasks: prereqs.yml + tags: [cloudflared, prereqs, always] + + - name: Install cloudflared if missing + ansible.builtin.include_tasks: install.yml + when: not __cloudflared_installed + tags: [cloudflared, install] + + - name: Configure cloudflared + ansible.builtin.include_tasks: configure.yml + tags: [cloudflared, configure, health] + + - name: Ensure cloudflared is up-to-date + ansible.builtin.include_tasks: update.yml + when: cloudflared_update | bool + tags: [cloudflared, update] diff --git a/roles/cloudflared/tasks/mint.yml b/roles/cloudflared/tasks/mint.yml new file mode 100644 index 0000000..d54ccfe --- /dev/null +++ b/roles/cloudflared/tasks/mint.yml @@ -0,0 +1,95 @@ +--- +# Opt-in entry point (tasks_from: mint): creates the Cloudflare Tunnel through the Cloudflare +# API from the controller (no `cloudflared tunnel login`, no browser) and registers its id and +# credentials as the no_log facts cloudflared_minted_tunnel_id and +# cloudflared_minted_credentials_json. The tunnel secret exists only in memory. Persisting the +# facts (for example vault-encrypted into inventory as cloudflared_tunnel_id and +# cloudflared_credentials_json) is the calling play's job; this role writes no file. +- name: Require explicit opt-in for the cloudflared mint + ansible.builtin.assert: + that: + - cloudflared_mint_confirm | bool + fail_msg: "cloudflared mint is opt-in: pass -e cloudflared_mint_confirm=true" + quiet: true + tags: [cloudflared, always] + +- name: Refuse to mint under CI + ansible.builtin.assert: + that: + - lookup('ansible.builtin.env', 'GITHUB_ACTIONS') | length == 0 + - lookup('ansible.builtin.env', 'GITEA_ACTIONS') | length == 0 + - lookup('ansible.builtin.env', 'CI') | length == 0 + fail_msg: "cloudflared mint refuses to run under CI: run the mint play by hand" + quiet: true + tags: [cloudflared, always] + +# Defined and empty (or null) counts as missing: the main entry point asserts a non-empty id, so +# skipping the mint on an empty one would deadlock. A tunnel that is already set is never +# replaced, so a re-run is safe. +- name: Skip the cloudflared mint when the tunnel is already set + ansible.builtin.debug: + msg: "cloudflared_tunnel_id is already set for {{ inventory_hostname }}; nothing to mint." + when: (cloudflared_tunnel_id | default('', true) | string | length) > 0 + tags: [cloudflared, mint] + +# Before anything is created, and in --check too. +- name: Require the mint inputs + ansible.builtin.assert: + that: + - cloudflared_account_id | default('', true) | string | length > 0 + - cloudflared_tunnel_api_token | default('', true) | string | length > 0 + - cloudflared_tunnel_name | default('', true) | string | length > 0 + fail_msg: >- + cloudflared_account_id, cloudflared_tunnel_api_token (vaulted) and cloudflared_tunnel_name must be set + and non-empty to mint a tunnel. + quiet: true + when: (cloudflared_tunnel_id | default('', true) | string | length) == 0 + tags: [cloudflared, always] + +# uri makes its request even under --check, so the block is skipped there: a preview must never +# create a tunnel. +- name: Mint Cloudflare Tunnel via API + when: (cloudflared_tunnel_id | default('', true) | string | length) == 0 and not ansible_check_mode + delegate_to: localhost + become: false + tags: [cloudflared, mint] + block: + - name: Generate tunnel secret + ansible.builtin.command: + argv: [openssl, rand, -base64, "32"] + register: __cloudflared_tunnel_secret + changed_when: false + no_log: true + + - name: Create Cloudflare Tunnel via API + ansible.builtin.uri: + url: "{{ cloudflared_api_base_url }}/accounts/{{ cloudflared_account_id }}/cfd_tunnel" + method: POST + headers: + Authorization: "Bearer {{ cloudflared_tunnel_api_token }}" + Content-Type: "application/json" + body_format: json + body: + name: "{{ cloudflared_tunnel_name }}" + tunnel_secret: "{{ __cloudflared_tunnel_secret.stdout | trim }}" + config_src: "local" + status_code: [200] + register: __cloudflared_tunnel_create + changed_when: true + no_log: true + + # Not cloudflared_tunnel_id itself: the block's `when` is re-evaluated per task and reads it, + # so setting it here would skip every task after this one. Not cacheable and never printed. + - name: Register the minted tunnel facts + ansible.builtin.set_fact: + cloudflared_minted_tunnel_id: "{{ __cloudflared_tunnel_create.json.result.id }}" + cloudflared_minted_credentials_json: "{{ __cloudflared_tunnel_create.json.result.credentials_file | to_json }}" + no_log: true + + # The raw secret and the API response (its credentials_file holds the TunnelSecret) would + # otherwise stay in the host's vars for the rest of the play; only the minted facts are kept. + - name: Clear the tunnel secret intermediates + ansible.builtin.set_fact: + __cloudflared_tunnel_secret: "" + __cloudflared_tunnel_create: "" + no_log: true diff --git a/roles/cloudflared/tasks/prereqs.yml b/roles/cloudflared/tasks/prereqs.yml new file mode 100644 index 0000000..8865549 --- /dev/null +++ b/roles/cloudflared/tasks/prereqs.yml @@ -0,0 +1,39 @@ +--- +- name: Create cloudflared group + become: true + ansible.builtin.group: + name: "{{ cloudflared_group }}" + system: true + tags: [cloudflared, prereqs, always] + +- name: Create cloudflared user + become: true + ansible.builtin.user: + name: "{{ cloudflared_user }}" + group: "{{ cloudflared_group }}" + shell: /usr/sbin/nologin + comment: "Cloudflare Tunnel daemon" + system: true + create_home: false + tags: [cloudflared, prereqs, always] + +- name: Create cloudflared config directory + become: true + ansible.builtin.file: + path: "{{ cloudflared_config_dir }}" + state: directory + owner: "{{ cloudflared_user }}" + group: "{{ cloudflared_group }}" + mode: "0750" + tags: [cloudflared, prereqs, always] + +- name: Check if cloudflared binary exists + ansible.builtin.stat: + path: "{{ cloudflared_install_dir }}/cloudflared" + register: __cloudflared_binary + tags: [cloudflared, prereqs, always] + +- name: Set cloudflared facts + ansible.builtin.set_fact: + __cloudflared_installed: "{{ __cloudflared_binary.stat.exists }}" + tags: [cloudflared, prereqs, always] diff --git a/roles/cloudflared/tasks/remove.yml b/roles/cloudflared/tasks/remove.yml new file mode 100644 index 0000000..e6cf4de --- /dev/null +++ b/roles/cloudflared/tasks/remove.yml @@ -0,0 +1,88 @@ +--- +# Run with -e cloudflared_remove=true (and cloudflared_remove_data=true to delete the +# configuration, the user, and the tunnel and its DNS records on Cloudflare too). The role ends +# after these tasks. +- name: Stop cloudflared service + become: true + ansible.builtin.systemd: + name: cloudflared + state: stopped + enabled: false + register: __cloudflared_stop + # The unit may already be gone (systemd: "Could not find the requested service "). + # Any other stop failure must halt here, before the unit file and data are deleted. + failed_when: + - __cloudflared_stop.failed | default(false) + - "'Could not find the requested service' not in (__cloudflared_stop.msg | default(''))" + tags: [cloudflared, remove] + +- name: Remove systemd service + become: true + ansible.builtin.file: + path: "{{ cloudflared_service_unit }}" + state: absent + tags: [cloudflared, remove] + +- name: Reload systemd + become: true + ansible.builtin.systemd: + daemon_reload: true + tags: [cloudflared, remove] + +- name: Remove cloudflared binary + become: true + ansible.builtin.file: + path: "{{ cloudflared_install_dir }}/cloudflared" + state: absent + tags: [cloudflared, remove] + +- name: Remove cloudflared configuration + become: true + ansible.builtin.file: + path: "{{ cloudflared_config_dir }}" + state: absent + when: cloudflared_remove_data | bool + tags: [cloudflared, remove] + +- name: Remove cloudflared user + become: true + ansible.builtin.user: + name: "{{ cloudflared_user }}" + state: absent + remove: true + when: cloudflared_remove_data | bool + tags: [cloudflared, remove] + +# Permanently deletes the tunnel and its DNS records on Cloudflare, so it needs +# cloudflared_remove_data: a plain cloudflared_remove only touches the host. +- name: Remove Cloudflare-side tunnel resources + when: + - cloudflared_remove_data | bool + - (cloudflared_tunnel_id | default('', true) | string | length) > 0 + delegate_to: localhost + become: false + no_log: true + block: + - name: Remove public DNS record(s) for the tunnel + loop: "{{ cloudflared_ingress }}" + loop_control: + loop_var: __cloudflared_ingress_item + label: "{{ __cloudflared_ingress_item.hostname }}" + community.general.cloudflare_dns: + zone: "{{ cloudflared_zone_name }}" + record: "{{ __cloudflared_ingress_item.hostname }}" + type: CNAME + value: "{{ cloudflared_tunnel_id }}.cfargotunnel.com" + api_token: "{{ cloudflared_tunnel_api_token }}" + state: absent + when: cloudflared_manage_dns | bool + tags: [cloudflared, remove] + + - name: Delete the Cloudflare Tunnel via API + ansible.builtin.uri: + url: "{{ cloudflared_api_base_url }}/accounts/{{ cloudflared_account_id }}/cfd_tunnel/{{ cloudflared_tunnel_id }}" + method: DELETE + headers: + Authorization: "Bearer {{ cloudflared_tunnel_api_token }}" + status_code: [200] + tags: [cloudflared, remove] diff --git a/roles/cloudflared/tasks/update.yml b/roles/cloudflared/tasks/update.yml new file mode 100644 index 0000000..8100241 --- /dev/null +++ b/roles/cloudflared/tasks/update.yml @@ -0,0 +1,106 @@ +--- +- name: Check installed cloudflared version + ansible.builtin.command: + argv: ["{{ cloudflared_install_dir }}/cloudflared", --version] + register: __cloudflared_version_cmd + changed_when: false + # Failure is expected when the binary is missing (rc 2): empty stdout falls through to 0.0.0 + # below, which triggers the install path. + failed_when: false + # Read-only, so it also runs in the --check preview. Skipped there, stdout would be empty, the + # version would fall back to 0.0.0 and the sha256 guard below would fail against an up-to-date + # binary. + check_mode: false + tags: [cloudflared, update] + +- name: Extract installed cloudflared version + ansible.builtin.set_fact: + __cloudflared_installed_version: >- + {{ + (__cloudflared_version_cmd.stdout + | regex_findall('([0-9]{4}\.[0-9]+\.[0-9]+)') + | first) + | default('0.0.0') + }} + tags: [cloudflared, update] + +- name: Determine if cloudflared update required + ansible.builtin.set_fact: + __cloudflared_update_required: "{{ __cloudflared_installed_version != cloudflared_version }}" + # Next to the live binary, so the swap is a rename on one filesystem. + __cloudflared_staged_binary: "{{ cloudflared_install_dir }}/cloudflared.new" + tags: [cloudflared, update] + +# A hash left over from an older release (a version bumped without its hash) would fail the +# staged download below with a bare checksum mismatch. Say what is wrong instead. Read-only, so +# it also runs in the --check preview. +- name: Check the installed binary against the configured sha256 + ansible.builtin.stat: + path: "{{ cloudflared_install_dir }}/cloudflared" + checksum_algorithm: sha256 + get_checksum: true + register: __cloudflared_installed_stat + when: __cloudflared_update_required + tags: [cloudflared, update] + +- name: Fail when cloudflared_sha256_amd64 is the hash of the installed binary + ansible.builtin.assert: + that: + - (__cloudflared_installed_stat.stat.checksum | default('')) | lower != cloudflared_sha256_amd64 | lower + fail_msg: >- + cloudflared_sha256_amd64 equals the sha256 of the binary installed on {{ inventory_hostname }} + (version {{ __cloudflared_installed_version }}), but cloudflared_version is {{ cloudflared_version }}. + The hash is stale: set it to the sha256 of the cloudflared-linux-amd64 asset of release + {{ cloudflared_version }}. + quiet: true + when: __cloudflared_update_required + tags: [cloudflared, update] + +# Download and verify before anything is stopped: a failed download or checksum leaves the +# running daemon untouched. mortis.kamino._binary_update then stops, backs up, swaps, restarts, +# checks the version and rolls back on failure, and removes the staged binary. A binary that +# reports no version (0.0.0 above) is replaced too; _binary_update backs it up when it exists. +- name: Stage and swap in the new cloudflared binary + when: __cloudflared_update_required + block: + # Its own rescue, so that only a staging failure gets this message: a failure in the swap + # below keeps the rollback message of mortis.kamino._binary_update. + - name: Stage the new cloudflared binary + block: + - name: Download and verify into the staging path + ansible.builtin.include_tasks: download.yml + vars: + __cloudflared_download_dest: "{{ __cloudflared_staged_binary }}" + tags: [cloudflared, update] + rescue: + - name: Fail the staging + ansible.builtin.fail: + msg: >- + Staging cloudflared {{ cloudflared_version }} failed ({{ ansible_failed_result.msg | default('see the task above') }}). + cloudflared was not stopped and still runs {{ __cloudflared_installed_version }}. + tags: [cloudflared, update] + + # An include does not pass its tags on to the included tasks, hence apply. + - name: Swap in the staged cloudflared binary + ansible.builtin.include_role: + name: mortis.kamino._binary_update + apply: + tags: [cloudflared, update] + vars: + _binary_update_service: cloudflared + _binary_update_binary_path: "{{ cloudflared_install_dir }}/cloudflared" + _binary_update_staged_path: "{{ __cloudflared_staged_binary }}" + _binary_update_version_command: ["{{ cloudflared_install_dir }}/cloudflared", --version] + _binary_update_expected_version: "{{ cloudflared_version }}" + _binary_update_version_regex: '([0-9]{4}\.[0-9]+\.[0-9]+)' + tags: [cloudflared, update] + + always: + # Left behind only when the run failed before the swap; get_url would reuse a matching + # file anyway, but a stale binary next to the live one is clutter. + - name: Remove the staged cloudflared binary + become: true + ansible.builtin.file: + path: "{{ __cloudflared_staged_binary }}" + state: absent + tags: [cloudflared, update] diff --git a/roles/cloudflared/tasks/validate.yml b/roles/cloudflared/tasks/validate.yml new file mode 100644 index 0000000..6199108 --- /dev/null +++ b/roles/cloudflared/tasks/validate.yml @@ -0,0 +1,81 @@ +--- +# Input checks. Imported first in main.yml with tags: always, so a bad input fails before any +# change, whatever tags the run selects. +- name: Require a plain cloudflared_version + ansible.builtin.assert: + that: + - cloudflared_version is string + - cloudflared_version is match('^[0-9]{4}\\.[0-9]+\\.[0-9]+$') + fail_msg: >- + cloudflared_version must be a release tag such as 2026.11.1 (YYYY.M.P), with no leading v: it is + used in the download URL and compared with what the binary reports. + quiet: true + +- name: Require a sha256 for the binary + ansible.builtin.assert: + that: + - cloudflared_sha256_amd64 is string + - cloudflared_sha256_amd64 is match('^[0-9a-fA-F]{64}$') + fail_msg: >- + cloudflared_sha256_amd64 must be the 64-digit hex sha256 of the cloudflared-linux-amd64 asset of + release {{ cloudflared_version }}. + quiet: true + +# The items land in config.yml and, with cloudflared_manage_dns, become DNS records. +- name: Require a hostname and a service for every ingress rule + ansible.builtin.assert: + that: + - cloudflared_ingress is sequence + - cloudflared_ingress is not string + - cloudflared_ingress is not mapping + - cloudflared_ingress | reject('mapping') | list | length == 0 + - cloudflared_ingress | selectattr('hostname', 'defined') | selectattr('service', 'defined') | list | length == cloudflared_ingress | length + fail_msg: >- + cloudflared_ingress must be a list of mappings, each with hostname and service (and optionally + originRequest). + quiet: true + +# The role never creates the tunnel on its main entry point. Defined and empty (or null) counts +# as missing, as in the mint entry point, so the two cannot disagree. +- name: Require the minted tunnel secrets + ansible.builtin.assert: + that: + - cloudflared_tunnel_id | default('', true) | string | length > 0 + - cloudflared_credentials_json | default('', true) | string | length > 0 + fail_msg: >- + cloudflared_tunnel_id and cloudflared_credentials_json are not defined or empty: run the mint entry + point first (include_role with tasks_from: mint and -e cloudflared_mint_confirm=true), persist + cloudflared_minted_tunnel_id and cloudflared_minted_credentials_json into your inventory as these two + variables, and run the role again. + quiet: true + when: not (cloudflared_remove | bool) + +# Every Cloudflare call below needs them: the tunnel check on every run, the tunnel deletion +# of a removal with cloudflared_remove_data. +- name: Require the Cloudflare API credentials + ansible.builtin.assert: + that: + - cloudflared_account_id | default('', true) | string | length > 0 + - cloudflared_tunnel_api_token | default('', true) | string | length > 0 + fail_msg: >- + cloudflared_account_id and cloudflared_tunnel_api_token (vaulted) have no role default and must be set + and non-empty. + quiet: true + when: >- + not (cloudflared_remove | bool) or + ((cloudflared_remove_data | bool) and (cloudflared_tunnel_id | default('', true) | string | length) > 0) + +- name: Require the zone while the role manages DNS + ansible.builtin.assert: + that: + - cloudflared_zone_name is string + - cloudflared_zone_name | length > 0 + fail_msg: >- + cloudflared_manage_dns is true, so cloudflared_zone_name must name the DNS zone of the + cloudflared_ingress hostnames. + quiet: true + when: + - cloudflared_manage_dns | bool + - >- + not (cloudflared_remove | bool) or + ((cloudflared_remove_data | bool) and (cloudflared_tunnel_id | default('', true) | string | length) > 0) diff --git a/roles/cloudflared/templates/config.yml.j2 b/roles/cloudflared/templates/config.yml.j2 new file mode 100644 index 0000000..1683ff9 --- /dev/null +++ b/roles/cloudflared/templates/config.yml.j2 @@ -0,0 +1,13 @@ +tunnel: {{ cloudflared_tunnel_id }} +credentials-file: {{ cloudflared_config_dir }}/{{ cloudflared_tunnel_id }}.json + +ingress: +{% for rule in cloudflared_ingress %} + - hostname: {{ rule.hostname }} + service: {{ rule.service }} +{% if rule.originRequest is defined %} + originRequest: +{{ rule.originRequest | to_nice_yaml | indent(6, first=true) }} +{% endif %} +{% endfor %} + - service: http_status:404