使用Terraform在AWS上的多个VPC上创建多个子网

时间:2018-10-11 10:14:11

标签: amazon-web-services terraform vpc

我想创建一个可创建许多VPC的terraform脚本。然后,我希望我的脚本在所有VPC中创建“ n”个子网。我想在一个子网资源块中这样做。我可以使用资源块内的count创建VPC,但无法与子网一起使用。请帮忙。

1 个答案:

答案 0 :(得分:1)

在Terraform中没有直接针对您的需求的此类规定,但是我们可以调整数量以满足您的需求。 首先,创建一个资源块,该资源块创建一定数量的VPC。

resource "aws_vpc" "main" {
  count = "${var.vpc_count}"
  cidr_block           = "${element(var.cidr_prefix, count.index)}.0.0/16"
  enable_dns_support   = "true"
  enable_dns_hostnames = "true"

  tags {
    Name = "${var.vpc_name}${count.index}"
  }
}

您也可以通过将值传递到variables.tf文件或.tfvars文件中来使用插值进行计数。

现在使用此脚本在所有VPC中创建“计数”数量的子网,并在所有可用区域中平均分配。

resource "aws_subnet" "private_subnet" {
  count = "${var.subnet_count * var.vpc_count}"
  vpc_id            = "${element(aws_vpc.main.*.id, count.index % var.vpc_count)}"
  cidr_block        = "${element(var.cidr_prefix, count.index)}.${count.index}.0/24"
  availability_zone = "${element(data.aws_availability_zones.all.names, count.index)}"

  tags {
    Name = "${var.vpc_name}-${element(var.availability_zone, count.index)}-${count.index}"
  }
}

您可以单独将VPC Cidr块定义为列表,将子网CIDR块定义为列表。尽管我使用了CIDR前缀并使用count来配置子网的CIDR块的值。

看看变量cidr_prefix。

variable "cidr_prefix"{
  type = "list"
  description = "The first 16 bits of the desired cidr block/s. Note: The number of elements in the list should not be less than the specified count of VPCs."
  default = ["172.16", "10.0", "143.14", "100.10"]
}