amazon-web-services - 用于 aws 安全组的 Terraform 中的变量值
问题描述
我是 terraform 的新手,正在尝试使用入口和出口规则创建 AWS 安全组。我没有对值进行硬编码并创建多个入口和出口块,而是尝试使用 terraformlookup
函数。
main.tf
文件如下所示:
provider "aws" {
version = "~> 2.0"
region = var.region
profile = var.profile
}
resource "aws_security_group" "this" {
name = "test-sg"
description = "test security group"
dynamic "ingress" {
for_each = var.ingress_rules
content {
description = lookup(ingress.value, "description", null)
from_port = lookup(ingress.value, "from_port", null)
to_port = lookup(ingress.value, "to_port", null)
protocol = lookup(ingress.value, "protocol", null)
cidr_blocks = lookup(ingress.value, "cidr_blocks", null)
}
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "test-sg"
}
}
variables.tf
文件看起来像这样
variable "ingress_rules" {
default = {
"description" = ["For HTTP", "For SSH"]
"from_port" = ["80", "22"]
"to_port" = ["80", "22"]
"protocol" = ["tcp", "tcp"]
"cidr_blocks" = ["0.0.0.0/0", "0.0.0.0/0"]
}
type = map(list(string))
description = "Security group rules"
}
运行terraform validate
时显示配置有效,但运行terraform plan
时显示以下错误:
ingress.value is list of string with 2 elements
Invalid value for "inputMap" parameter: lookup() requires a map as the first
argument.
仍然花了很长时间之后,我无法弄清楚如何解决这个错误。将查找值传递给variables.tf
文件的正确方法是什么?
解决方案
我将按如下方式实现它:
resource "aws_security_group" "test_security_group" {
name = "test-sg"
description = "test security group"
dynamic "ingress" {
for_each = var.sg_ingress_rules
content {
from_port = ingress.value.from_port
to_port = ingress.value.to_port
protocol = ingress.value.protocol
cidr_blocks = ingress.value.cidr_blocks
description = ingress.value.description
}
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "test security group"
}
}
变量.tf
variable "sg_ingress_rules" {
description = "Ingress security group rules"
type = map
}
my_vars.tfvars
sg_ingress_rules = {
"1" = {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
description = "HTTP"
},
"2" = {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["<my_private_ip>/32"]
description = "SSH"
}
}
希望对进一步理解有所帮助!
推荐阅读
- swagger-2.0 - 如何使用 OpenApi Generator 为 java 生成一些模型?
- javascript - Linkedin 返回未捕获的错误:JavaScript API 域仅限于
- r - 一次为数据框中的多列生成线性模型
- jquery - 如果所选日期在 Js 日历中有特定日期,则将所选日期更改为明天
- c# - 为集成测试创建 LocalDB 测试数据库
- sql - 从 Oracle 数据库中的两个表中查询
- regex - '\' 后面跟一个非转义字符有什么作用?
- xamarin - 编译错误尝试通过 Xamarin Android 绑定项目绑定 ABBYY RTR SDK.AAR 文件
- excel - 在 excel 中搜索部分匹配项
- reactjs - 预期的模拟函数已被调用但未被调用