I’m working with Terraform to deploy my infrastructure on DigitalOcean, and I want to automate the creation of DNS records for each Droplet I set up.
Is there a way to have Terraform automatically add an A record for each Droplet’s IP address in my DigitalOcean domain zone? Ideally, I’d like the DNS records to be created or updated whenever I apply changes.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Accepted Answer
Hey there! 👋
Setting up DNS records with Terraform on DigitalOcean is super straightforward and can save you a lot of time.
If you just want a basic setup, you can manage your domain and add an A record to point to your Droplet’s IP without needing any extra configurations.
Here’s an example:
# Create the domain in DigitalOcean
resource "digitalocean_domain" "example" {
name = "example.com" # Replace with your domain name
}
# Add an A record for www.example.com
resource "digitalocean_record" "www" {
domain = digitalocean_domain.example.id
type = "A"
name = "www" # This makes www.example.com
value = "192.168.0.11" # Replace with your Droplet's IP
}
This will create a domain (example.com
) and set up an A record for www.example.com
to point to your Droplet’s IP address. Once it’s applied, your DNS will be good to go!
If you want the A record to automatically use your Droplet’s IP address, you can reference the Droplet’s IP in the value
field.
Just replace the IP with your Droplet’s ipv4_address
like this:
resource "digitalocean_droplet" "my_droplet" {
name = "example-droplet"
region = "nyc3"
size = "s-1vcpu-1gb"
image = "ubuntu-22-04-x64"
}
resource "digitalocean_record" "www" {
domain = digitalocean_domain.example.id
type = "A"
name = "www"
value = digitalocean_droplet.my_droplet.ipv4_address # Auto-updates with Droplet IP
}
Here are a couple of resources to help you out:
Let me know if this helps!
If you’re new to Terraform, I would also suggest this Terraform ebook here.
- Bobby
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.