Tal
Tal

Reputation: 11

terraform - passing vpc_id parameter from different VPC's to several subnets

I'm new to terraform and trying the following:

  1. I created 3 aws VPC's:

#VPC creation

enter codresource "aws_vpc" "new_vpc" {
 cidr_block = var.new_vpc[count.index]
 count = 3
 tags = {
 Name = var.vpc_name[count.index]
 count = 3

} }

  1. The variables.tf is as following:

#varibales for the vpc #=======================

variable "new_vpc" {
    type = list
   }

variable "vpc_name" {
  type = list
}
  1. the terraform.tfvars is :

    new_vpc=["10.0.0.0/16" , "10.0.0.0/17" , "10.0.0.0/18"]
    vpc_name=["DEV_VPC" , "UAT_VPC" , "PROD_VPC" ]
    

all the VPC's created successfully

the next step is to create 3 subnets and each subnet need to be assign to a different VPC.

in oder to create a subnet the following paramaters are required : vpc_id + cidr_block

need your advice for the required vpc_id parameter - how to pass each subnet different vpc_id (as i mentioned above 3 vpc's created)

10x a lot

Upvotes: 1

Views: 687

Answers (1)

Johnny9
Johnny9

Reputation: 496

Since you used count to create vpc you can also use count to create subnets.

resource "aws_subnet" "You_subnet_name" {
  count = 3
  vpc_id = aws_vpc.new_vpc[count.index].id
}

You don't need to specify the cidr, the vpc id is enough. You need however to specify the cidr_block part to alocate ip range for your subnet. If you want to use all the ip space in the vpc for 1 subnet you can simply do:

resource "aws_subnet" "You_subnet_name" {
  count = 3
  vpc_id = aws_vpc.new_vpc[count.index].id
  cidr_block = aws_vpc.new_vpc[count.index].cidr_block
}

Upvotes: 1

Related Questions