--- # 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 | default(0) == 200 retries: 3 delay: 5 # Running out of retries fails the task whatever its status, and no_log would hide why: the # two tasks below fail instead, with the re-mint instructions for a 404. ignore_errors: true # noqa: ignore-errors # 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 | default(0) == 404 or ((__cloudflared_tunnel_lookup.json | default({})).result | default({})).deleted_at | default(None) is not none tags: [cloudflared, configure, health] - name: Fail if the tunnel lookup failed ansible.builtin.fail: msg: >- The Cloudflare tunnel lookup failed (HTTP {{ __cloudflared_tunnel_lookup.status | default('none') }}). Check cloudflared_api_base_url, cloudflared_account_id and that cloudflared_tunnel_api_token has the Cloudflare Tunnel permission. when: __cloudflared_tunnel_lookup is failed 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]