Azure Terraform: Part 8 – Terraform Locals

Reading Time: 2 minutes

In this chapter of our Terraform journey we will venture into the the first of the Terraform capabilities that allows us to streamline our configuration and enhance the readability of our Terraform script, Terraform Locals.

Terraform Locals

Terraform Locals allows you to define a local value within your Terraform main.tf file and reference the name associated with the defined value multiple times within your Terraform script.

A local value needs to be defined within a locals block and acts as a dynamic reference within you script. In our test environment declaring the tag as a local value within the locals block would look like,

locals {
  tags = {
    environment = "dev"
  }
}

Tags being the name given to the local value, we can then use the name to reference tags within our Terraform script.

It is best practice to define the locals value towards the top of your Terraform scipt.

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "3.82.0"
    }
  }
}

provider "azurerm" {
  features {}
}

locals {
  tags = {
    environment = "dev"
  }
}

In the code block above we have defined a locals value for tags below the empty features block.

Using the Locals Value

In part 3 of this terraform series we created an Azure Resource Group, defining the optional argument for tags,

resource "azurerm_resource_group" "tfrg007" {
  name     = "tgtestrg007"
  location = "uksouth"

  tags = {
    environment = "dev"
  }
}

To reference the locals value we have defined for tags this can be re-written as tags = local.tags. Note when referencing the value local (no s) is used not locals.

resource "azurerm_resource_group" "ftrg001" {
  name     = "FT23-RG-001"
  location = "uksouth"

  tags = local.tags
}

This will still tag the resource group as being part of the dev environment as defined within the locals block.

You can then use tags = local.tags to update the tags vale define for any other resource within your Terraform script.

See the Hashicorp documentation for additional information about Terraform Locals, the link is here.

In the next blog post in this series we will take a look at Terraform Variables.