I am facing a problem in Terraform. I am trying to provision VPC's and Subnets using pre-defined CIDR ranges in my variables file. Below is the code snippet from the variables file i.e variables.tf
variable "vpc-fullcidr" {
description = "VPC CIDR range"
type = "list"
default = ["10.0.0.0/16", "192.168.0.0/16"]
}
variable "subnet-cidr" {
description = "Subnet CIDR range"
type = "list"
default = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24", "192.168.0.0/24",
"192.168.1.0/24", "192.168.2.0/24"]
}
variable "vpc-count" {
description = "Number of VPC to create"
type = "string"
default = "2"
}
variable "subnet-count"
{
description = "Number of Subnets to create"
default = "6"
}
Below is my VPC Template. VPC's are getting provisioned without any issues:-
resource "aws_vpc" "VPCPrimary" {
count = "${var.vpc-count}"
cidr_block = "${element(var.vpc-fullcidr, count.index)}"
#### Below DNS values are for the internal vpc dns resolution
enable_dns_support = true
enable_dns_hostnames = true
tags {
Name = "${element(var.VPCNameTag, count.index)}"
}
}
When I am trying to create Subnets it is failing. Below is my Subnets template :-
resource "aws_subnet" "PrivateSubnets" {
count = "${var.subnet-count}"
vpc_id = "${element(aws_vpc.VPCPrimary.*.id, count.index)}"
availability_zone = "${var.primaryaz}"
cidr_block = "${element(var.subnet-cidr, count.index)}"
tags {
Name = "Private Subnet ${count.index + 1}"
}
}
Terraform Error log :-
Error: Error applying plan:
2 error(s) occurred:
* aws_subnet.PrivateSubnets[4]: 1 error(s) occurred:
* aws_subnet.PrivateSubnets.4: Error creating subnet: InvalidSubnet.Range:
The CIDR '192.168.1.0/24' is invalid.
status code: 400, request id: 1a9136e6-8631-43cb-99a6-ccd2522854d4
* aws_subnet.PrivateSubnets[1]: 1 error(s) occurred:
* aws_subnet.PrivateSubnets.1: Error creating subnet: InvalidSubnet.Range:
The CIDR '10.0.2.0/24' is invalid.
status code: 400, request id: 1b0e4cf5-2e1d-402e-a89d-f08d8ac694e1
I am trying to provision the infrastructure in an automated way where the variables.tf file is getting populated dynamically using user inputs in the .NET front end using stored procedures. This issue is when I am trying to create multiple VPC's along with multiple subnets. Is there any way in which I can map the Subnet CIDR block with VPC CIDR block in the terraform resource "aws_subnet".