Skip to main content

Command Palette

Search for a command to run...

Building and Testing Your First Terraform Module on AWS: A Hands-On Guide for Beginners

Published
7 min read
Building and Testing Your First Terraform Module on AWS: A Hands-On Guide for Beginners

Introduction

This hands-on lab is designed to guide you through the process of building and testing a basic Terraform module from scratch on AWS. Terraform modules allow you to organize, simplify, and reuse your infrastructure-as-code by abstracting repeated configurations into modular components. Instead of rewriting the same code for every project, you can create a module once and reuse it across multiple environments — saving time and reducing errors.

In this lab, you’ll learn how to:

  • Set up your environment with Terraform and the AWS CLI.

  • Create a Terraform module that provisions a VPC, subnet, and retrieves the latest Amazon Linux 2 AMI.

  • Use that module in your main Terraform configuration to deploy an EC2 instance inside the VPC.

  • Test, validate, and deploy the infrastructure, then clean it up using Terraform commands.

By the end of this lab, you’ll have a solid understanding of how Terraform modules work, how to structure your Terraform project, and how to deploy AWS infrastructure efficiently using reusable code.

This is an essential step for anyone looking to master Infrastructure as Code (IaC) and streamline cloud deployments in real-world environments.

Terraform modules are a good way to abstract out repeated chunks of code, making them reusable across other Terraform projects and configurations. In this hands-on lab, we'll be writing a basic Terraform module from scratch and then testing it out.

Prerequisite

  • Ensure you have AWS CLI installed on your Linux VM

  • You can use the command - sudo snap install aws-cli --classic To download the aws cli

Also, Run aws configure to authenticate, generate your access key and secret key from the cli console

Ensure you have installed Terraform on your Linux VM as well.

Solution

Create the Directory Structure for the Terraform Project

  • Check the Terraform status using the version command:

Run - terraform version

Run - aws —version To check your aws cli version.

  • Since the Terraform version is returned, you have validated that the Terraform binary is installed and functioning properly.
    Note: If you receive a notification that there is a newer version of Terraform available, you can ignore it

  • Create a new directory called terraform_project to house your Terraform code:

Run - mkdir terraform_project

  • Switch to this main project directory:

Run - cd terraform_project

  • Create a custom directory called modules and a directory inside it called vpc:

Run - mkdir -p modules/vpc

  • Switch to the VPC directory using the absolute path:

Run - cd /home/cloud_user/terraform_project/modules/vpc/

Write Your Terraform VPC Module Code

Once we are already inside the VPC directory, then we will now write our Terraform VPC Module Code, we will have to first create a main.tf file using the command "vim main.tf ", then input these codes in the main.tf file

  • Using Vim, create a new file called main.tf:

Run - vim main.tf

  • In the file, insert and review the provided code:

provider "aws" {

region = var.region

}

resource "aws_vpc" "this" {

cidr_block = "10.0.0.0/16"

}

resource "aws_subnet" "this" {

vpc_id = aws_vpc.this.id

cidr_block = "10.0.1.0/24"

}

data "aws_ssm_parameter" "this" {

name = "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2"

}

After entering the codes in there,

  • Press Escape and enter :wq to save and exit the file.

  • Create a new file called variables.tf:

    Run - vim variables.tf

  • In the file, insert and review the provided code:

variable "region" {

type = string

default = "us-east-1"

}

  • Press Escape and enter :wq to save and exit the file.

  • Create a new file called outputs.tf:

Run - vim outputs.tf

  • In the file, insert and review the provided code:

output "subnet_id" {

value = aws_subnet.this.id

}

output "ami_id" {

value = data.aws_ssm_parameter.this.value

}

  • Note: The code in outputs.tf is critical to exporting values to your main Terraform code, where you'll be referencing this module. Specifically, it returns the subnet and AMI IDs for your EC2 instance.

  • Press Escape and enter :wq to save and exit the file.

Write Your Main Terraform Project Code

  • Switch to the main project directory:

Run - cd ~/terraform_project

  • Create a new file called main.tf:

Run - vim main.tf

  • In the file, insert and review the provided code:

variable "main_region" {

type = string

default = "us-east-1"

}

provider "aws" {

region = var.main_region

}

module "vpc" {

source = "./modules/vpc"

region = var.main_region

}

resource "aws_instance" "my-instance" {

ami = module.vpc.ami_id

subnet_id = module.vpc.subnet_id

instance_type = "t2.micro"

}

  • Note: The code in main.tf invokes the VPC module that you created earlier. Notice how you're referencing the code using the source option within the module block to let Terraform know where the module code resides.

  • Press Escape and enter :wq to save and exit the file.

  • Create a new file called outputs.tf:

Run - vim outputs.tf

  • In the file, insert and review the provided code:

output "PrivateIP" {

description = "Private IP of EC2 instance"

value = aws_instance.my-instance.private_ip

}

  • Press Escape and enter :wq to save and exit the file.

Deploy Your Code and Test Out Your Module

  • Format the code in all of your files in preparation for deployment:

Run - terraform fmt -recursive

Then the next stage is to generate AWS Access Key and Secret Access Key on our AWS console, after generating, we run this command " AWS configure " then it will prompt for our AWS access key, we paste it and press enter, then next it will prompt for our AWS secret access key, we copy and paste it press enter, it will prompt for our default region name we will enter us-east-1 and press enter, for default output leave it at none and press enter.

  • Initialize the Terraform configuration to fetch any required providers and get the code being referenced in the module block:

Run - terraform init

  • Validate the code to look for any errors in syntax, parameters, or attributes within Terraform resources that may prevent it from deploying correctly:

Run - terraform validate

  • You should receive a notification that the configuration is valid.

  • Review the actions that will be performed when you deploy the Terraform code:

Run - terraform plan

  • In this case, it will create 3 resources, which includes the EC2 instance configured in the root code and any resources configured in the module. If you scroll up and view the resources that will be created, any resource with module.vpc in the name will be created via the module code, such as module.vpc.aws_vpc.this.

  • Deploy the code:

Run - terraform apply --auto-approve

  • Note: The --auto-approve flag will prevent Terraform from prompting you to enter yes explicitly before it deploys the code.

  • Once the code has executed successfully, note in the output that 3 resources have been created and the private IP address of the EC2 instance is returned as was configured in the outputs.tf file in your main project code.

  • View all of the resources that Terraform has created and is now tracking in the state file:

Run - terraform state list

  • The list of resources should include your EC2 instance, which was configured and created by the main Terraform code, and 3 resources with module.vpc in the name, which were configured and created via the module code.

  • Tear down the infrastructure you just created before moving on:

Finally, we head to AWS Console, then search for Instance, And view Instances, we will see our Ec2 Instance that was created.

Run - terraform destroy To delete the terraform

  • When prompted, type yes and press Enter.

Conclusion

Congratulations — you've completed this hands-on lab!

SUCCESS…..

Join me on this cloud adventure and elevate your tech skills! Sign in to the Azure portal, follow my easy instructions, and unleash the power of being in the cloud.

Subscribe to my blog for more tech tips and tricks that will keep you ahead in the digital game. Your journey to mastering Cloud computing starts here!

🌟 Thank you for being a part of this incredible journey! Together, let's unlock new opportunities and make the most out of our digital experiences. Happy computing! 🌟