Terraform – Looping Through Nested Objects To Find EC2 Instance Private_IPs Then Create Route53 Records

I’m trying to understand not only how to filter and sort a nested object variable to create Route 53 records, but I’m also wanting to have terraform lookup the Private_IPs of the running instances to then be used in the route53 record creation. Below is an example of the code I’m trying to use as a shell.

provider "aws" {
  region = "us-east-2"
}

variable "dns-records" {
  type = set(object({
    dns       = string
    instances = set(string)
  }))
  default = [
    {
      dns       = "web.example.com"
      instances = ["i-ins1", "i-ins2", "i-ins3"]
    },
    {
      dns       = "web1.example.com"
      instances = ["i-ins1"]
    },
    {
      dns       = "web2.example.com"
      instances = ["i-ins2"]
    },
    {
      dns       = "web3.example.com"
      instances = ["i-ins3"]
    },
    {
      dns       = "web1-2.example.com"
      instances = ["i-ins1", "i-ins2"]
    }
  ]
}

data "aws_instance" "example" {
  ???
}

locals {
  ???
}

resource "aws_route53_record" "dns_records" {
  for_each = ???
  zone_id  = "ZID"
  name     = ???
  type     = "A"
  ttl      = 300
  records  = ???
}

The closest working example I’ve been able to come to is below, but I’ve had to give up the lookup of the aws_instance private_ips and just hard code them in the variables.

provider "aws" {
  region = "us-east-2"
}

variable "dns-records" {
  type = map(set(string))
  default = {
    "web.example.com"    = ["1.2.3.4", "2.3.4.5", "3.4.5.6"]
    "web1.example.com"   = ["1.2.3.4"]
    "web2.example.com"   = ["2.3.4.5"]
    "web3.example.com"   = ["3.4.5.6"]
    "web1-2.example.com" = ["1.2.3.4", "2.3.4.5"]
  }
}

resource "aws_route53_record" "dns_records" {
  for_each = var.dns-records

  zone_id = "ZID..."
  name    = each.key
  type    = "A"

  ttl = 300

  records = each.value
}

Leave a Comment