[英]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.我试图在 destination_cidr_block 中传递 2 个 IP 地址。 I used a for_each line to allow this to pass but the count is causing issues.
我使用了 for_each 行来允许它通过,但计数导致了问题。 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: main.tf 文件如下所示:
locals {
subnet_ids = toset([
"10.12.40.144/32",
"215.11.22.123/32",
])
}
Variable.tf变量.tf
variable "connect_to_on_prem_vpn" {
type = bool
default = true
}
The issue you are having is due to the mixing of for_each
and count
.您遇到的问题是由于
for_each
和count
的混合。 If you supply for_each
with an empty set, it will create 0 resource, just like count = 0
would.如果您为
for_each
提供一个空集,它将创建 0 个资源,就像count = 0
一样。 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.