test(cloudflared): add the default molecule scenario

Runs without Cloudflare and without a real cloudflared: a stub of the
Cloudflare API on the controller's loopback answers the tunnel, zone and
DNS record calls through cloudflared_api_base_url, a stub binary stands
in for the daemon, and the releases come from file:// URLs.

Covers the converge with an update through _binary_update and its
idempotence, the rendered files and the running unit, the input asserts,
the deleted-tunnel and DNS guards, a stale hash and a failed checksum,
the mint entry point (as child processes outside CI) and the remove
path. The cloudflare_dns calls cannot reach the stub and are not run.

Assisted-by: Claude Code:claude-opus-5-5
This commit is contained in:
Defame1297 committed 2026-11-23 14:22:16 +00:00
1 parent e308683431
commit 9a626962a5
8 files changed
+831

No files matched your search

@@ -0,0 +1,23 @@
---
# Stops the Cloudflare API stub that prepare.yml started on the controller. Also run before
# create, when there is nothing to stop yet.
- name: Cleanup
hosts: localhost
connection: local
gather_facts: false
vars:
cloudflared_test_stub_dir: "{{ lookup('ansible.builtin.env', 'MOLECULE_EPHEMERAL_DIRECTORY') }}/cloudflare-stub"
tasks:
- name: Read the pid of the stub
ansible.builtin.slurp:
src: "{{ cloudflared_test_stub_dir }}/pid"
register: cloudflared_test_stub_pid
failed_when: false
- name: Stop the stub
ansible.builtin.command:
argv: [kill, "{{ cloudflared_test_stub_pid.content | b64decode | trim }}"]
# It may have ended at its lifetime already.
failed_when: false
changed_when: true
when: cloudflared_test_stub_pid.content is defined
@@ -0,0 +1,9 @@
---
# Role variables come from the inventory group_vars in molecule.yml. The first run updates the
# stub binary from 2026.1.0 to 2026.2.0 through mortis.kamino._binary_update; the idempotence run
# finds 2026.2.0 and changes nothing.
- name: Converge
hosts: all
gather_facts: false
roles:
- role: mortis.kamino.cloudflared
@@ -0,0 +1,168 @@
"""Stub of the Cloudflare API calls of the cloudflared role, for its molecule scenario.
Listens on 127.0.0.1 on a free port, writes the port to <state-dir>/port and its pid to
<state-dir>/pid, and appends one JSON line per request (method, path, status; never a secret)
to <state-dir>/requests.log. Exits by itself after --lifetime seconds, so a cancelled run
leaves nothing running for long.
"""
import argparse
import base64
import binascii
import json
import os
import re
import threading
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit
PREFIX = "/client/v4"
TOKEN = "molecule-not-a-token"
ACCOUNT = "molecule-account"
ZONE_NAME = "example.test"
ZONE_ID = "molecule-zone"
# Tunnel id -> deleted_at (None while the tunnel exists).
TUNNELS = {
"6f1a6e2c-0000-4000-8000-000000000001": None,
"6f1a6e2c-0000-4000-8000-000000000002": "2026-01-01T00:00:00Z",
}
RECORDS = [
{"name": "taken.example.test", "type": "A", "content": "192.0.2.10"},
{
"name": "moved.example.test",
"type": "CNAME",
"content": "6f1a6e2c-0000-4000-8000-000000000009.cfargotunnel.com",
},
]
TUNNEL_PATH = re.compile(r"^/accounts/([^/]+)/cfd_tunnel(?:/([^/]+))?$")
RECORDS_PATH = re.compile(r"^/zones/([^/]+)/dns_records$")
LOCK = threading.Lock()
class Handler(BaseHTTPRequestHandler):
state_dir = "."
# Quiet: the requests go to requests.log instead of stderr.
def log_message(self, format, *args):
pass
def _send(self, status, result=None):
body = json.dumps(
{"success": status == 200, "errors": [], "result": result}
).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
with (
LOCK,
open(
os.path.join(self.state_dir, "requests.log"), "a", encoding="utf-8"
) as log,
):
log.write(
json.dumps(
{"method": self.command, "path": self.path, "status": status}
)
+ "\n"
)
def _route(self):
if self.headers.get("Authorization") != f"Bearer {TOKEN}":
return self._send(403)
url = urlsplit(self.path)
if not url.path.startswith(PREFIX):
return self._send(404)
path = url.path[len(PREFIX) :]
query = {key: values[0] for key, values in parse_qs(url.query).items()}
match = TUNNEL_PATH.match(path)
if match and match.group(1) == ACCOUNT:
return self._tunnel(match.group(2))
match = RECORDS_PATH.match(path)
if self.command == "GET" and match and match.group(1) == ZONE_ID:
records = [
r
for r in RECORDS
if all(r.get(k) == query[k] for k in ("type", "content") if k in query)
]
return self._send(200, records)
if self.command == "GET" and path == "/zones":
zones = (
[{"id": ZONE_ID, "name": ZONE_NAME}]
if query.get("name") == ZONE_NAME
else []
)
return self._send(200, zones)
return self._send(404)
def _tunnel(self, tunnel_id):
if tunnel_id is None and self.command == "POST":
return self._create()
if tunnel_id not in TUNNELS:
return self._send(404)
if self.command == "GET":
return self._send(200, {"id": tunnel_id, "deleted_at": TUNNELS[tunnel_id]})
if self.command == "DELETE":
TUNNELS[tunnel_id] = "2026-01-01T00:00:00Z"
return self._send(200, {"id": tunnel_id})
return self._send(405)
# Accepts only what the real API needs for a locally managed tunnel: a name, config_src
# local and a base64 secret of at least 32 bytes.
def _create(self):
try:
body = json.loads(
self.rfile.read(int(self.headers.get("Content-Length", "0")))
)
secret = base64.b64decode(body["tunnel_secret"], validate=True)
except (ValueError, KeyError, TypeError, binascii.Error):
return self._send(400)
if (
not body.get("name")
or body.get("config_src") != "local"
or len(secret) < 32
):
return self._send(400)
tunnel_id = str(uuid.uuid4())
TUNNELS[tunnel_id] = None
credentials = {
"AccountTag": ACCOUNT,
"TunnelID": tunnel_id,
"TunnelName": body["name"],
"TunnelSecret": body["tunnel_secret"],
}
return self._send(
200,
{"id": tunnel_id, "name": body["name"], "credentials_file": credentials},
)
do_GET = _route
do_POST = _route
do_DELETE = _route
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--state-dir", required=True)
parser.add_argument("--lifetime", type=int, default=1500)
args = parser.parse_args()
os.makedirs(args.state_dir, exist_ok=True)
Handler.state_dir = args.state_dir
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
for name, value in (("pid", os.getpid()), ("port", server.server_address[1])):
tmp = os.path.join(args.state_dir, name + ".tmp")
with open(tmp, "w", encoding="utf-8") as handle:
handle.write(f"{value}\n")
os.replace(tmp, os.path.join(args.state_dir, name))
timer = threading.Timer(args.lifetime, server.shutdown)
timer.daemon = True
timer.start()
server.serve_forever()
if __name__ == "__main__":
main()
@@ -0,0 +1,48 @@
---
# Run by verify.yml in a child ansible-playbook process, because the mint guard reads the
# controller's environment (lookup env), which a play cannot change; the child gets its
# environment from the task that starts it, so the result does not depend on what the runner
# exports. The child uses `-i localhost,` and so does not see the molecule group_vars: verify.yml
# passes the inputs with -e, and cloudflared_test_expect_minted says what to assert afterwards.
- name: Mint with a controlled environment
hosts: localhost
connection: local
gather_facts: false
tasks:
- name: Run the mint entry point
ansible.builtin.include_role:
name: mortis.kamino.cloudflared
tasks_from: mint
vars:
cloudflared_mint_confirm: true
- name: No tunnel fact was registered
ansible.builtin.assert:
that:
- cloudflared_minted_tunnel_id is not defined
- cloudflared_minted_credentials_json is not defined
quiet: true
when: not (cloudflared_test_expect_minted | default(false) | bool)
- name: Parse the minted credentials
ansible.builtin.set_fact:
cloudflared_test_minted: "{{ cloudflared_minted_credentials_json | from_json }}"
no_log: true
when: cloudflared_test_expect_minted | default(false) | bool
# The stub accepted the secret only as base64 of at least 32 bytes; 32 bytes are 44
# characters. The secret and the API response must not stay in the host's variables.
- name: The tunnel facts were registered and the intermediates cleared
ansible.builtin.assert:
that:
- cloudflared_minted_tunnel_id is match('^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')
- cloudflared_test_minted.TunnelID == cloudflared_minted_tunnel_id
- cloudflared_test_minted.AccountTag == cloudflared_account_id
- cloudflared_test_minted.TunnelName == cloudflared_tunnel_name
- cloudflared_test_minted.TunnelSecret | length == 44
- __cloudflared_tunnel_secret == ""
- __cloudflared_tunnel_create == ""
fail_msg: The minted tunnel facts are missing or wrong, or an intermediate was kept
quiet: true
no_log: true
when: cloudflared_test_expect_minted | default(false) | bool
@@ -0,0 +1,87 @@
---
# Runs on the repository's own runner (label kamino-molecule), in the molecule-ubuntu2404 image
# (MOLECULE_IMAGE, the pin in .gitea/workflows/molecule.yml). No Cloudflare and no real
# cloudflared: prepare.yml starts a stub of the Cloudflare API on the controller's loopback
# (files/cloudflare_api_stub.py, reached through cloudflared_api_base_url; cleanup.yml stops it)
# and seeds a stub cloudflared binary that reports an older version, so the update downloads its
# new stub from local file:// URLs. The scenario downloads nothing. cloudflared_manage_dns is
# false here because community.general.cloudflare_dns cannot be pointed at the stub; the DNS
# guards in front of it are run with it true in verify.yml.
# The container runs systemd as PID 1 with a writable cgroup; no privileged mode.
driver:
name: docker
platforms:
- name: cloudflared-instance
image: ${MOLECULE_IMAGE}
pre_build_image: true
pull: true
command: /sbin/init
cgroupns_mode: host
volumes:
- /sys/fs/cgroup:/sys/fs/cgroup:rw
tmpfs:
- /run
- /run/lock
security_opts:
- apparmor=unconfined
provisioner:
name: ansible
# One source for every play, so a verify play that runs the role again renders the same
# configuration.
inventory:
group_vars:
all:
# The stub binary; @VERSION@ is replaced per release file. Its hash is the configured
# sha256, so the release files need no checksum file.
cloudflared_test_stub: |
#!/bin/sh
case "$1" in
--version) echo "cloudflared version @VERSION@ (built 2026-01-01-0000 UTC)" ;;
tunnel)
[ "$2" = --config ] || { echo "stub cloudflared: expected --config" >&2; exit 2; }
case "$4" in
ingress) grep -q 'service: http_status:404' "$3" && { echo "Validating rules from $3"; exit 0; } ;;
run) [ -r "$3" ] && exec sleep infinity ;;
esac
echo "stub cloudflared: cannot handle: $*" >&2; exit 1 ;;
*) echo "stub cloudflared: unexpected arguments: $*" >&2; exit 2 ;;
esac
cloudflared_test_stub_dir: "{{ lookup('ansible.builtin.env', 'MOLECULE_EPHEMERAL_DIRECTORY') }}/cloudflare-stub"
cloudflared_test_tunnel_id: 6f1a6e2c-0000-4000-8000-000000000001
cloudflared_test_credentials_json: >-
{"AccountTag": "molecule-account", "TunnelID": "6f1a6e2c-0000-4000-8000-000000000001", "TunnelSecret": "bW9sZWN1bGU="}
cloudflared_version: "2026.2.0"
cloudflared_sha256_amd64: "{{ cloudflared_test_stub | replace('@VERSION@', cloudflared_version) | hash('sha256') }}"
cloudflared_download_url: "file:///opt/molecule-download/cloudflared-{{ cloudflared_version }}"
cloudflared_api_base_url: >-
http://127.0.0.1:{{ lookup('ansible.builtin.file', cloudflared_test_stub_dir ~ '/port') }}/client/v4
cloudflared_account_id: molecule-account
cloudflared_tunnel_api_token: molecule-not-a-token
cloudflared_tunnel_id: "{{ cloudflared_test_tunnel_id }}"
cloudflared_credentials_json: "{{ cloudflared_test_credentials_json }}"
cloudflared_manage_dns: false
cloudflared_ingress: "{{ cloudflared_test_ingress }}"
cloudflared_test_ingress:
- hostname: app.example.test
service: https://127.0.0.1:443
originRequest:
originServerName: app.example.test
- hostname: other.example.test
service: http://127.0.0.1:8080
verifier:
name: ansible
scenario:
# molecule's default sequence minus both destroys: the workflow removes the container before the
# run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait.
# After a local run, run `molecule destroy` yourself.
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
@@ -0,0 +1,75 @@
---
# Stand-ins for what the scenario cannot have: the Cloudflare API (a stub on the controller's
# loopback), an installed cloudflared (a stub binary reporting 2026.1.0, so the converge updates
# it), and the release files of two newer versions behind file:// URLs. The configured sha256 is
# the hash of the stub of the requested version, so 2026.2.0 verifies and 2026.3.0 does only when
# a case passes its hash. A stale tunnel credentials file and an unrelated JSON file are seeded
# in the config directory: configure must remove the first and keep the second.
- name: Prepare
hosts: all
gather_facts: false
tasks:
- name: Remove the state of an earlier stub run
delegate_to: localhost
run_once: true
ansible.builtin.file:
path: "{{ cloudflared_test_stub_dir }}"
state: absent
# Runs in the background until cleanup.yml stops it, or until its lifetime, kept below the
# workflow's 30-minute job timeout, runs out.
- name: Start the Cloudflare API stub on the controller
delegate_to: localhost
run_once: true
ansible.builtin.command:
argv:
- "{{ ansible_playbook_python }}"
- -I
- "{{ playbook_dir }}/files/cloudflare_api_stub.py"
- --state-dir
- "{{ cloudflared_test_stub_dir }}"
- --lifetime
- "1500"
async: 1500
poll: 0
changed_when: true
- name: Wait for the stub to listen
delegate_to: localhost
run_once: true
ansible.builtin.wait_for:
path: "{{ cloudflared_test_stub_dir }}/port"
timeout: 30
- name: Create the download and config directories
ansible.builtin.file:
path: "{{ cloudflared_test_dir }}"
state: directory
mode: "0755"
loop: [/opt/molecule-download, /etc/cloudflared]
loop_control:
loop_var: cloudflared_test_dir
- name: Write the installed stub binary and the release files
ansible.builtin.copy:
dest: "{{ cloudflared_test_release.dest }}"
mode: "0755"
content: "{{ cloudflared_test_stub | replace('@VERSION@', cloudflared_test_release.version) }}"
loop:
- {dest: /usr/local/bin/cloudflared, version: 2026.1.0}
- {dest: /opt/molecule-download/cloudflared-2026.2.0, version: 2026.2.0}
- {dest: /opt/molecule-download/cloudflared-2026.3.0, version: 2026.3.0}
loop_control:
loop_var: cloudflared_test_release
label: "{{ cloudflared_test_release.dest }}"
- name: Seed a stale credentials file and an unrelated JSON file
ansible.builtin.copy:
dest: "/etc/cloudflared/{{ cloudflared_test_seed }}"
mode: "0600"
content: "{}\n"
loop:
- 6f1a6e2c-0000-4000-8000-000000000000.json
- notes.json
loop_control:
loop_var: cloudflared_test_seed
@@ -0,0 +1,38 @@
---
# One failing run: runs the main entry point with the inputs of the case and asserts that the
# expected message, not something else, stopped it. Input: cloudflared_test_case (name, vars,
# expect). Task vars cannot come from a template as a whole, so each input a case may change is
# passed with its scenario value as the default.
- name: "Run the role, case {{ cloudflared_test_case.name }}"
block:
- name: "Include the role, case {{ cloudflared_test_case.name }}"
ansible.builtin.include_role:
name: mortis.kamino.cloudflared
vars:
cloudflared_version: "{{ cloudflared_test_case.vars.cloudflared_version | default('2026.2.0') }}"
cloudflared_sha256_amd64: >-
{{ cloudflared_test_case.vars.cloudflared_sha256_amd64
| default(cloudflared_test_stub | replace('@VERSION@', '2026.2.0') | hash('sha256')) }}
cloudflared_tunnel_id: "{{ cloudflared_test_case.vars.cloudflared_tunnel_id | default(cloudflared_test_tunnel_id) }}"
cloudflared_credentials_json: "{{ cloudflared_test_case.vars.cloudflared_credentials_json | default(cloudflared_test_credentials_json) }}"
cloudflared_account_id: "{{ cloudflared_test_case.vars.cloudflared_account_id | default('molecule-account') }}"
cloudflared_manage_dns: "{{ cloudflared_test_case.vars.cloudflared_manage_dns | default(false) }}"
cloudflared_zone_name: "{{ cloudflared_test_case.vars.cloudflared_zone_name | default('') }}"
cloudflared_ingress: "{{ cloudflared_test_case.vars.cloudflared_ingress | default(cloudflared_test_ingress) }}"
# Only reached when the include returned. The message must not contain the expected
# text, so the rescue below cannot mistake it for the failure under test.
- name: "Fail because the include returned, case {{ cloudflared_test_case.name }}"
ansible.builtin.fail:
msg: The role accepted the input
rescue:
# A failed loop task reports its message per item.
- name: "The expected failure stopped the run, case {{ cloudflared_test_case.name }}"
vars:
cloudflared_test_messages: >-
{{ (ansible_failed_result.msg | default('')) ~ ' '
~ (ansible_failed_result.results | default([]) | map(attribute='msg', default='') | join(' ')) }}
ansible.builtin.assert:
that: cloudflared_test_case.expect in cloudflared_test_messages
fail_msg: "Expected '{{ cloudflared_test_case.expect }}', got: {{ cloudflared_test_messages }}"
quiet: true
@@ -0,0 +1,383 @@
---
- name: Verify the converged daemon
hosts: all
gather_facts: false
tasks:
- name: Read config.yml
ansible.builtin.slurp:
src: /etc/cloudflared/config.yml
register: cloudflared_test_config_raw
- name: Parse config.yml
ansible.builtin.set_fact:
cloudflared_test_config: "{{ cloudflared_test_config_raw.content | b64decode | from_yaml }}"
- name: Config.yml routes the ingress hostnames and ends with the catch-all
ansible.builtin.assert:
that:
- cloudflared_test_config.tunnel == cloudflared_test_tunnel_id
- cloudflared_test_config['credentials-file'] == '/etc/cloudflared/' ~ cloudflared_test_tunnel_id ~ '.json'
- cloudflared_test_config.ingress | length == 3
- cloudflared_test_config.ingress[0].hostname == 'app.example.test'
- cloudflared_test_config.ingress[0].service == 'https://127.0.0.1:443'
- "cloudflared_test_config.ingress[0].originRequest == {'originServerName': 'app.example.test'}"
- cloudflared_test_config.ingress[1].hostname == 'other.example.test'
- cloudflared_test_config.ingress[1].originRequest is not defined
- "cloudflared_test_config.ingress[2] == {'service': 'http_status:404'}"
quiet: true
- name: Read the credentials file
ansible.builtin.slurp:
src: "/etc/cloudflared/{{ cloudflared_test_tunnel_id }}.json"
register: cloudflared_test_credentials
no_log: true
- name: Stat the configuration, the seeded files and what an update leaves behind
ansible.builtin.stat:
path: "{{ cloudflared_test_path }}"
loop:
- /etc/cloudflared/config.yml
- "/etc/cloudflared/{{ cloudflared_test_tunnel_id }}.json"
- /etc/cloudflared/6f1a6e2c-0000-4000-8000-000000000000.json
- /etc/cloudflared/notes.json
- /usr/local/bin/cloudflared.new
- /usr/local/bin/cloudflared.bak
loop_control:
loop_var: cloudflared_test_path
register: cloudflared_test_files
- name: The files are private to the daemon, the stale credentials are gone and the update left nothing behind
ansible.builtin.assert:
that:
- cloudflared_test_files.results[0].stat.mode == '0640'
- cloudflared_test_files.results[0].stat.pw_name == 'cloudflared'
- cloudflared_test_files.results[1].stat.mode == '0600'
- cloudflared_test_files.results[1].stat.pw_name == 'cloudflared'
- (cloudflared_test_credentials.content | b64decode | from_json) == (cloudflared_test_credentials_json | from_json)
- not cloudflared_test_files.results[2].stat.exists
- cloudflared_test_files.results[3].stat.exists
- not cloudflared_test_files.results[4].stat.exists
- not cloudflared_test_files.results[5].stat.exists
quiet: true
- name: Ask the installed binary for its version
ansible.builtin.command:
argv: [/usr/local/bin/cloudflared, --version]
register: cloudflared_test_version
changed_when: false
- name: Ask systemd about the daemon
ansible.builtin.systemd:
name: cloudflared
register: cloudflared_test_unit
# The stub's `run` only keeps running when it can read the config it was given, so an active
# unit shows the service user reads config.yml.
- name: Stat the daemon's process
ansible.builtin.stat:
path: "/proc/{{ cloudflared_test_unit.status.MainPID }}"
register: cloudflared_test_process
- name: The updated daemon runs as the service user with the rendered config
ansible.builtin.assert:
that:
- "'2026.2.0' in cloudflared_test_version.stdout"
- cloudflared_test_unit.status.ActiveState == 'active'
- cloudflared_test_unit.status.UnitFileState == 'enabled'
- cloudflared_test_unit.status.ExecStart is search('--config /etc/cloudflared/config.yml run')
- cloudflared_test_process.stat.exists
- cloudflared_test_process.stat.pw_name == 'cloudflared'
quiet: true
# cloudflared_manage_dns is false in the converge: the tunnel was checked, no DNS call made.
- name: Read the requests the API stub received
delegate_to: localhost
ansible.builtin.slurp:
src: "{{ cloudflared_test_stub_dir }}/requests.log"
register: cloudflared_test_requests
- name: The converge checked the tunnel and made no DNS call
vars:
cloudflared_test_log: "{{ cloudflared_test_requests.content | b64decode }}"
ansible.builtin.assert:
that:
- >-
cloudflared_test_log is search('"GET", "path": "/client/v4/accounts/molecule-account/cfd_tunnel/'
~ cloudflared_test_tunnel_id ~ '"')
- cloudflared_test_log is not search('/zones')
quiet: true
# Every case fails, before any change or at a guard ahead of the first change; the last play
# checks that the daemon was left as the converge set it up.
- name: Verify the failure paths
hosts: all
gather_facts: false
tasks:
- name: Checksum config.yml and the binary before the failure cases
ansible.builtin.stat:
path: "{{ cloudflared_test_path }}"
checksum_algorithm: sha256
loop: [/etc/cloudflared/config.yml, /usr/local/bin/cloudflared]
loop_control:
loop_var: cloudflared_test_path
register: cloudflared_test_before
- name: Ask systemd about the daemon before the failure cases
ansible.builtin.systemd:
name: cloudflared
register: cloudflared_test_unit_before
- name: Run each case
ansible.builtin.include_tasks: tasks/failed_run.yml
loop:
- name: version-with-v
vars: {cloudflared_version: v2026.2.0}
expect: must be a release tag
- name: sha256-not-hex
vars: {cloudflared_sha256_amd64: not-a-hash}
expect: must be the 64-digit hex sha256
- name: ingress-without-service
vars: {cloudflared_ingress: [{hostname: app.example.test}]}
expect: each with hostname and service
- name: tunnel-not-minted
vars: {cloudflared_tunnel_id: ""}
expect: run the mint entry point first
- name: credentials-not-minted
vars: {cloudflared_credentials_json: ""}
expect: run the mint entry point first
- name: account-missing
vars: {cloudflared_account_id: ""}
expect: cloudflared_account_id and cloudflared_tunnel_api_token (vaulted) have no role default
- name: zone-missing
vars: {cloudflared_manage_dns: true}
expect: cloudflared_manage_dns is true, so cloudflared_zone_name
- name: tunnel-deleted
vars: {cloudflared_tunnel_id: 6f1a6e2c-0000-4000-8000-000000000002}
expect: no longer exists on Cloudflare
# Retried three times, 5 s apart, before the 404 is trusted.
- name: tunnel-unknown
vars: {cloudflared_tunnel_id: 6f1a6e2c-0000-4000-8000-00000000000f}
expect: (HTTP 404)
- name: zone-unknown
vars: {cloudflared_manage_dns: true, cloudflared_zone_name: missing.example.test}
expect: No Cloudflare zone found named missing.example.test
- name: record-owned-by-something-else
vars:
cloudflared_manage_dns: true
cloudflared_zone_name: example.test
cloudflared_ingress: [{hostname: taken.example.test, service: "http://127.0.0.1:8080"}]
expect: do not point at a Cloudflare Tunnel
# The configured hash is the installed binary's, so the version was bumped without it.
- name: stale-sha256
vars:
cloudflared_version: 2026.3.0
cloudflared_sha256_amd64: "{{ cloudflared_test_stub | replace('@VERSION@', '2026.2.0') | hash('sha256') }}"
expect: The hash is stale
- name: checksum-mismatch
vars: {cloudflared_version: 2026.3.0, cloudflared_sha256_amd64: "{{ 'f' * 64 }}"}
expect: cloudflared was not stopped and still runs 2026.2.0
loop_control:
loop_var: cloudflared_test_case
label: "{{ cloudflared_test_case.name }}"
- name: Checksum config.yml and the binary after the failure cases
ansible.builtin.stat:
path: "{{ cloudflared_test_path }}"
checksum_algorithm: sha256
loop: [/etc/cloudflared/config.yml, /usr/local/bin/cloudflared]
loop_control:
loop_var: cloudflared_test_path
register: cloudflared_test_after
- name: Stat the staged binary
ansible.builtin.stat:
path: /usr/local/bin/cloudflared.new
register: cloudflared_test_staged
- name: Ask systemd about the daemon after the failure cases
ansible.builtin.systemd:
name: cloudflared
register: cloudflared_test_unit_after
- name: The failures changed nothing and the daemon still runs
ansible.builtin.assert:
that:
- cloudflared_test_after.results | map(attribute='stat.checksum') | list == cloudflared_test_before.results | map(attribute='stat.checksum') | list
- not cloudflared_test_staged.stat.exists
- cloudflared_test_unit_after.status.ActiveState == 'active'
# not restarted, not even by the failed update
- cloudflared_test_unit_after.status.MainPID == cloudflared_test_unit_before.status.MainPID
quiet: true
# The mint entry point. The molecule job runs with CI variables set, so every mint that should
# get past the CI guard runs as a child process with them blanked (mint.yml).
- name: Verify the mint entry point
hosts: all
gather_facts: false
vars:
cloudflared_test_mint_inputs:
cloudflared_api_base_url: "{{ cloudflared_api_base_url }}"
cloudflared_account_id: molecule-account
cloudflared_tunnel_api_token: molecule-not-a-token
cloudflared_tunnel_name: molecule-tunnel
cloudflared_test_no_ci: {GITHUB_ACTIONS: "", GITEA_ACTIONS: "", CI: "", ANSIBLE_NOCOLOR: "1"}
tasks:
- name: Mint without confirmation
block:
- name: Include the mint entry point with cloudflared_mint_confirm unset
ansible.builtin.include_role:
name: mortis.kamino.cloudflared
tasks_from: mint
# Only reached when the include returned, so the guard did not fire. The message
# must not contain the guard's text, so the rescue below cannot mistake it for it.
- name: Fail because the include returned
ansible.builtin.fail:
msg: The include returned without the confirm guard firing
rescue:
- name: The confirm guard fired, and nothing else failed first
ansible.builtin.assert:
that:
- "'mint is opt-in' in ansible_failed_result.msg"
- "'cloudflared_mint_confirm=true' in ansible_failed_result.msg"
quiet: true
- name: Mint under each CI variable, run as a child process with only that one set
delegate_to: localhost
run_once: true
ansible.builtin.command:
argv:
- ansible-playbook
- -i
- localhost,
- "{{ playbook_dir }}/mint.yml"
- -e
- "{{ cloudflared_test_mint_inputs | to_json }}"
environment: "{{ cloudflared_test_no_ci | combine({item: 'true'}) }}"
loop: [GITHUB_ACTIONS, GITEA_ACTIONS, CI]
register: cloudflared_test_mint_ci
# The child is expected to fail (the CI guard fires). Its rc and output are asserted next.
failed_when: false
changed_when: false
# Ansible 2.19 prints task failures to stderr, so both streams are checked.
- name: The CI guard fired for every variable
ansible.builtin.assert:
that:
- item.rc != 0
- "'refuses to run under CI' in (item.stdout ~ item.stderr)"
- "'mint is opt-in' not in (item.stdout ~ item.stderr)"
quiet: true
loop: "{{ cloudflared_test_mint_ci.results }}"
loop_control:
label: "{{ item.item }}"
- name: Run the mint cases outside CI, each as a child process
delegate_to: localhost
run_once: true
ansible.builtin.command:
argv: >-
{{ ['ansible-playbook', '-i', 'localhost,', playbook_dir ~ '/mint.yml',
'-e', cloudflared_test_mint_inputs | combine(item.vars) | to_json]
+ item.args | default([]) }}
environment: "{{ cloudflared_test_no_ci }}"
loop:
# A tunnel that is already set is never replaced.
- {name: already-set, vars: {cloudflared_tunnel_id: "{{ cloudflared_test_tunnel_id }}"}}
- {name: account-missing, vars: {cloudflared_account_id: ""}}
# An empty id counts as missing; in check mode the inputs are asserted and nothing is created.
- {name: check-mode, vars: {cloudflared_tunnel_id: ""}, args: [--check]}
- {name: minted, vars: {cloudflared_test_expect_minted: true}}
loop_control:
label: "{{ item.name }}"
register: cloudflared_test_mint_cases
# Some children are expected to fail. Their rc and output are asserted next.
failed_when: false
changed_when: false
- name: Read the requests the API stub received
delegate_to: localhost
ansible.builtin.slurp:
src: "{{ cloudflared_test_stub_dir }}/requests.log"
register: cloudflared_test_requests
- name: Each mint case ended as expected, and only the last one created a tunnel
vars:
cloudflared_test_out: >-
{{ cloudflared_test_mint_cases.results | map(attribute='stdout')
| zip(cloudflared_test_mint_cases.results | map(attribute='stderr')) | map('join', ' ') | list }}
cloudflared_test_rc: "{{ cloudflared_test_mint_cases.results | map(attribute='rc') | list }}"
cloudflared_test_posts: >-
{{ cloudflared_test_requests.content | b64decode | split('\n')
| select('search', '"POST", "path": "/client/v4/accounts/molecule-account/cfd_tunnel"') | list }}
ansible.builtin.assert:
that:
- cloudflared_test_rc[0] == 0
- "'nothing to mint' in cloudflared_test_out[0]"
- cloudflared_test_rc[1] != 0
- "'must be set and non-empty to mint' in cloudflared_test_out[1]"
- cloudflared_test_rc[2] == 0
- "'nothing to mint' not in cloudflared_test_out[2]"
- cloudflared_test_rc[3] == 0
- cloudflared_test_posts | length == 1
- cloudflared_test_posts[0] is search('"status": 200')
fail_msg: "Return codes {{ cloudflared_test_rc }}, outputs: {{ cloudflared_test_out }}"
quiet: true
# The remove path. Last on purpose: it runs once, outside the idempotence step, and nothing runs
# after verify except molecule's cleanup. cloudflared_manage_dns stays false, so the removal
# deletes the tunnel through the API stub and makes no DNS call.
- name: Verify the remove path
hosts: all
gather_facts: false
tasks:
- name: Run the role with the remove flags
ansible.builtin.include_role:
name: mortis.kamino.cloudflared
vars:
cloudflared_remove: true
cloudflared_remove_data: true
- name: Stat what the removal deletes
ansible.builtin.stat:
path: "{{ cloudflared_test_path }}"
loop:
- /etc/systemd/system/cloudflared.service
- /usr/local/bin/cloudflared
- /etc/cloudflared
- /etc/systemd/system/multi-user.target.wants/cloudflared.service
loop_control:
loop_var: cloudflared_test_path
register: cloudflared_test_removed
- name: Look up the cloudflared user
ansible.builtin.getent:
database: passwd
key: cloudflared
fail_key: false
register: cloudflared_test_user
- name: Ask systemd whether the service is still active
ansible.builtin.systemd:
name: cloudflared
register: cloudflared_test_active
failed_when: false
- name: Read the requests the API stub received
delegate_to: localhost
ansible.builtin.slurp:
src: "{{ cloudflared_test_stub_dir }}/requests.log"
register: cloudflared_test_requests
- name: Everything is gone, nothing was recreated, and the tunnel was deleted on Cloudflare
ansible.builtin.assert:
that:
- cloudflared_test_removed.results | map(attribute='stat') | map(attribute='exists') | select | list | length == 0
# prereqs, which create the account, do not run after a removal
- cloudflared_test_user.ansible_facts.getent_passwd.cloudflared is none
# the module errors for a unit that no longer exists, which is also a pass
- (cloudflared_test_active.status | default({})).ActiveState | default('inactive') != 'active'
- >-
cloudflared_test_requests.content | b64decode is search('"DELETE", "path": "/client/v4/accounts/molecule-account/cfd_tunnel/'
~ cloudflared_test_tunnel_id ~ '", "status": 200')
quiet: true