The plain scalar `cloudflared_test_posts[0] is search('"status": 200')`
holds ': ', so YAML parsed it as a one-key mapping and ansible-core
refused it ("Conditional expressions must be strings"). A folded block
scalar keeps it a string.
Assisted-by: Claude Code:claude-opus-5-5
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, 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_idandcloudflared_tunnel_api_token(vaulted), and, whilecloudflared_manage_dnsis true,cloudflared_zone_name; list the routed hostnames incloudflared_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_idandcloudflared_credentials_jsonhave 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 themintentry point first, persist its output facts into inventory under these two names, then run the role (see Entry points). - The secrets are not
requiredin 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 themintentry point must run whilecloudflared_tunnel_idis 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_versionis asserted at role start to be aYYYY.M.Prelease tag, with no leadingv, andcloudflared_sha256_amd64to 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 <config_dir>/<tunnel id>.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:- 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_confirmmust be true, and the entry point fails whenGITHUB_ACTIONS,GITEA_ACTIONSorCIis set in the controller environment. This guards against accidents; it is not a security boundary. - When
cloudflared_tunnel_idis 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_tokenandcloudflared_tunnel_name, generates the tunnel secret in memory withopenssl rand -base64 32on the controller, creates the tunnel through the API withconfig_src: localand registerscloudflared_minted_tunnel_idandcloudflared_minted_credentials_jsonasno_logfacts. 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.
- Guards:
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
- 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.ymlalways runs validation, prerequisites and configure unlesscloudflared_removeis true; the binary install only when it is absent; the update only when the installed version differs; remove only whencloudflared_removeis true, and then every later task is skipped. - Secrets: the tasks that create the secrets, the
uricalls that put the token in the Authorization header, thecloudflare_dnscalls and the credentials file write useno_log(the credentials write also setsdiff: false). A failure of those tasks therefore shows only as "censored": to debug a failed DNS change, check the Cloudflare audit log or setno_log: falseon a throwaway run against a non-secret zone. The tunnel id itself is not masked: it shows inconfig.ymldiffs, 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, then failing with the re-mint instructions), if the tunnel lookup fails otherwise (with its HTTP status), if the zone is not found, or if an existing record for an ingress hostname does not point at some
cfargotunnel.comtunnel and the hostname is not incloudflared_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_ingressare deleted. The lookup is filtered by the tunnel'scfargotunnel.comtarget, so other records in the zone are not touched. - Re-mint after a tunnel was deleted out of band: remove the stale
cloudflared_tunnel_idandcloudflared_credentials_jsonfrom inventory, run themintentry point and persist its output. - Stale credentials: files named
<uuid>.jsonin the config directory other than the current tunnel's are removed. - The
Restart cloudflaredhandler runs whenconfig.ymlor the credentials file changes. cloudflared's own ingress check (ingress validate) runs afterconfig.ymlis written. - Update: the version is compared as
YYYY.M.Pagainstcloudflared --version. The new binary is downloaded and checksum-verified intocloudflared.newbefore 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
cloudflaredis notactiveafter start.