我是Terraform的新手。 我正在尝试创建一个代码,在其中可以循环创建子网,但是cidrsubnet功能无法正常工作,因为我不想更改子网掩码。 例如:我要创建具有以下IP的子网:子网1:10.90.46.0/27,子网2:10.90.46.32/27子网3:10.90.46.64/27,依此类推,直到子网8:10.90.46.224/27 谢谢
答案 0 :(得分:1)
应用计数,这将使资源数量成倍增加。
variable "vpc_id" {
default = "vpc-123"
}
#Here add all your 8 CIDR's to the list in "subnet_cidr" and for each one add one entry in "subnet_azs". You can repeat values in "subnet_azs" but not in subnet_cidr"
variable "subnet_cidr" {
default = ["10.90.46.0/27", "10.90.46.32/27", "10.90.46.64/27", "10.90.46.224/27"]
}
variable "subnet_azs" {
default = ["us-east-1a", "us-east-1b", "us-east-1c", "us-east-1c"]
}
resource "aws_subnet" "my_subnets" {
count = 8
vpc_id = "${var.vpc_id}"
cidr_block = "${element(var.subnet_cidr, count.index)}"
availability_zone = "${element(var.subnet_azs, count.index)}"
}
答案 1 :(得分:0)
自动分配IP地址范围序列的一种方法是使用Terraform Registry中的the hashicorp/subnets/cidr
module:
module "subnet_addrs" {
source = "hashicorp/subnets/cidr"
version = "1.0.0"
base_cidr_block = "10.90.46.0/24"
networks = [
{ name = "us-east-1a", new_bits = 3 },
{ name = "us-east-1b", new_bits = 3 },
{ name = "us-east-1c", new_bits = 3 },
{ name = "us-east-1d", new_bits = 3 },
{ name = "us-east-1e", new_bits = 3 },
{ name = "us-east-1f", new_bits = 3 },
{ name = "us-east-1g", new_bits = 3 },
{ name = "us-east-1h", new_bits = 3 },
]
}
在上面的示例中,module.subnet_addrs.network_cidr_blocks
将是这样的地图:
{
"us-east-1a" = "10.90.46.0/27"
"us-east-1b" = "10.90.46.32/27"
"us-east-1c" = "10.90.46.64/27"
"us-east-1d" = "10.90.46.96/27"
"us-east-1e" = "10.90.46.128/27"
"us-east-1f" = "10.90.46.160/27"
"us-east-1g" = "10.90.46.192/27"
"us-east-1h" = "10.90.46.224/27"
}
这样的映射可以直接用作资源的for_each
,因此我们可以使用AWS的示例声明这样的子网(因为您没有说出您使用的是哪个云供应商) :
resource "aws_subnet" "my_subnets" {
for_each = module.subnet_addrs.network_cidr_blocks
vpc_id = var.vpc_id
availability_zone = each.key
cidr_block = each.value
}
此模块的自述文件中有一些有关[如果您打算rename or renumber networks later要记住的事项”的指导,以确保所做的更改与已存在的对象兼容。我建议您在采用此方法之前先查看该文档,以确保将来可以对您将来可能想到的网络拓扑进行任何更改。
例如,上例中的分配已经覆盖了整个寻址空间"10.90.46.0/24"
,因此,如果您以后想添加一个新子网而不引入任何新的寻址空间,则需要替换其中的一个具有一对替换子网的现有子网,它们都具有new_bits = 4
,因此前缀长度为/28
而不是/27
,因此您将有一个额外的位数可用于网络编号。 / p>