Using Ansible to Automate Cloudflare DNS Changes
Ansible has a module that makes it easy to automate Cloudflare DNS changes. This tutorial shows you an example of how to use Ansible to create a TXT record using Cloudflare’s API token authentication method.
Step 1: Create a Cloudflare API Token
The first thing we need to do is login to the Cloudflare Dashboard and create a new API Token that has permissions to Edit DNS records.
Go to: https://dash.cloudflare.com/profile/api-tokens then click Create Token.

Click Use template next the Edit zone DNS option.

Scroll down to Zone Resources and select the domain you want the API Token to be able to edit. You can also choose what client IP addresses are allowed to use the Token so you can restrict access to your office. After you’ve done that click Continue to summary.

Click Create Token.

The final screen shows your API Token. Click Copy then store it in a safe place. Do not show this token to anyone or they will be able to modify your DNS records.

Now that you’ve created an API Token, we will use it in the next step while creating the playbook.
Step 2: Create Ansible Playbook
Create a file called create-txt-record.yml
and add the following contents.
---
- hosts: localhost
gather_facts: no
vars:
domain: "yourdomain.com"
token: "yourapitoken"
tasks:
- name: create TXT record
cloudflare_dns:
api_token: "{{ token }}"
domain: "{{ domain }}"
record: "test"
type: "TXT"
value: "Hello World"
Replace the domain
and token
variables with your domain and the token generated in the first step.
Step 3: Run Ansible Playbook
Run the playbook with the following command.
ansible-playbook create-txt-record.yml

Step 4: Test TXT Record
Test to see if the TXT record was created with the following command (replace yourdomain.com with your domain).
dig -t txt test.yourdomain.com +short
The output should say Hello World.

And you should be able to see the record in the Cloudflare Dashboard.

How to Delete the TXT Record
You can delete the TXT record by adding the state: absent
option. Here is an example playbook which I’ve called delete-txt-record.yml
.
---
- hosts: localhost
gather_facts: no
vars:
domain: "yourdomain.com"
token: "yourapitoken"
tasks:
- name: create TXT record
cloudflare_dns:
api_token: "{{ token }}"
domain: "{{ domain }}"
record: "test"
type: "TXT"
state: absent
After running the playbook with ansible-playbook delete-txt-record.yml
, the dig command we ran in step 4 should return nothing.
Conclusion
In this tutorial, we used Ansible and the Cloudflare module to automate the creation and deletion of TXT records. We used Cloudflare’s API token authentication method because you can use the principle of least privilege to make accessing the account more secure.