johnny3210
johnny3210

Reputation: 61

How to use for_each and count in the same terraform resource

I'm trying to pass in 2 IP addresses within the destination_cidr_block. I used a for_each line to allow this to pass but the count is causing issues. How do you write the resource block to get this to work with both?

    resource "aws_ec2_transit_gateway_route" "services_to_location" {
  for_each =  local.subnet_ids

  provider = aws.network_account
  count = var.connect_to_on_prem_vpn ? 1 : 0
  destination_cidr_block         = each.key
  transit_gateway_attachment_id  = data.aws_ec2_transit_gateway_vpn_attachment.test_vpn.id
  transit_gateway_route_table_id = aws_ec2_transit_gateway_route_table.test_vpc.id
}

main.tf file looks like this :

locals {
  subnet_ids = toset([
    "10.12.40.144/32",
    "215.11.22.123/32",
  ])
}

Variable.tf

variable "connect_to_on_prem_vpn" {
  type = bool
  default = true
}

Upvotes: 1

Views: 1668

Answers (1)

jordanm
jordanm

Reputation: 34914

The issue you are having is due to the mixing of for_each and count. If you supply for_each with an empty set, it will create 0 resource, just like count = 0 would. You can leverage this to use your bool with something like this:

locals {
  subnet_ids = var.connect_to_on_prem_vpn ? toset([
    "10.12.40.144/32",
    "215.11.22.123/32",
  ]) : toset([])
}

resource "aws_ec2_transit_gateway_route" "services_to_location" {
  for_each =  local.subnet_ids

  provider = aws.network_account
  destination_cidr_block         = each.key
  transit_gateway_attachment_id  = data.aws_ec2_transit_gateway_vpn_attachment.test_vpn.id
  transit_gateway_route_table_id = aws_ec2_transit_gateway_route_table.test_vpc.id
}

Upvotes: 5

Related Questions