2

Terraform cidrsubnets 为我提供了我想要的以下子网。

我正在使用的 Terraform 版本:Terraform v0.14.9

> cidrsubnets("172.16.0.0/18", 6, 6, 6, 6)
tolist([
  "172.16.0.0/24",
  "172.16.1.0/24",
  "172.16.2.0/24",
  "172.16.3.0/24",
])
Requirement
==========
Main CIDR range = 172.16.0.0/18
Public Subnets = [172.16.0.0/24, 172.16.1.0/24]
Private Subents = [172.16.2.0/24, 172.16.3.0/24]

如何使用 Terraform cidrsubnets函数将上述公共子网和私有子网的 CIDR 范围传递给下面的 VPC 模块。

variable "vpc_cidr" {
  default = "172.16.0.0/18"
}

data "aws_availability_zones" "azs" {
  state = "available"
}

module "vpc" {
  
  source  = "terraform-aws-modules/vpc/aws"
  version = "2.77.0"

  name                 = "my-vpc"
  cidr                 = var.vpc_cidr
  azs                  = data.aws_availability_zones.azs.names
  private_subnets      = ["172.16.1.0/24", "172.16.2.0/24"] <= I want to pass these subnets from cidrsubnets function
  public_subnets       = ["172.16.3.0/24", "172.16.4.0/24"] <= I want to pass these subnets from cidrsubnets function
  enable_nat_gateway   = true
  single_nat_gateway   = true
  enable_dns_hostnames = true

}


有人可以帮我解决这个问题吗?

4

1 回答 1

1

您可以在cidrsubnets之上使用slice功能。由于将返回一个列表,因此根据索引对其进行切片,您将获得 2 个包含公共和私有 IP 的列表:cidrsubnets

module "vpc" {
  ...
  private_subnets      = slice(cidrsubnets(var.vpc_cidr, 6, 6, 6, 6),0,2)
  public_subnets       = slice(cidrsubnets(var.vpc_cidr, 6, 6, 6, 6),2,4)
  ...
}

于 2021-05-03T06:41:29.460 回答