Understanding Terraform Modules: The Key to Scalable Infrastructure


Introduction: Why Terraform Modules Matter
Terraform modules are the building blocks of Infrastructure as Code (IaC), enabling you to package and reuse infrastructure components efficiently. Whether you're managing cloud resources across multiple environments or collaborating with a team, modules help maintain consistency, reduce duplication, and simplify maintenance.
In this blog post, we'll cover:
What Terraform modules are and their benefits
How to create and use modules
Best practices for module design
Real-world examples
Understanding Terraform Modules
What is a Terraform Module?
A Terraform module is a reusable, self-contained package of Terraform configurations that defines a set of resources. Think of it as a function in programming it encapsulates logic and can be called multiple times with different inputs. Modules is made up of main.tf ,variables.tf and outputs.tf files.
Types of Modules
Root Module: The main configuration where execution begins.
Child Module: A reusable module called within the root or another module.
Public/Private Modules: Shared via Terraform Registry, GitHub, or private repositories.
Why Use Modules?
✅ Reusability: Avoid copy-pasting code.
✅ Consistency: Enforce standards across projects.
✅ Scalability: Manage large infrastructure efficiently.
✅ Collaboration: Share modules across teams.
1,Building And Testing a Basic Terraform Module
Prerequisite Ensure you have AWS CLI installed on your linux Vm You can use the command sudo snap install aws-cli --classic 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.
Let Goes First sign in as a rootuser using the command code sudo su - and input your password
And create a new directory called terraform_project to house your Terraform code: using the command code mkdir terraform_project
Next is to switch to this main project directory with the command code cd terraform_project
After switching to the main project directory create a custom directory called modules and a directory inside it called vpc using the command code mkdir -p modules/vpc
Run the command ls to see the list of the directory content.
Switch to the vpc directory using the command code cd modules/vpc
Next is to write the terraform vpc modules code. So l create a new file called main.tf using the command vim main.tf
In the file l inserted and review my code Note this code might be provided, Click on letter i so you can be able to type or paste your code in the file you created using Vim.
After inputting the code l Pressed Escape and enter :wq to save and exit the file.
Note: From the code below the first line shows our provider which is aws and the second line shows that the region has been specified in our variables.tf which will be creating next. On the resource line our resource was named and our vpc ip established and was also reference in our subnets. our subnet was we specified it on our variables.tf and also in our resources too insead of repeating same code er just reused the code in a reference form.
Next l created a new file again called variables.tf using the command vim variables.tf
In the file, l also inserted and review my variables code our location was set to us east-1 as our default region, save and exit the file.
- Next l created a new file called outputs.tf with the command code vim outputs.tf
in the file, l inserted and review my code
Note: The code in our outputs.tf is critical to exporting values to our main Terraform code, where where we reference the modules. Specifically, it returns the subnet and AMI IDs for our EC2 instance.
Next is to create our Main Terraform Project Code To do this we need to switch to the main project directory: we the command code cd ~/terraform_project
After switching to your main resource project directory we have to create a new file called main.tf using the command code vim main.tf
ln this file, l inserted and review the code Note: The code in main.tf invokes the VPC module that we created earlier. Notice how we 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
I went ahead to create a new file called outputs.tf using the command code vim outputs.tf
In the file, l inserted and review the code after which l Pressed Escape and enter :wq to save and exit the file.
2, Deploying our Code and Testing out our Module To do this we have to format the code in all our files in preparation for deployment, To format we run the command code terraform fmt -recursive
After formatting next is to run our Aws configure so we can attach our private key, Access key and so on to do this run the command code aws configure.
That command will prompt you getting your AWS Access Key ID: Your access key (from IAM user credentials).AWS Secret Access Key: Your secret key (from IAM user credentials). Default region name: The AWS region you want to use (e.g., us-east-1
, eu-west-1
). Default output format: The output format (e.g., json
, text
, yaml
, or table
) to get them head over to aws console to create one. Note: The aws configure
command is used to set up the AWS CLI (Command Line Interface) with your credentials and default settings.
Double click on the user
select user to head over to where you will create your access key.
Click on the create access key and select the command line interface
Scroll down and check the confirmation and click next
Once created scroll down to copy the keys or download the file.
Return to your project to paste your keys, on the default region name and output format click on enter to leave it at default.
Next is to initialize the Terraform configuration to fetch any required providers and get the code being referenced in the module block with the command code terraform init
Next is to validate the code to look for any errors in syntax, parameters, or attributes within Terraform resources that may prevent it from deploying correctly: run the command terraform validate
I received a notification that the configuration is valid and successful
The next terraform code to run is 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.
above are 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.
At this stage is to deploy our code using the command 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 our main project code
To view all of the resources that Terraform has created and is now tracking in the state file: run the command terraform state list
The list of resources should include our 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.
Lets confirm that our EC2 instatnce was created successfully from the AWS console, l went straight to the console and clicked on instance and boom i saw my my instance ID.
Double click on the instance and view the properties
Conclusion
Terraform modules are not just a nice-to-have, they are essential if you're working in a real-world infrastructure-as-code environment. If you're not using modules yet, today is a great day to start modularizing your Terraform code!.
See you next time.
###
Subscribe to my newsletter
Read articles from Nweke Henry directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
