DEV Community

Govind
Govind

Posted on

3

Managing DNS with Namecheap, Cloudflare and Terraform: A Complete Guide

Managing DNS with Namecheap, Cloudflare and Terraform: A Complete Guide

Setting up your domain's DNS can be a tedious manual process, but with infrastructure as code tools like Terraform, you can automate these configurations and ensure consistency across environments. In this guide, we'll walk through how to:

  1. Transfer your Namecheap domain's DNS management to Cloudflare
  2. Set up Terraform to manage your Cloudflare DNS records
  3. Implement CI/CD with GitHub Actions to automate DNS updates

Prerequisites

  • A domain registered with Namecheap
  • A Cloudflare account
  • GitHub repository for your infrastructure code
  • Basic understanding of DNS concepts

Step 1: Setting Up Namecheap to Use Cloudflare's Nameservers

Before we can manage DNS records with Terraform, we need to point our Namecheap domain to Cloudflare's nameservers.

Adding Your Domain to Cloudflare

  1. Log in to your Cloudflare account
  2. Click "Add a Site" and enter your domain name (e.g., example.com)
  3. Select the Free plan (or another plan that suits your needs)
  4. Cloudflare will scan for existing DNS records - verify these records are correct
  5. Cloudflare will provide you with nameserver addresses (typically in the format ns1.cloudflare.com and ns2.cloudflare.com)

Updating Nameservers in Namecheap

  1. Log in to your Namecheap account
  2. Go to the "Domain List" and click "Manage" next to your domain
  3. Select the "Custom DNS" option under "Nameservers"
  4. Enter the Cloudflare nameservers provided during setup (usually 2 nameservers)
    • Example: ns1.cloudflare.com and ns2.cloudflare.com
  5. Save your changes

It may take 24-48 hours for the nameserver changes to propagate globally. You can verify the nameserver change using:

dig NS example.com
Enter fullscreen mode Exit fullscreen mode

Step 2: Managing DNS with Terraform

Now that Cloudflare is handling your DNS, we can use Terraform to manage the records.

Setting Up Terraform Configuration Files

Create the following files in your project directory:

main.tf

terraform {
  required_providers {
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "~> 5.0"
    }
  }
}

provider "cloudflare" {
  api_token = var.cloudflare_api_token
}

variable "cloudflare_api_token" {
  sensitive = true
}

variable "zone_id" {
  default = "abcdef1234567890abcdef1234567890" # Replace with your Cloudflare zone ID
}

variable "domain" {
  default = "example.com" # Replace with your domain
}
Enter fullscreen mode Exit fullscreen mode

dns.tf

# A record for the root domain
resource "cloudflare_dns_record" "a_root" {
  zone_id = var.zone_id
  name    = "@"
  type    = "A"
  content = "203.0.113.10" # Replace with your server IP
  ttl     = 1
  proxied = true
}

# A record for a subdomain
resource "cloudflare_dns_record" "app_server" {
  zone_id = var.zone_id
  name    = "app" 
  type    = "A"
  content = "203.0.113.20" # Replace with your server IP
  ttl     = 1
  proxied = false
}

# CNAME record example
resource "cloudflare_dns_record" "www" {
  zone_id = var.zone_id
  name    = "www"
  type    = "CNAME"
  content = "example.com"
  ttl     = 1
  proxied = true
}
Enter fullscreen mode Exit fullscreen mode

terraform.tfvars (Add this to .gitignore to keep secrets out of version control)

cloudflare_api_token = "your_cloudflare_api_token_here"
Enter fullscreen mode Exit fullscreen mode

.gitignore

.terraform/
*.tfstate
*.tfstate.*
.terraform.lock.hcl
terraform.tfvars
Enter fullscreen mode Exit fullscreen mode

Getting Your Cloudflare Zone ID and API Token

  1. Zone ID:

    • Log in to Cloudflare
    • Select your domain
    • The Zone ID is displayed on the right side of the overview page
  2. API Token:

    • In Cloudflare, go to "My Profile" > "API Tokens"
    • Create a token with "Edit zone DNS" template or custom permissions
    • Copy the generated token

Running Terraform Locally

Initialize and apply your Terraform configuration:

terraform init
terraform plan -var="cloudflare_api_token=your_token_here"
terraform apply -var="cloudflare_api_token=your_token_here"
Enter fullscreen mode Exit fullscreen mode

Step 3: Setting Up CI/CD with GitHub Actions

To automate DNS changes when you update your Terraform files, create a GitHub Actions workflow.

Create a file at .github/workflows/terraform.yml:

name: 'Terraform Apply'

on:
  push:
    paths:
      - '*.tf'
      - '*.tfvars'
    branches:
      - main
permissions:
  contents: read

jobs:
  terraform:
    runs-on: ubuntu-latest
    name: Terraform Apply
    environment: production
    defaults:
      run:
        shell: bash
    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v2

      - name: Terraform Init
        run: terraform init

      - name: Terraform Plan
        run: terraform plan -var="cloudflare_api_token=${{ secrets.CLOUDFLARE_API_TOKEN }}"

      - name: Terraform Apply
        run: terraform apply -var="cloudflare_api_token=${{ secrets.CLOUDFLARE_API_TOKEN }}" --auto-approve --input=false

      - name: Terraform Output
        run: terraform output
Enter fullscreen mode Exit fullscreen mode

Setting Up GitHub Secrets

  1. In your GitHub repository, go to "Settings" > "Secrets and variables" > "Actions"
  2. Add a new repository secret with the name CLOUDFLARE_API_TOKEN and your Cloudflare API token as the value

Now, whenever you push changes to your Terraform files on the main branch, GitHub Actions will automatically apply those changes to your Cloudflare DNS configuration.

Verifying Your Setup

After everything is set up, you can verify that your DNS records are correctly configured:

dig example.com
dig app.example.com
Enter fullscreen mode Exit fullscreen mode

You can also check the Cloudflare dashboard to see the records that have been created.

Best Practices

  1. Use Terraform State Backend: Consider using a remote backend like AWS S3 or Terraform Cloud to store your state files.
  2. Version Control: Keep all your Terraform code in version control.
  3. Multiple Environments: Consider using workspaces or separate directories for different environments.
  4. Test Changes: Use terraform plan to review changes before applying them.

Conclusion

By combining Namecheap, Cloudflare, and Terraform with GitHub Actions, you've created a robust, automated system for managing DNS records. This approach allows you to:

  • Version control your DNS configuration
  • Automate changes to reduce human error
  • Track changes over time
  • Easily replicate configurations across environments

This infrastructure-as-code approach brings the reliability and reproducibility of modern DevOps practices to your domain management workflow.

Dynatrace image

Frictionless debugging for developers

Debugging in production doesn't have to be a nightmare.

Dynatrace reimagines the developer experience with runtime debugging, native OpenTelemetry support, and IDE integration allowing developers to stay in the flow and focus on building instead of fixing.

Learn more

Top comments (0)

Dev Diairies image

User Feedback & The Pivot That Saved The Project

🔥 Check out Episode 3 of Dev Diairies, following a successful Hackathon project turned startup.

Watch full video 🎥