Have a modules/network/testvpc and modules/network/subnet module configurations .
mainfolder/modules/network/testvpc/main.tf
variable "vpccidr" {type="list"}
variable "vpcname" {type="list"}
resource "aws_vpc" "customVpc" {
count = "${length(var.vpccidr)}"
cidr_block = "${element(var.vpccidr,count.index)}"
tags {
Name = "${element(var.vpcname,count.index)}"
}
mainfolder/modules/network/subnet/main.tf
variable "subcidr" {type="list"}
variable "subname" {type="list"}
resource "aws_subnet" "subnet" {
count = "${length(var.subcidr)}"
vpc_id = "${element(aws_vpc.customVpc.*.id, count.index)}"
cidr_block = "${element(var.subcidr, count.index)}"
tags {
Name = "${element(var.subname, count.index)}"
}
}
mainfolder/main.tf
module "testvpc" {
source = "./modules/network/testvpc"
vpccidr="${var.vpccidr}"
vpcname="${var.vpcname}"
}
module "subnet" {
source = "./modules/network/subnet"
subcidr = "${var.subcidr}"
subname = "${var.subname}"
}
mainfolder/var.tf
variable "vpccidr" {type="list"}
variable "vpcname" {type="list"}
variable "subcidr" {type="list"}
variable "subname" {type="list"}
mainfolder/terraform.tfvars
- vpccidr=["10.1.0.0/16","10.2.0.0/16","10.3.0.0/16"]
vpcname=["vpc-shared","vpc-sand","vpc-preprod"]
subcidr=["10.1.1.0/24","10.2.1.0/24","10.3.1.0/24"]
subname=["sub-shared","sub-sand","sub-preprod"]
-
While running terraform validate -var-file=terraform.tfvars getting the following error
Error: resource 'aws_subnet.subnet' config: unknown
resource 'data.aws_vpc.customVpc' referenced in variable
data.aws_vpc.customVpc.*.id
Is it because aws_subnet is not able to locate vpc_id since the resource aws_vpc is not created it . I am calling both the testvpc and subnet as modules in the mainfolder/main.tf . What am i missing .
Secondly is the loop in the aws_vpc and aws_subnet proper . It should create vpc-shared 10.1.0.0/16 and sub-shared within that vpc and so on