My terraform module structure looks like this.
├───dev
│ dev.auto.tfvars
│ main.tf
│ output.tf
│ variables.tf
│
└───modules
├───instances
│ main.tf
│ output.tf
│ variables.tf
│ versions.tf
│
└───networking
main.tf
output.tf
variables.tf
versions.tf
My learning objective is to add aws_vpc,aws_subnet under networking module. networking (main.tf)
resource "aws_vpc" "vpc" {
cidr_block = var.cidr_block
instance_tenancy = "default"
enable_dns_hostnames = var.enable_dns_hostnames
enable_dns_support = var.enable_dns_support
}
resource "aws_subnet" "private_subnets" {
cidr_block = var.private_subnets
vpc_id = aws_vpc.vpc.id
availability_zone = var.az
}
resource "aws_subnet" "public_subnets" {
cidr_block = var.public_subnets
vpc_id = aws_vpc.vpc.id
availability_zone = var.az
}
I'm referring this from my dev(main.tf)
module "vpc_subnets" {
source = "../modules/networking"
cidr_block = var.vpc_cidr_block
enable_dns_hostnames = true
enable_dns_support = true
az = var.az
}
But I can't understand how to refer/call to resource "aws_subnet" "private_subnets" and resource "aws_subnet" "public_subnets" in my dev (main.tf) .
CodePudding user response:
Your module has to output values that you want to use in your dev (main.tf)
. For example:
resource "aws_vpc" "vpc" {
cidr_block = var.cidr_block
instance_tenancy = "default"
enable_dns_hostnames = var.enable_dns_hostnames
enable_dns_support = var.enable_dns_support
}
resource "aws_subnet" "private_subnets" {
cidr_block = var.private_subnets
vpc_id = aws_vpc.vpc.id
availability_zone = var.az
}
resource "aws_subnet" "public_subnets" {
cidr_block = var.public_subnets
vpc_id = aws_vpc.vpc.id
availability_zone = var.az
}
output "public_subnets" {
value = aws_subnet.public_subnets
}
output "private_subnets" {
value = aws_subnet.private_subnets
}
then in your dev (main.tf)
your refer to them as
module "vpc_subnets" {
source = "../modules/networking"
cidr_block = var.vpc_cidr_block
enable_dns_hostnames = true
enable_dns_support = true
az = var.az
}
# for example:
locals {
my_public_subnet_id = module.vpc_subnets.public_subnets.id
my_private_subnet_id = module.vpc_subnets.private_subnets.id
}