Mca*_*r49 6 loops dynamic amazon-web-services terraform
我正在尝试配置此 Terraform,以便添加新的 SG 入口规则所需要做的就是向文件添加一个块.tfvars,并且新的入口规则将添加到单个 SG 中。
我有一个.tfvars如下所示的文件:
rules = [
{
protocol = "tcp"
port = 22
cidr = ["10.0.0.0/8"],
},
{
protocol = "tcp"
port = 80
cidr = ["10.0.0.0/8"]
},
{
protocol = "tcp"
port = 443
cidr = ["10.0.0.0/8"]
},
{
protocol = "icmp"
port = -1
cidr = ["10.0.0.0/8"]
}
]
Run Code Online (Sandbox Code Playgroud)
我的地形是:
variable "rules" {
type = list(object({
protocol = string
port = number
cidr = list(string)
}))
description = "Specify the protocol, port range, and CIDRs."
}
resource "aws_security_group" "this" {
...
dynamic "ingress" {
for_each = { for rule in var.rules : rule.id => rule }
content {
from_port = var.rules.port
to_port = var.rules.port
protocol = var.rules.protocol
cidr_blocks = var.rules.cidr
}
}
...
Run Code Online (Sandbox Code Playgroud)
我尝试遍历上面的内容,也尝试使用 using for_each = var.rules,但我只是收到以下错误(以下每个错误都会发生):
protocol = var.rules.protocol
from_port = var.rules.port
to_port = var.rules.port
cidr_blocks = var.rules.cidr
-----------------------------
var.rules is list of object with 4 elements.
This value does not have any attributes.`
Run Code Online (Sandbox Code Playgroud)
我有点困惑,不知道还能尝试什么,所以有人有什么想法吗?
这里有几个问题。第一个是在您的for_each元参数值for表达式 lambda 中,您试图访问不存在的对象键id。另外,您可以轻松地list(object)在此处使用 a 而不是像map(object)您在转换中尝试执行的那样,然后可以直接使用您的输入变量。我们可以丢弃这些并相应地修复该值:
for_each = var.rules
Run Code Online (Sandbox Code Playgroud)
第二个问题是动态块中的临时 lambda 迭代器变量是块本身的名称。在本例中,您的块名为ingress。因此,我们需要从其对象键访问值:
content {
from_port = ingress.value.port
to_port = ingress.value.port
protocol = ingress.value.protocol
cidr_blocks = ingress.value.cidr
}
Run Code Online (Sandbox Code Playgroud)
结合这些修复,我们得出:
dynamic "ingress" {
for_each = var.rules
content {
from_port = ingress.value.port
to_port = ingress.value.port
protocol = ingress.value.protocol
cidr_blocks = ingress.value.cidr
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11651 次 |
| 最近记录: |