when conditional count evaluates to a whole number other than 0, code runs fine. but, when the count evaluates to 0, apply fails.
I see there was discussion of workarounds for this a few years ago by @apparentlymart , @jbardin , and @brikis98, ( "Referencing Attributes from Resources with count = 0" change in Terraform 0.11 should be a warning! · Issue #16726 · hashicorp/terraform · GitHub ) but now it seems that the workarounds are deprecated too. How is this supposed to be handled now?
THE ERRORS:
╷
│ Error: Invalid index
│
│ on network.tf line 72, in resource "aws_nat_gateway" "NAT":
│ 72: allocation_id = aws_eip.NATEIP[count.index].id
│ ├────────────────
│ │ aws_eip.NATEIP is empty tuple
│ │ count.index is 1
│
│ The given key does not identify an element in this collection value.
╵
╷
│ Error: Invalid index
│
│ on network.tf line 72, in resource "aws_nat_gateway" "NAT":
│ 72: allocation_id = aws_eip.NATEIP[count.index].id
│ ├────────────────
│ │ aws_eip.NATEIP is empty tuple
│ │ count.index is 0
│
│ The given key does not identify an element in this collection value: the collection has no elements.
╵
╷
│ Error: Invalid index
│
│ on network.tf line 79, in output "NatEip1":
│ 79: value = aws_eip.NATEIP[0].public_ip
│ ├────────────────
│ │ aws_eip.NATEIP is empty tuple
│
│ The given key does not identify an element in this collection value: the collection has no elements.
THE CODE:
resource "aws_eip" "NATEIP" {
provider = aws.region-main
count = var.RdsCreate ? 2 : 0
vpc = true
depends_on = [aws_internet_gateway.IGW]
}
resource "aws_nat_gateway" "NAT" {
provider = aws.region-main
allocation_id = aws_eip.NATEIP[count.index].id
count = length(aws_subnet.RdsSubnets)
subnet_id = aws_subnet.RdsSubnets[count.index].id #aws_subnet.Public.id
depends_on = [aws_internet_gateway.IGW, aws_eip.NATEIP]
}
output "NatEip1" {
value = aws_eip.NATEIP[0].public_ip
#value = "${element(concat(aws_eip.NATEIP.*.public_ip, tolist("")), 0)}"
}
output "NatEip2" {
value = aws_eip.NATEIP[1].public_ip
#value = "${element(concat(aws_eip.NATEIP.*.public_ip, tolist("")), 0)}"
}