我正在尝试为列表输入变量的映射实现for_each。
输出应该是为AZ us-east-1a(3个子网)和us-east-1b(2个子网)创建的子网列表。
需要以下帮助:
MAIN.TF
resource "aws_vpc" "name" {
cidr_block = "192.168.0.0/16"
}
resource "aws_subnet" "name" {
for_each = var.subnetcidr
vpc_id = aws_vpc.name.id
availability_zone = each.key
cidr_block = toset(each.value) //need help here
}
TFVARS文件
subnetcidr = {
"us-east-1a" = ["192.168.1.0/24","192.168.2.0/24","192.168.0.0/24"]
"us-east-1b" = ["192.168.3.0/24","192.168.4.0/24"]
}
错误:
Error: Incorrect attribute value type
on main.tf line 28, in resource "aws_subnet" "name":
28: cidr_block = toset(each.value)
|----------------
| each.value is tuple with 2 elements
Inappropriate value for attribute "cidr_block": string required.
任何帮助将不胜感激。 TIA!
答案 0 :(得分:0)
错误似乎很明显:
Inappropriate value for attribute "cidr_block": string required
不确定为什么要传递列表...
resource "aws_vpc" "name" {
cidr_block = "192.168.0.0/16"
}
resource "aws_subnet" "name" {
for_each = var.subnetcidr
vpc_id = aws_vpc.name.id
availability_zone = each.key
cidr_block = element(each.value, 0)
}
subnetcidr
变量,请输入类似以下内容:subnetcidr = {
"192.168.0.0/24" = "us-east-1a"
"192.168.1.0/24" = "us-east-1a"
"192.168.2.0/24" = "us-east-1a"
"192.168.3.0/24" = "us-east-1b"
"192.168.4.0/24" = "us-east-1b"
}
您现在可以看到,唯一的cidr块是键,区域是值。
然后在您的代码中,我们这样做:
resource "aws_vpc" "name" {
cidr_block = "192.168.0.0/16"
}
resource "aws_subnet" "name" {
for_each = var.subnetcidr
vpc_id = aws_vpc.name.id
availability_zone = each.value
cidr_block = each.key
}
答案 1 :(得分:0)
我终于能够解决这个问题。下面是方法。
资源“ aws_vpc”“名称” {
cidr_block =“ 10.0.0.0/16”
}
资源“ aws_subnet”“名称” {
vpc_id = aws_vpc.name.id
for_each =转置(var.subnet)
availability_zone = each.value [0]
cidr_block = each.key
}
可变子网{}
子网= {
“ us-east-1a” = [“ 10.0.0.0/20”,“ 10.0.16.0/20”,“ 10.0.32.0/20”]
“ us-east-1b” = [“ 10.0.64.0/20”,“ 10.0.80.0/20”]
“ us-east-1d” = [“ 10.0.112.0/20”,“ 10.0.128.0/20”,“ 10.0.144.0/20”,“ 10.0.96.0/20”]
}