简体   繁体   中英

Terraform: How to create multiple aws subnets from one resource block?

I'm trying to create multiple subnets from one resource block and I get the following error

Error: aws_subnet.private: cidr_block must be a single value, not a list

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"]

You have to create multiple aws_subnet resources by utilitizing the count argument to create one resource for each entry in your var.private_subnet list:

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
}

This expands the single aws_subnet resource into two, each with slightly different values based on the enumeration of count when each resource block is evaluated by terraform.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM