Eduarn – Online & Offline Training with Free LMS for Python, AI, Cloud & More

Tuesday, March 31, 2026

Terraform Module with for_each INSIDE Module (Azure RG)

 Terraform Module with for_each INSIDE Module (Azure RG)

#!/bin/bash

# Create directory structure
mkdir -p tfmodule-foreach-inside/modules/rg
cd tfmodule-foreach-inside || exit

echo "📁 Creating Terraform files..."

# -------------------------
# provider.tf
# -------------------------
cat <<EOF > provider.tf
provider "azurerm" {
features {}
}
EOF

# -------------------------
# main.tf (NO loop here)
# -------------------------
cat <<EOF > main.tf

module "rg" {
source = "./modules/rg"

resource_groups = {
dev = "rg-dev"
test = "rg-test"
prod = "rg-prod"
}

rg_location = "eastus"
}

output "rg_names_output" {
value = module.rg.rg_names_output
}
EOF

# -------------------------
# modules/rg/rg.tf (for_each HERE)
# -------------------------
cat <<EOF > modules/rg/rg.tf
resource "azurerm_resource_group" "rg" {
for_each = var.resource_groups

name = each.value
location = var.rg_location

tags = {
environment = each.key
}
}
EOF

# -------------------------
# modules/rg/variable.tf
# -------------------------
cat <<EOF > modules/rg/variable.tf
variable "resource_groups" {
type = map(string)
}

variable "rg_location" {
type = string
}
EOF

# -------------------------
# modules/rg/output.tf
# -------------------------
cat <<EOF > modules/rg/output.tf
output "rg_names_output" {
value = {
for key, rg in azurerm_resource_group.rg :
key => rg.name
}
}
EOF

echo "✅ Terraform module with for_each INSIDE module created!"
echo ""
echo "👉 Next steps:"
echo "cd tfmodule-foreach-inside"
echo "terraform init"
echo "terraform plan"
echo "terraform apply"

▶️ How to Run

chmod +x setup.sh
./setup.sh

🎯 What This Does

  • Module called once
  • for_each inside module creates:
    • rg-dev
    • rg-test
    • rg-prod

📤 Output Example

{
"dev": "rg-dev",
"test": "rg-test",
"prod": "rg-prod"
}

🧠 Key Concept (Very Important)

🔹 for_each inside module

  • Loops over map
  • Uses:
    • each.key → dev/test/prod
    • each.value → resource name

⚖️ Count vs for_each (Inside Module)

Featurecountfor_each
Input typelistmap
Stability❌ index-based✅ key-based
Production use⚠️ limited✅ recommended

✅ Summary

  • for_each inside module = best practice
  • Cleaner, stable, production-ready
  • Ideal for multi-environment setups

No comments:

Post a Comment

AI Coding Agents Are Evolving Beyond Code Generation

 Most developers still think AI coding agents are only about writing code faster. That’s not the real shift happening in software engineerin...