From eaa5d2f4ee6b43925e0833fb01276a5da40dd9f8 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Mon, 23 Nov 2026 14:55:59 +0000 Subject: [PATCH] fix(cloudflared): query DNS per hostname and validate config.yml first The overwrite guard listed the zone's first 100 records only, so a record further on went unseen. It now queries each ingress hostname by name and compares names case-insensitively, and the prune listing pages through result_info.total_pages. Query values are urlencoded. The template task validates config.yml with cloudflared before it replaces the file; the rendered content is unchanged. The API stub filters by name and pages to match. Assisted-by: Claude Code:claude-opus-5-5 --- .../default/files/cloudflare_api_stub.py | 38 +++++++--- roles/cloudflared/tasks/configure.yml | 75 +++++++++++++------ 2 files changed, 80 insertions(+), 33 deletions(-) diff --git a/roles/cloudflared/molecule/default/files/cloudflare_api_stub.py b/roles/cloudflared/molecule/default/files/cloudflare_api_stub.py index c4e1fbd..5136771 100644 --- a/roles/cloudflared/molecule/default/files/cloudflare_api_stub.py +++ b/roles/cloudflared/molecule/default/files/cloudflare_api_stub.py @@ -44,13 +44,14 @@ class Handler(BaseHTTPRequestHandler): state_dir = "." # Quiet: the requests go to requests.log instead of stderr. - def log_message(self, format, *args): + def log_message(self, *args): pass - def _send(self, status, result=None): - body = json.dumps( - {"success": status == 200, "errors": [], "result": result} - ).encode() + def _send(self, status, result=None, result_info=None): + reply = {"success": status == 200, "errors": [], "result": result} + if result_info is not None: + reply["result_info"] = result_info + body = json.dumps(reply).encode() self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) @@ -83,12 +84,7 @@ class Handler(BaseHTTPRequestHandler): 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) + return self._records(query) if self.command == "GET" and path == "/zones": zones = ( [{"id": ZONE_ID, "name": ZONE_NAME}] @@ -98,6 +94,26 @@ class Handler(BaseHTTPRequestHandler): return self._send(200, zones) return self._send(404) + # Filters by name (case-insensitive, as DNS names are), type and content, and pages. + def _records(self, query): + records = [ + r + for r in RECORDS + if ("name" not in query or r["name"].lower() == query["name"].lower()) + and all(r[k] == query[k] for k in ("type", "content") if k in query) + ] + per_page = int(query.get("per_page", "100")) + page = int(query.get("page", "1")) + total_pages = max(1, -(-len(records) // per_page)) + chunk = records[(page - 1) * per_page : page * per_page] + info = { + "page": page, + "per_page": per_page, + "total_count": len(records), + "total_pages": total_pages, + } + return self._send(200, chunk, info) + def _tunnel(self, tunnel_id): if tunnel_id is None and self.command == "POST": return self._create() diff --git a/roles/cloudflared/tasks/configure.yml b/roles/cloudflared/tasks/configure.yml index 6b15544..4478a4b 100644 --- a/roles/cloudflared/tasks/configure.yml +++ b/roles/cloudflared/tasks/configure.yml @@ -55,12 +55,16 @@ - name: Manage the tunnel's DNS records when: cloudflared_manage_dns | bool + vars: + __cloudflared_prune_url: >- + {{ cloudflared_api_base_url }}/zones/{{ __cloudflared_zone_lookup.json.result[0].id }}/dns_records?type=CNAME&content={{ + (cloudflared_tunnel_id ~ '.cfargotunnel.com') | urlencode }}&per_page=100 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 }}" + url: "{{ cloudflared_api_base_url }}/zones?name={{ cloudflared_zone_name | urlencode }}" method: GET headers: Authorization: "Bearer {{ cloudflared_tunnel_api_token }}" @@ -76,21 +80,24 @@ 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 + # One query per hostname, filtered by name and not by type, so an existing A or AAAA + # record at a hostname is caught too, however many records the zone holds. + - name: Look up the existing DNS records of each ingress hostname delegate_to: localhost become: false - vars: - __cloudflared_zone_dns_query: "per_page=100" + loop: "{{ cloudflared_ingress }}" + loop_control: + loop_var: __cloudflared_ingress_item + label: "{{ __cloudflared_ingress_item.hostname }}" ansible.builtin.uri: url: >- - {{ cloudflared_api_base_url }}/zones/{{ __cloudflared_zone_lookup.json.result[0].id }}/dns_records?{{ __cloudflared_zone_dns_query }} + {{ cloudflared_api_base_url }}/zones/{{ __cloudflared_zone_lookup.json.result[0].id }}/dns_records?name={{ + __cloudflared_ingress_item.hostname | lower | urlencode }}&per_page=100 method: GET headers: Authorization: "Bearer {{ cloudflared_tunnel_api_token }}" status_code: [200] - register: __cloudflared_zone_dns_records + register: __cloudflared_hostname_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. @@ -99,25 +106,28 @@ # 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. + # this role's own and is repointed. Names compare case-insensitively. - 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 }} + Existing DNS record(s) for {{ __cloudflared_hostname }} ({{ __cloudflared_existing_targets }}) do not point at a Cloudflare Tunnel. Verify manually and add - {{ __cloudflared_ingress_item.hostname }} to + {{ __cloudflared_hostname }} to cloudflared_allow_dns_overwrite to proceed if this is expected. loop: "{{ cloudflared_ingress }}" loop_control: loop_var: __cloudflared_ingress_item + index_var: __cloudflared_ingress_index 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 }}" + __cloudflared_hostname: "{{ __cloudflared_ingress_item.hostname | lower }}" + __cloudflared_existing_targets: >- + {{ __cloudflared_hostname_records.results[__cloudflared_ingress_index].json.result + | selectattr('name', 'match', '(?i)^' ~ (__cloudflared_hostname | regex_escape) ~ '$') + | map(attribute='content') | map('lower') | map('trim', '.') | list }} when: >- - __cloudflared_ingress_item.hostname not in cloudflared_allow_dns_overwrite and + __cloudflared_hostname not in (cloudflared_allow_dns_overwrite | map('lower') | list) and __cloudflared_existing_targets | length > 0 and __cloudflared_existing_targets | select('match', '^.*\.cfargotunnel\.com$') | list | length == 0 @@ -140,28 +150,45 @@ 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. + # CNAMEs of this tunnel, never records of other services or tunnels in the zone. Paged: + # the first page says how many there are, the rest are fetched below. - 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 }}" + url: "{{ __cloudflared_prune_url }}&page=1" method: GET headers: Authorization: "Bearer {{ cloudflared_tunnel_api_token }}" status_code: [200] - register: __cloudflared_existing_tunnel_records + register: __cloudflared_tunnel_records_first # 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: List the further pages of DNS records pointing at this tunnel + delegate_to: localhost + become: false + loop: "{{ range(2, (__cloudflared_tunnel_records_first.json.result_info.total_pages | default(1) | int) + 1) | list }}" + loop_control: + loop_var: __cloudflared_page + ansible.builtin.uri: + url: "{{ __cloudflared_prune_url }}&page={{ __cloudflared_page }}" + method: GET + headers: + Authorization: "Bearer {{ cloudflared_tunnel_api_token }}" + status_code: [200] + register: __cloudflared_tunnel_records_more + check_mode: false + 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: >- + {{ __cloudflared_tunnel_records_first.json.result + + (__cloudflared_tunnel_records_more.results | default([]) | map(attribute='json.result') | flatten(levels=1)) }} loop_control: loop_var: __cloudflared_dns_record_item label: "{{ __cloudflared_dns_record_item.name }}" @@ -171,7 +198,7 @@ type: CNAME api_token: "{{ cloudflared_tunnel_api_token }}" state: absent - when: __cloudflared_dns_record_item.name not in (cloudflared_ingress | map(attribute='hostname') | list) + when: __cloudflared_dns_record_item.name | lower not in (cloudflared_ingress | map(attribute='hostname') | map('lower') | list) # api_token is a module parameter and would show in the task's output. no_log: true @@ -182,8 +209,12 @@ owner: "{{ cloudflared_user }}" group: "{{ cloudflared_group }}" mode: "0640" + # A config cloudflared rejects is never written. + validate: "{{ cloudflared_install_dir }}/cloudflared tunnel --config %s ingress validate" notify: Restart cloudflared + # Also the only check of the existing config under --tags health, where the template above + # does not run. - name: Validate cloudflared ingress config ansible.builtin.command: argv: