How to Use a Terraform Module

In this blog post, we will learn how to use a Terraform module with variables to create resources in Microsoft Azure.

Modules

In yesterday’s blog post I showed how to use modules without variables and hardcode the values. Today we will take a step forward and make the module more usable.

Folder and Files

Below is the folder and file structure I am going to use, the only difference you will find here compared basic configuration is that I’m also using a variables.tf file which will hold the variables.

Modules 
   CREATE_AZ_RG       
    rg.tf
    variables.tf

Variables.tf

Below, is the content of the variables.tf file. as you can see I have two variables that I will use to create a Resource Group in Azure.

variable "rgname" {
    type = string
}

variable "rglocation" {
    type = string
}

rg.tf

The content of the rg.tf which holds the module looks as follow:

resource "azurerm_resource_group" "rg" {
  name     = var.rgname
  location = var.rglocation
}

Main.tf

The last piece of the puzzle is the main.tf file which I will use to call the module. In the file, I set the values for the resource group (name and location). If you notice I’m using the variables name I have specified in the variables.tf file.

module "azurerm_resource_group" {
    source = "/Terraform/Modules/AzureRG2"
    rgname = "Myrg0001"
    rglocation = "westus"
}

This blog post was first published on our sister site https://www.ntweekly.com

Leave a comment

Your email address will not be published. Required fields are marked *