AWS Terraform - 在资源上使用动态块
Posted
技术标签:
【中文标题】AWS Terraform - 在资源上使用动态块【英文标题】:AWS Terraform - using dynamic block on resource 【发布时间】:2021-07-25 19:16:31 【问题描述】:我正在尝试使用动态块为 AWS 安全组编写 Terraform 模块,但出现此错误:
│
│ on main.tf line 17, in module "security_group":
│ 17: ingress =
│
│ The argument "ingress" was already set at main.tf:8,5-12. Each argument may be set only once.
我已按照文档进行操作,但仍然出现错误 我正在使用 Terraform 0.15.1 和 AWS 提供商版本 3.38.0
这是我的代码
./modules/security_group/main.tf
resource "aws_security_group" "main"
.......
dynamic "ingress"
for_each = var.ingress
content
description = ingress.value["description"]
from_port = ingress.value["from_port"]
to_port = ingress.value["to_port"]
protocol = ingress.value["protocol"]
cidr_blocks = ingress.value["cidr_blocks"]
ipv6_cidr_blocks = ingress.value["ipv6_cidr_blocks"]
.......
./modules/security_group/variables.tf
variable "ingress"
description = ""
type = object(
description = string
from_port = number
to_port = number
protocol = string
cidr_blocks = list(string)
ipv6_cidr_blocks = list(string)
)
default =
description = ""
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = []
ipv6_cidr_blocks = []
./main.tf
module "security_group"
source = "./modules/security_group"
name = "$var.project-sg"
description = "security group testing"
vpc_id = "my-vpc"
ingress =
description = ""
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = []
ipv6_cidr_blocks = []
ingress =
description = ""
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = []
ipv6_cidr_blocks = []
【问题讨论】:
【参考方案1】:你有ingress
参数。我想你想要一个作为列表:
variable "ingress"
description = ""
type = list(object(
description = string
from_port = number
to_port = number
protocol = string
cidr_blocks = list(string)
ipv6_cidr_blocks = list(string)
))
default = [
description = ""
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = []
ipv6_cidr_blocks = []
]
module "security_group"
source = "./modules/security_group"
name = "$var.project-sg"
description = "security group testing"
vpc_id = "my-vpc"
ingress = [
description = ""
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = []
ipv6_cidr_blocks = []
,
description = ""
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = []
ipv6_cidr_blocks = []
]
【讨论】:
以上是关于AWS Terraform - 在资源上使用动态块的主要内容,如果未能解决你的问题,请参考以下文章
Terraform:如何在单个资源块中提供多个 lambda 函数 zip 文件