Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 577
Wayneio Avatar asked Dec 17 '19 13:12

Wayneio


People also ask

Can you use count in output Terraform?

count is a meta-argument defined by the Terraform language. It can be used with modules and with every resource type. The count meta-argument accepts a whole number, and creates that many instances of the resource or module.

How do you set a count argument in Terraform?

How to use Terraform Count. We use count to deploy multiple resources. The count meta-argument generates numerous resources of a module. You use the count argument within the block and assign a whole number (could by variable or expression), and Terraform generates the number of resources.

How do you pass output value in Terraform?

Terraform Output Command To get the raw value without quotes, use the -raw flag. To get the JSON-formatted output, we can use the -json flag. This is quite useful when we want to pass the outputs to other tools for automation since JSON is way easier to handle programmatically.


1 Answers

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 =
like image 76
Ngenator Avatar answered Oct 23 '22 12:10

Ngenator