我有这个资源来创建安全组,并有几个入口规则。
这些文件位于";安全组";文件夹,因为我必须为它创建一个模块。
Main.tf
resource "aws_security_group" "main" {
name = var.sg_name
dynamic "ingress" {
for_each = local.ingress_rules
content {
description = ingress.value.description
from_port = ingress.value.port
to_port = ingress.value.port
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
}
变量.tf
locals {
ingress_rules = [{
port = 443
description = "Port 443"
},
{
port = 80
description = "Port 80"
}]
}
现在,在模块/安全组/文件夹之外,我有一个主.tf文件,我想在其中调用该模块来创建安全组。
module "security_group" {
source = "./modules/security-group"
dynamic "ingress" {
for_each = local.ingress_rules
content {
description = ingress.value.description
from_port = ingress.value.port
to_port = ingress.value.port
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
}
│ Error: Unsupported block type
│
│ on main.tf line 29, in module "security_group":
│ 29: dynamic "ingress" {
│
│ Blocks of type "dynamic" are not expected here.
╵
否则,我如何调用此模块来创建规则和其他必要的东西?提前感谢
模块没有动态块。您必须将规则作为常规变量传递给模块,而不是本地值:
variable "ingress_rules" {
default = [{
from_port = 443
to_port = 443
description = "Port 443"
},
{
from_port = 80
to_port = 80
description = "Port 80"
}]
}
resource "aws_security_group" "main" {
name = var.sg_name
dynamic "ingress" {
for_each = var.ingress_rules
content {
description = ingress.value.description
from_port = ingress.value.from_port
to_port = ingress.value.to_port
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
}
然后在父文件夹中:
module "security_group" {
source = "./modules/security-group"
ingress_rules = [
{
description = "description"
from_port = 20
to_port = 20
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
]
}
您必须修复属性的所有名称。不能只混合port
和to_port
。