A simple 'dynamic dns'-client with Ansible and Cloudflare

  • April 20, 2019

My ISP does not give me a static IP. It doesn’t change often, but in the rare case that it has changed I never discover it before I actually need it.

So. I wanted a very simple way of auto-updating the home.example.com record. I didn’t want to bother with a thirdparty client from something like dyndns (and I didn’t want to pay for anything).

As I use Cloudflare as dns service for all domains I own I could just use their API and solve it with a oneliner, but doing it with Ansible is more readable

---
- hosts: localhost

  connection: local

  vars:
  - cf_zone: 'example.com'
    cf_record: 'home'
    cf_email: 'email-for-cloudflare-login'
    cf_api_token: 'your-api-token-from-cloudflare'
  
  tasks:
  - name: Get current public IP address
    uri:
      url: 'https://ipinfo.io/ip'
      return_content: yes
    register: public_ip

  - name: Update DNS record
    cloudflare_dns:
      zone: '{{ cf_zone }}'
      record: '{{ cf_record }}'
      type: A
      value: '{{ public_ip.content | trim }}'
      state: present
      account_email: '{{ cf_email }}'
      account_api_token: '{{ cf_api_token }}'

  - name: Create Cron job
    cron:
      name: Update DNS record
      minute: '15'
      job: '/path/to/ansible/playbook.yml'