Wayneio
Wayneio

Reputation: 3566

Create Terraform Output When Count Enabled

I am trying to create an outputs.tf for a resource in Terraform which has count set. When count is 1, all works fine, however when count is 0, it does not:

If I create the output like this

output "ec2_instance_id" {
  value = aws_instance.ec2_instance.id
}

It errors

because aws_instance.ec2_instance has "count" set, its attributes must be accessed on specific instances.

However, changing it to

output "ec2_instance_id" {
  value = aws_instance.ec2_instance[0].id
}

works for a count of 1, but when count is 0 gives

aws_instance.ec2_instance is empty tuple

The given key does not identify an element in this collection value.

Therefore I saw this post and tried

output "ec2_instance_id" {
  value = aws_instance.ec2_instance[count.index].id
}

but that gives

The "count" object can be used only in "resource" and "data" blocks, and only when the "count" argument is set.

What is the correct syntax?

Upvotes: 9

Views: 10752

Answers (1)

Ngenator
Ngenator

Reputation: 11259

As long as you only care about 1 or 0 instances, you can access the whole list can use the splat expression aws_instance.ec2_instance[*].id with the join function and an empty string, which results in the ID or an empty string depending on whether the resource was created or not.

output "ec2_instance_id" {
  value = join("", aws_instance.ec2_instance[*].id)
}

Example:

variable "thing1" {
  default = [
    { id = "one" }
  ]
}

variable "thing2" {
  default = []
}

output "thing1" {
  value = join("", var.thing1[*].id)
}

output "thing2" {
  value = join("", var.thing2[*].id)
}

Results in

➜ terraform apply

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

thing1 = one
thing2 =

Upvotes: 9

Related Questions