Terraform:如何从一个资源块创建多个AWS子网?

时间:2018-07-05 17:05:22

标签: amazon-web-services terraform

我正在尝试从一个资源块创建多个子网,但出现以下错误

  

错误:aws_subnet.private:cidr_block必须是单个值,而不是列表

main.tf

resource "aws_subnet" "private" {
  vpc_id                  = "${aws_vpc.vpcname.id}"
  cidr_block              = "${var.private_subnet}"
  availability_zone       = "${data.aws_availability_zones.available.names[count.index]}"
  map_public_ip_on_launch = false

  tags {
    Name        = "${var.private}"
    Environment = "${terraform.workspace}"
  }
}

variable.tf

variable "private_subnet" {
  type    = "list"
  default = []
}

dev.tfvars

private_subnet = ["10.0.2.0/24", "10.0.3.0/24"]

2 个答案:

答案 0 :(得分:3)

您必须通过利用aws_subnet参数为count列表中的每个条目创建一个资源来创建多个var.private_subnet资源:

resource "aws_subnet" "private" {
  count                   = "${length(var.private_subnet)}"
  vpc_id                  = "${aws_vpc.vpcname.id}"
  cidr_block              = "${var.private_subnet[count.index]}"
  availability_zone       = "${data.aws_availability_zones.available.names[count.index]}"
  map_public_ip_on_launch = false
}

这会将单个aws_subnet资源扩展为两个,当每个资源块通过terraform求值时,基于count的枚举,每个资源的值会略有不同。

答案 1 :(得分:1)

private_subnet是一个列表,因此您应该选择一个元素,例如

cidr_block = "${element(var.private_subnet,count.index)}"