Terraform module - output variable as input for another module

Mahesh picture Mahesh · Sep 25, 2020 · Viewed 10.6k times · Source

I am new to terraform and trying to build an infrastructure with two subnets and VPC. I have created two modules

  • VPC
  • subnet

The VPC module will create a VPC and will return vpc_id as output, the same return vpc_id I am trying to use in the subnet module, but when I run the terraform plan, it asks me for the enter vpc_id input.

I want the vpc_id from the output value of the VPC module, can anyone please help me on the same.

Below is the code,

root tf file,

 provider "aws" {
  shared_credentials_file = var.shared_cred
  profile                 = "default" 
  region                  = var.aws_region
}

module "vpc" {
  source = "./vpc"
  name   = "terraformVPC"
  cidr   = "10.50.40.0/27"
}

module "private_subnet" {
  source      = "./subnet"
  subnet_name = "private_subnet"
  subnet_cidr = "10.50.40.16/28"
  #VPC_id = aws_vpc.moduleVPC.id
  VPCid = module.vpc.outvpc_id # this is the issue
}

module "public_subnet" {
  source      = "./subnet"
  subnet_name = "public_subnet"
  subnet_cidr = "10.50.40.0/28"
  VPCid      = module.vpc.outvpc_id
}

Subnet resource

resource "aws_subnet" "module_subnet" {
  cidr_block = var.subnet_cidr
  vpc_id     = var.VPCid

  tags = {
    Name = var.subnet_name
  }
}

Subnet module variable declaration

variable "subnet_name" {
  description = " define th subnet name"
}

variable "subnet_cidr" {
  description = "define th subnet cidr block"
}

variable "VPCid" {
  description = "Assign VPC id to subnet"
}

VPC output

output "outvpc_id" {
  value = "${aws_vpc.moduleVPC.id}"
}

Answer

Amir Mehler picture Amir Mehler · Dec 31, 2020

This is called "Module Composition". The important thing to remember is that you reference outputs of another module.

The format is: module.<object-name>.<output-name>

module "network" {
  source = "./modules/aws-network"

  base_cidr_block = "10.0.0.0/8"
}

module "consul_cluster" {
  source = "./modules/aws-consul-cluster"

  vpc_id     = module.network.vpc_id       # < output of module.network
  subnet_ids = module.network.subnet_ids   # < output of module.network
}