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

人盡茶涼 提交于 2019-12-19 12:00:32

问题


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

回答1:


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.




回答2:


private_subnet is a list, so you should pick a single element, e.g.

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



来源:https://stackoverflow.com/questions/51196693/terraform-how-to-create-multiple-aws-subnets-from-one-resource-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!