In one of our our Terraform modules we have a variable to optionally create a load balancer. As part of this we create some subnets thusly:

resource "aws_subnet" "subnet_loadbalancer" {
  count = var.create_loadbalancer ? length(var.az_names) : 0
  vpc_id            = aws_vpc.vpc_main.id
  cidr_block        = var.lb_subnet_cidrs[count.index]
  availability_zone = var.az_names[count.index]

Now, if we are creating a loadbalancer I want to output the first subnet for later use in other modules:

output primary_LB_Subnet {
  value = aws_subnet.subnet_loadbalancer[0]

This is fine if we create the loadbalancer, but not if var.create_loadbalancer is false. In that case I get the following error:

Error: Invalid index

  on ..\..\modules\vpc\loadbalancer.tf line 19, in output "primary_LB_Subnet":
  19:   value = aws_subnet.subnet_loadbalancer[0]
    | aws_subnet.subnet_loadbalancer is empty tuple

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

I can see why this would be a problem, as we haven't create the subnets, so my immediate thought was to do something like:

output loadbalancer_sg_id {
  value = var.create_loadbalancer ? aws_subnet.subnet_loadbalancer[0] : null

But this doesn't help the issue and I still get the same issue. What is the correct way to address this within Terraform?

  • If at all possible, you should avoid this type of complex logic in terraform. Specifically for this reason ;)
    – thisguy123
    Commented Mar 22, 2020 at 16:55

1 Answer 1


Could you wrap the assignment to value using the try type conversion function?

output primary_LB_Subnet {
  value = try(aws_subnet.subnet_loadbalancer[0], null)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.