π Managing Cloudflare DNS with Terraform
ZONE_ID="" API_TOKEN=""tf vars file for token
cloudflare_api_token = "" cloudflare_zone_id = ""Using Azure Blob Storage for State Backend
terraform init -migrate-state export ARM_ACCESS_KEY="" This repository automates the management of Cloudflare DNS records using Terraform.It includes scripts to import existing DNS records, generate Terraform configurations, and apply changes efficiently.
π Directory Structure
π οΈ Setup Requirements
To use this Terraform setup for managing Cloudflare DNS, you need:1οΈβ£ Cloudflare API Token
Generate an API token with the following permissions:- Zone.Zone Read
- Zone.DNS Read & Write
- Go to Cloudflare Dashboard
- Navigate to My Profile > API Tokens
- Create a custom token with the above permissions
- Copy and save the token securely (youβll need it for Terraform)
2οΈβ£ Cloudflare Zone ID
Each Cloudflare domain (zone) has a unique Zone ID. π‘ How to find your Zone ID:- Go to Cloudflare Dashboard
- Select your domain
- Under Overview, find the Zone ID at the bottom of the page.
π Step-by-Step Usage
1οΈβ£ Configure Terraform Provider
Edit theprovider.tf file with your API token:
2οΈβ£ Generate Terraform Resource Blocks
Use thetf-gen.sh script to fetch existing Cloudflare DNS records and create Terraform configuration:
import.tf containing Terraform resource blocks for each DNS record.
3οΈβ£ Import Existing Cloudflare DNS Records
Run theimport.sh script to import existing records into Terraform state:
4οΈβ£ Apply Terraform Configuration
After importing, run Terraform to verify and apply changes:π Handling DNS Record Changes
- To add new records: Modify
main.tfand runterraform apply. - To update existing records: Change
main.tfand runterraform planto preview changes. - To remove records: Delete the record from
main.tfand runterraform apply.
π₯ Troubleshooting
π Terraform is trying to recreate existing records
Ifterraform plan shows it will recreate existing records, itβs likely because:
- The import was not done correctly
- The imported state differs from the generated Terraform code
import.sh before terraform plan.
π Example Terraform Configuration
A typical DNS record managed with Terraform looks like this:π― Next Steps
- Automate DNS updates using CI/CD
- Manage multiple Cloudflare accounts using workspaces
- Enhance security by using environment variables for sensitive data
π€ Author
Ahmad Raza - ahmadraza.inFor more guides, visit: docs.ahmadraza.in π
π What This README Covers
βοΈ Terraform setup for Cloudflare DNSβοΈ Generating Terraform configuration from existing records
βοΈ Importing existing DNS records into Terraform state
βοΈ Managing DNS records efficiently
βοΈ Troubleshooting common issues
