Correct way to handle 'optional' array of resources in Terraform 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?
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)
}