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

Showing posts with label Terraform Module with count INSIDE Module (Azure RG) By EduArn. Show all posts
Showing posts with label Terraform Module with count INSIDE Module (Azure RG) By EduArn. Show all posts

Tuesday, March 31, 2026

Terraform Module with count INSIDE Module (Azure RG) By EduArn

Save below code int setup.sh file:

 vi setup.sh 

#!/bin/bash

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

echo "📁 Creating Terraform files..."

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

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

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

rg_names = ["rg-dev", "rg-test", "rg-prod"]
rg_location = "eastus"
}

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

# -------------------------
# modules/rg/rg.tf (COUNT HERE)
# -------------------------
cat <<EOF > modules/rg/rg.tf
resource "azurerm_resource_group" "rg" {
count = length(var.rg_names)

name = var.rg_names[count.index]
location = var.rg_location

tags = {
environment = "Dev"
}
}
EOF

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

variable "rg_location" {
type = string
}
EOF

# -------------------------
# modules/rg/output.tf
# -------------------------
cat <<EOF > modules/rg/output.tf
output "rg_names_output" {
value = azurerm_resource_group.rg[*].name
}
EOF

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

▶️ How to Run

chmod +x setup.sh
./setup.sh

🎯 What This Does

  • count is used inside module
  • Root module calls only once
  • Module creates multiple resources internally

📁 Output

rg-dev
rg-test
rg-prod

🧠 Key Concept (Important for Interviews)

🔹 Count in Root Module

  • Creates multiple module instances

🔹 Count in Module (this example)

  • Creates multiple resources inside module

👉 This is a very important distinction


✅ Summary

  • Module called once
  • count handled internally
  • Clean and reusable design
  • Best for encapsulated logic

Terraform Modules in Azure: Step-by-Step Guide with Count, for_each & YAML Examples

  Introduction In modern cloud environments, writing reusable and scalable infrastructure is critical. Using Terraform with Microsoft Azur...