Reusable infrastructure with Terraform Modules

Check my YouTube video for this article

For more articles, please follow my website

As development, staging and production environment are isolated from each other, so does the terraform code required to. In order to built a re-usable terraform code for both staging and production environment, without conducting copy and paste, one must follow the modules strategy. In this blog we will learn how to create Reusable infrastructure with Terraform Modules

Terraform modules:

Think of them just like functions in a programming language, which we define once and then call them by passing parameters from anywhere in the code. Just like functions, put the infrastructure code inside a Terraform module and then reuse it in multiple places throughout the code.

Thus, both our staging and production environment (which are almost identical) can use the same modules without the requirement to copy and paste.

Let’s build a very basic and simple AWS network, comprising of a VPC and subnet


  1. Install Terraform and configure AWS secret keys
  2. Clone this git repo

Build AWS network via Terraform modules:

Below is our directory structure for the code in git repo

Image for post
Image for post

Create VPC

resource "aws_vpc" "terraform_vpc" { 
cidr_block = var.vpc-fullcidr
#### this 2 true values are for use the internal vpc dns resolution
enable_dns_support = true
enable_dns_hostnames = true
tags = {
Name = "terraform_vpc"

Declare output variables for vpc_id

output "vpc_id" {
value = "${}"

Create subnet

Here we are first declaring the variable vpc_id and then using the value

variable vpc_id {}resource "aws_subnet" "PublicAZA" {
vpc_id = var.vpc_id
cidr_block = var.Subnet-Public-AzA-CIDR
tags = {
Name = "PublicSubnetAZA"


How to call the modules from the file

provider "aws" {
region = var.region
module "vpc" {source = "./modules/vpc"}module "subnet" {
source = "./modules/subnets"
vpc_id = "${module.vpc.vpc_id}"

# this is how you refer the bucket and dynamobdb which you have created in the previous stepterraform {backend "s3" {
bucket = "terraform-remote-state-devops4solutions-bucket-s3"
dynamodb_table = "terraform-state-lock-dynamo-devops4solutions"
region = "us-east-2"
key = "terraform.tfstate"

Now run the below command

git clone vpc-subnet-example
terraform init
terraform plan
terraform apply

Check your AWS console, to see the successful creation of VPC, subnet.

Congratulation, you have successfully learnt how to create a reusable infrastructure using terraform modules.

Devops Automation Enginneer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store