When terraform requires an IP address but what you have is a DNS name

I needed to expose for a bit an ElastiCache via a Network load balancer. To do so at a point in time you need to create a aws_lb_target_group_attachment. In such cases the target_id needs to be an IP address.

resource "aws_lb_target_group_attachment" "redis" {
  target_group_arn = aws_lb_target_group.redis.arn
  target_id        = aws_elasticache_replication_group.redis.primary_endpoint_address
}

Now the primary_endpoint_address is a DNS name and not an IP, and what’s more, you cannot get by by thinking, OK it is a hostname, but eventually it will resolve into an IP to be used, no it expects an IP address. So we have to have a level of indirection here to figure it out. dns_a_record_set to the rescue:

data "dns_a_record_set" "redis" {
  host = aws_elasticache_replication_group.redis.primary_endpoint_address
}

However, keep in mind that dns_a_record_set returns a list and not a single record, so it still cannot be used, even if the query returns a single record. And you end up with something like this:

resource "aws_lb_target_group_attachment" "redis" {
  target_group_arn = aws_lb_target_group.redis.arn
  target_id        = data.dns_a_record_set.redis.addrs[0]
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s