有没有办法使用cidr range在Terraform中使用Terraform创建多个子网

时间:2019-12-11 16:37:47

标签: amazon-web-services terraform terraform-provider-aws

我有2个前端和后端子网,当前我将子网范围作为变量传递,但是有什么方法可以通过terraform来选择VPC中的自由cidr范围?

1 个答案:

答案 0 :(得分:0)

Hashicorp有一个可用于帮助子网CIDR https://registry.terraform.io/modules/hashicorp/subnets/cidr/1.0.0

的模块
module "subnet_addrs" {
  source = "hashicorp/subnets/cidr"

  base_cidr_block = "10.0.0.0/8"
  networks = [
    {
      name     = "foo"
      new_bits = 8
    },
    {
      name     = "bar"
      new_bits = 8
    },
    {
      name     = "baz"
      new_bits = 4
    },
    {
      name     = "beep"
      new_bits = 8
    },
    {
      name     = "boop"
      new_bits = 8
    },
  ]
}

将为network_cidr_blocks输出值

{
  foo  = "10.0.0.0/16"
  bar  = "10.1.0.0/16"
  baz  = "10.16.0.0/12"
  beep = "10.32.0.0/16"
  boop = "10.33.0.0/16"
}

您也可以使用一些内置函数cidrsubnetscidrsubnet从VPC CIDR自己计算它

https://www.terraform.io/docs/configuration/functions/cidrsubnets.html

> cidrsubnets("10.0.0.0/8", 8, 8, 4, 8, 8)
[
  "10.0.0.0/16",
  "10.1.0.0/16",
  "10.16.0.0/12",
  "10.32.0.0/16",
  "10.33.0.0/16",
]