Get attributes of a conditionally included resource

2 min read

To be able to conditionally include a given resource we can use the count argument but if we do so it is not as straightforward to use it's outputs (attributes) because now on this resource we have an array of outputs even thought we are confident that it will just have one if enabled. Let's take a deeper look on how to deal with this using the following conditional resource as an example:

resource "aws_route53_record" "ampa_public_r53_cname_record" {
  count   = try(length(var.public_alias_name)>0, false)?1:0
  zone_id = data.aws_route53_zone.public_r53_zone.zone_id
  name    = var.public_alias_name
  type    = "CNAME"

  records = [ aws_route53_record.ampa_web_public_r53_record.fqdn ]
  ttl     = "3600"
}

If we try to use it as follows:

locals {
  test = aws_route53_record.ampa_web_public_r53_cname_record.fqdn
}

We will get an error precisely complaining about the fact that it is an array so to be able to access it's data you must use an index:

Error: Missing resource instance key

  on .terraform/modules/terraform-ampa/locals.tf line 36, in locals:
  36:   test = aws_route53_record.ampa_web_public_r53_cname_record.fqdn

Because aws_route53_record.ampa_web_public_r53_cname_record has "count"
set, its attributes must be accessed on specific instances.

For example, to correlate with indices of a referring resource, use:
    aws_route53_record.ampa_web_public_r53_cname_record[count.index]

Since this resource won't ever have more than one element (count can only be either 0 or 1) we can use element() and force it's index to 0 as follows:

element(aws_route53_record.ampa_web_public_r53_cname_record.*.fqdn, 0)

Since we will be able to access this resource only when count is 1, we can wrap it using the try() function to make sure it won't fail with an error when such index is not available:

try(element(aws_route53_record.ampa_web_public_r53_cname_record.*.fqdn, 0), "")

Posted on 10/02/2021

Categories