Introduction
In modern cloud environments, writing reusable and scalable infrastructure is critical. Using Terraform with Microsoft Azure, you can achieve this efficiently through Terraform modules.
This blog provides:
✅ Simple module example
✅ count implementation
✅ for_each implementation
✅ YAML-based configuration
✅ Fully working step-by-step code
๐ฆ Step 1: Simple Terraform Module (Basic Example)
๐ Folder Structure
project/
├── main.tf
├── provider.tf
└── modules/
└── rg/
├── main.tf
├── variables.tf
└── outputs.tf๐น Module Code
modules/rg/main.tf
resource "azurerm_resource_group" "rg" {
name = var.rg_name
location = var.rg_location
}modules/rg/variables.tf
variable "rg_name" {
type = string
}
variable "rg_location" {
type = string
}modules/rg/outputs.tf
output "rg_name" {
value = azurerm_resource_group.rg.name
}๐น Root Module
provider.tf
provider "azurerm" {
features {}
}main.tf
module "rg" {
source = "./modules/rg"
rg_name = "demo-rg"
rg_location = "eastus"
}▶️ Run
terraform init
terraform plan
terraform apply๐ Step 2: Using count in Module (Multiple Resources)
variable "rg_names" {
default = ["rg-dev", "rg-test", "rg-prod"]
}
module "rg" {
source = "./modules/rg"
count = length(var.rg_names)
rg_name = var.rg_names[count.index]
rg_location = "eastus"
}๐ Creates:
- rg-dev
- rg-test
- rg-prod
๐ Step 3: Using for_each (Recommended)
variable "rgs" {
default = {
dev = "rg-dev"
test = "rg-test"
prod = "rg-prod"
}
}
module "rg" {
source = "./modules/rg"
for_each = var.rgs
rg_name = each.value
rg_location = "eastus"
}๐ค Output
output "rg_names" {
value = {
for key, mod in module.rg :
key => mod.rg_name
}
}๐งพ Step 4: Using YAML Configuration (Advanced)
๐ config.yaml
resource_groups:
dev: rg-dev
test: rg-test
prod: rg-prod๐น Terraform Code
locals {
config = yamldecode(file("${path.module}/config.yaml"))
}
module "rg" {
source = "./modules/rg"
for_each = local.config.resource_groups
rg_name = each.value
rg_location = "eastus"
}๐ง Key Concepts
| Feature | Use |
|---|---|
| Module | Reusable code |
| count | Simple iteration |
| for_each | Map-based iteration |
| YAML | External config |
⚖️ Count vs for_each
| Feature | count | for_each |
| Input | List | Map |
| Stability | ❌ Index-based | ✅ Key-based |
| Recommended | ⚠️ Limited | ✅ Yes |
๐ฏ Best Practices
- Use modules for reusable design
- Prefer for_each over count
- Use YAML for external configuration
- Keep modules small and focused
- Avoid hardcoding values
๐ Learn with Eduarn
At Eduarn, we provide hands-on training on:
- Terraform
- Microsoft Azure
✔ Real-time projects
✔ Corporate training
✔ Job-oriented learning
๐ Visit: https://eduarn.com
๐ Conclusion
Terraform modules are essential for building scalable, reusable, and production-ready infrastructure.
By mastering:
- Basic modules
- count
- for_each
- YAML configs
๐ You become a real-world DevOps engineer
๐ฅ Hashtags
#Terraform #Azure #DevOps #InfrastructureAsCode #CloudAutomation #TerraformModules #EduArn

No comments:
Post a Comment