Using try() for a resource that may or may not be counted

I’ve used try() a little bit and I assumed this would work:

output "emr-notebook-cluster-arn" {
  value = try(aws_emr_cluster.notebook-cluster.arn, aws_emr_cluster.notebook-cluster[0].arn)

However, I get this on plan:

│ Error: Missing resource instance key
│   on line 2, in output "emr-notebook-cluster-arn":
│    2:   value = try(aws_emr_cluster.notebook-cluster.arn, aws_emr_cluster.notebook-cluster[0].arn)
│ Because aws_emr_cluster.notebook-cluster has "count" set, its attributes
│ must be accessed on specific instances.
│ For example, to correlate with indices of a referring resource, use:
│     aws_emr_cluster.notebook-cluster[count.index]

Isn’t try() supposed to suppress that error and move on to the next arg? I’m using terraform 1.1.4

Hi @grimm26,

The key part of the documentation here is:

The try function can only catch and handle dynamic errors resulting from access to data that isn’t known until runtime. It will not catch errors relating to expressions that can be proven to be invalid for any input, such as a malformed resource reference.

If the expression is invalid, it can never get to the point of evaluating the try function. It’s always statically known whether resources use count or for_each, so expressions referencing those resources must match their configuration.

1 Like

gotcha. Looks like I should just do value = one(aws_emr_cluster.notebook-cluster[*].arn)