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?