0
0
Terraformcloud~30 mins

Why modules enable reusability in Terraform - See It in Action

Choose your learning style9 modes available
Why modules enable reusability
📖 Scenario: You are managing cloud infrastructure using Terraform. You want to create reusable code blocks to deploy virtual machines with consistent settings across different projects.
🎯 Goal: Build a Terraform module for a virtual machine and reuse it twice with different names and IP addresses.
📋 What You'll Learn
Create a Terraform module with variables for VM name and IP address
Use the module twice in the main configuration with different inputs
Output the VM names from the module instances
💡 Why This Matters
🌍 Real World
Cloud engineers use Terraform modules to reuse infrastructure code for similar resources across projects, saving time and reducing errors.
💼 Career
Understanding modules is essential for infrastructure as code roles, enabling scalable and maintainable cloud deployments.
Progress0 / 4 steps
1
Create a Terraform module with variables
Create a Terraform module folder named vm_module. Inside it, create a file main.tf that defines a resource aws_instance with the name set to the variable vm_name and private IP set to the variable vm_ip. Also create a variables.tf file defining the variables vm_name and vm_ip as strings.
Terraform
Need a hint?

Define variables in variables.tf and use them in main.tf inside the module folder.

2
Add module usage in main Terraform configuration
In the root Terraform configuration, create a file main.tf. Add two module blocks named vm1 and vm2 that use the vm_module source. Set vm_name to "web-server-1" and vm_ip to "10.0.1.10" for vm1. Set vm_name to "web-server-2" and vm_ip to "10.0.1.11" for vm2.
Terraform
Need a hint?

Use module "name" { source = "./vm_module" ... } blocks to reuse the module with different inputs.

3
Add outputs in the module
Inside the vm_module folder, create a file outputs.tf. Add an output named vm_name_output that outputs the tag Name of the aws_instance.vm resource.
Terraform
Need a hint?

Outputs allow you to expose values from modules. Use output "name" { value = ... }.

4
Output module instance names in root configuration
In the root main.tf, add two outputs named vm1_name and vm2_name. Set their values to the outputs vm_name_output from the modules vm1 and vm2 respectively.
Terraform
Need a hint?

Use output "name" { value = module.module_name.output_name } to expose module outputs.