我正在尝试将公共子网和私有子网定义为 Terraform 的输入变量vpc
模块。如何在迭代语句中引用我的私有/公共子网变量,而不是在“list[x]”元素中进行硬编码?
我有在中定义的 vpc 模块(目前只有两个 AZ)main.tf
。
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
name = "my-vpc"
cidr = var.my_cidr
azs = ["eu-west-1a", "eu-west-1b"]
private_subnets = [var.my_private_subnets[0], var.my_private_subnets[1]]
public_subnets = [var.my_public_subnets[0], var.my_public_subnets[1]]
# ^
# +--- can these subnets be iterated over in a for_each here?
...
}
我的子网输入变量定义如下:
variable "my_cidr" {
description = "The IPv4 CIDR block for the VPC"
type = string
default = "10.10.0.0/16"
}
variable "my_private_subnets" {
type = list
description = "private subnet within vpc cidr block"
default = ["10.10.20.0/24", "10.10.30.0/24"]
}
variable "my_public_subnets" {
type = list
description = "public subnet within vpc cidr block"
default = ["10.10.100.0/24", "10.10.200.0/24"]
}
答案1
首先将变量类型更新为列表(字符串)
variable "my_private_subnets" {
type = list(string)
description = "private subnets within vpc cidr block"
default = ["10.10.20.0/24", "10.10.30.0/24"]
}
variable "my_public_subnets" {
type = list(string)
description = "public subnets within vpc cidr block"
default = ["10.10.20.0/24", "10.10.30.0/24"]
}
然后将这些作为变量传递给模块,如下所示:
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
name = "my-vpc"
cidr = "10.6.0.0/16"
azs = ["eu-west-1a", "eu-west-1b"]
private_subnets = var.my_private_subnets
public_subnets = var.my_public_subnets
}