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"
}
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
}
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
}
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
-
Initialize Terraform (downloads Azure provider and module dependencies):
terraform init -
Validate configuration:
terraform validate -
Preview changes:
terraform plan -
Apply changes (create resource group):
terraform apply --auto-approve
β Final Output
Terraform will create an Azure Resource Group named:
mademi-rg1
in the region:
centralus
π 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)