22 - Creating DNS Records
Working Code:
terraform/exercise-22-creating-dns-records/
The Problem: Manually creating DNS records in a web UI is repetitive and error-prone (duplicates, CNAMEs pointing to themselves).
The Solution: Use Terraform to manage DNS as code with validation to catch errors.
Objective
Create:
workhorse.g02...(A Record) → 1.2.3.4www.g02...(CNAME) →workhorsemail.g02...(CNAME) →workhorse- Validation to prevent duplicates
How-to
1. Variables with Validation
hcl
variable "server_aliases" {
default = ["www", "mail"]
validation {
condition = length(distinct(var.server_aliases)) == length(var.server_aliases)
error_message = "Duplicate server alias names found."
}
}2. Multiple Records with for_each
hcl
resource "dns_cname_record" "aliases" {
for_each = toset(var.server_aliases)
zone = "sdi.hdm-stuttgart.cloud."
name = each.value
cname = "workhorse.g02.sdi.hdm-stuttgart.cloud."
}Troubleshooting
"Missing Resource State": DNS server accepted the request but didn't return confirmation. Fix by importing manually:
bash
terraform import 'dns_cname_record.aliases["www"]' 'g02.sdi.hdm-stuttgart.cloud./www'Verify records resolved correctly:
bash
dig +noall +answer @ns1.hdm-stuttgart.cloud g2.sdi.hdm-stuttgart.cloud
dig +noall +answer @ns1.hdm-stuttgart.cloud workhorse.g2.sdi.hdm-stuttgart.cloud
dig +noall +answer @ns1.hdm-stuttgart.cloud www.g2.sdi.hdm-stuttgart.cloud
dig +noall +answer @ns1.hdm-stuttgart.cloud mail.g2.sdi.hdm-stuttgart.cloud