使用变量输入从locals.tf创建资源



我有一长串ACL规则,正试图通过迭代它们来生成aws_network_ACL。规则在我的模块中的locals.tf文件中,以使main.tf更整洁,看起来像这个

locals.tf

locals {
webapp = [{
"protocol"  = "tcp"
"rule_no"   = 100
"action"    = "allow"
"from_port" = 22
"to_port"   = 22
},
{
"protocol"  = "tcp"
"rule_no"   = 110
"action"    = "allow"
"from_port" = 60111
"to_port"   = 60111
},
{
"protocol"  = "tcp"
"rule_no"   = 120
"action"    = "allow"
"from_port" = 3243
"to_port"   = 3243
},
{
"protocol"  = "tcp"
"rule_no"   = 130
"action"    = "allow"
"from_port" = 6379
"to_port"   = 6379
},
{
"protocol"  = "tcp"
"rule_no"   = 140
"action"    = "allow"
"from_port" = 50123
"to_port"   = 50123
},
{
"protocol"  = "tcp"
"rule_no"   = 150
"action"    = "allow"
"from_port" = 50432
"to_port"   = 50432
},
{
"protocol"  = "tcp"
"rule_no"   = 160
"action"    = "allow"
"from_port" = 3306
"to_port"   = 3306
},
{
"protocol"  = "tcp"
"rule_no"   = 170
"action"    = "allow"
"from_port" = 50001
"to_port"   = 50001
},
{
"protocol"  = "tcp"
"rule_no"   = 180
"action"    = "allow"
"from_port" = 50010
"to_port"   = 50015
},
{
"protocol"  = "tcp"
"rule_no"   = 190
"action"    = "allow"
"from_port" = 50650
"to_port"   = 50660
}
]
}

(还有更多,但为了简洁起见缩短了。

在我的模块的main.tf中,我想对每个模块进行迭代,创建一个ACL

resource "aws_network_acl" "webapp" {
vpc_id = data.aws_vpc.posttrade-vpc.id
for_each = {for idx, query in locals.posttrade: idx => query}
egress = [
protocol = each.value.protocol
rule_no = each.value.rule_no
action = "allow"
from_port = each.value.from_port
to_port = each.value.to_port
]
}

但是得到错误

Missing item separator: Expected a comma to mark the beginning of the next item.

是否可以从本地文件或变量映射中执行此操作?

您缺少一个用于创建多个出口的动态块。你只需要添加代码:

resource "aws_network_acl" "webapp" {
vpc_id = data.aws_vpc.posttrade-vpc.id
dynamic "egress" {
for_each = toset(local.webapp)
content {
protocol  = egress.value["protocol"]
rule_no   = egress.value["rule_no"]
action    = "allow"
from_port = egress.value["from_port"]
to_port   = egress.value["to_port"]
}
}
}

这将导致:

Terraform will perform the following actions:
# aws_network_acl.webapp will be created
+ resource "aws_network_acl" "webapp" {
+ arn        = (known after apply)
+ egress     = [
+ {
+ action          = "allow"
+ cidr_block      = ""
+ from_port       = 22
+ icmp_code       = null
+ icmp_type       = null
+ ipv6_cidr_block = ""
+ protocol        = "tcp"
+ rule_no         = 100
+ to_port         = 22
},
+ {
+ action          = "allow"
+ cidr_block      = ""
+ from_port       = 3243
+ icmp_code       = null
+ icmp_type       = null
+ ipv6_cidr_block = ""
+ protocol        = "tcp"
+ rule_no         = 120
+ to_port         = 3243
},
......

最新更新