In response to: https://xeiaso.net/blog/2025/yoke-k8s/

In the opening paragraphs there is a callout with the following message:

If you really do think that Terraform is code, then go try and make multiple DNS records for each random instance ID based on a dynamic number of instances. Correct me if I'm wrong, but I don't think you can do that in Terraform.

IMG_1995.jpeg

The following Terraform code demonstrates creating multiple DNS records based on a dynamic number of EC2 instances.

variable "instance_count" {
  description = "Number of EC2 instances"
  default     = 3
}

variable "domain_name" {
  description = "Domain name for the DNS records"
  default     = "example.com"
}

variable "hosted_zone_id" {
  description = "The Route 53 hosted zone ID"
}

resource "aws_instance" "web" {
  count         = var.instance_count
  ami           = "ami-0c55b159cbfafe1f0" # Replace with a valid AMI ID
  instance_type = "t2.micro"

  tags = {
    Name = "web-instance-${count.index}"
  }
}

resource "aws_route53_record" "web" {
  for_each = { for idx, instance in aws_instance.web : idx => instance }

  zone_id = var.hosted_zone_id
  name    = "web-${each.key}.${var.domain_name}"
  type    = "A"
  ttl     = 300
  records = [each.value.public_ip]
}

Which results in the following Terraform plan:

["create"] - aws_instance.web[0]
["create"] - aws_instance.web[1]
["create"] - aws_instance.web[2]
["create"] - aws_route53_record.web["0"]
["create"] - aws_route53_record.web["1"]
["create"] - aws_route53_record.web["2"]

If you feel I have misunderstood your meaning, please advise.