DEV Community

Deepak Sharma
Deepak Sharma

Posted on

Terraform Module Example – Resource Group Creation on Azure

This project demonstrates how to create an Azure Resource Group using Terraform modules.

By using modules, we can organize our code better, promote reusability, and simplify management of infrastructure.


📂 Project Structure

parent_module/
│── main.tf

└── modules/
└──── resource_group/
├────── resource_group.tf
├────── variables.tf


🔹 1. main.tf (in parent_module directory)

This is the root configuration file where we call our module.

module "rg_create" {
  source      = "../modules/resource_group"
  rg_name     = "mademi-rg1"
  rg_location = "centralus"
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • module "rg_create" → Declares a module block named rg_create.
  • source = "../modules/resource_group" → Points to the directory where our module is located.
  • rg_name → Resource Group name passed to the module (mademi-rg1).
  • rg_location → Azure region where the Resource Group will be created (centralus).

🔹 2. resource_group.tf (inside modules/resource_group)

This file defines the actual resource that Terraform will create.

resource "azurerm_resource_group" "mademi-rg" {
  name     = var.rg_name
  location = var.rg_location 
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • azurerm_resource_group → Azure Resource Group resource type.
  • name → Uses the value of the variable rg_name.
  • location → Uses the value of the variable rg_location.

🔹 3. variables.tf (inside modules/resource_group)

This file declares the input variables that the module will accept.

variable "rg_name" {
  type = string
}

variable "rg_location" {
  type = string
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • rg_name → The name of the Resource Group (string type).
  • rg_location → The Azure region (string type).

These variables are provided from the parent module (main.tf).

⚙️ How to Run

  1. Initialize Terraform (downloads Azure provider and module dependencies):

    terraform init
    
  2. Validate configuration:

    terraform validate
    
  3. Preview changes:

    terraform plan
    
  4. Apply changes (create resource group):

    terraform apply --auto-approve
    

✅ Final Output

Terraform will create an Azure Resource Group named:

mademi-rg1
Enter fullscreen mode Exit fullscreen mode

in the region:

centralus
Enter fullscreen mode Exit fullscreen mode

📘 Key Learning

  • Modules in Terraform make code reusable and clean.
  • Instead of writing resources directly in the root main.tf, you can package them into modules and pass values as variables.
  • This is especially useful when you manage large infrastructure with multiple environments.

👉 This setup can be extended further by adding:

  • Virtual Networks
  • Storage Accounts
  • Virtual Machines
  • and other Azure resources inside modules.

👉 Follow me on

Top comments (0)