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
Check out my YouTube video for this article
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
Prerequisite:
Build AWS network via Terraform modules:
Below is our directory structure for the code in git repo
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 = "${aws_vpc.terraform_vpc.id}"
}
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 main.tf 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 step
terraform {
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 https://github.com/devops4solutions/terraform-example-aws.git
cd 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.