🎓 A1Learner
🔍
0 of 50 lessons completed

Locals

A local value is a name for a value computed inside a configuration. It is calculated once and reused wherever it is needed.

Build a shared prefix

The prefix joins the project name and the environment.

locals {
  project     = "shop"
  environment = "dev"
  prefix      = "${local.project}-${local.environment}"
}

Use the local twice

Both files carry the same prefix. Change it in one place.

resource "local_file" "a" {
  content  = "First file."
  filename = "${path.module}/${local.prefix}-a.txt"
}

Locals can build on locals

Each new local can reuse one defined above it.

locals {
  base_name = "${local.project}-${local.environment}"
  file_a    = "${local.base_name}-a.txt"
  file_b    = "${local.base_name}-b.txt"
}

Example

# main.tf
terraform {
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.0"
    }
  }
}

locals {
  project     = "shop"
  environment = "dev"
  prefix      = "${local.project}-${local.environment}"
}

resource "local_file" "a" {
  content  = "First file."
  filename = "${path.module}/${local.prefix}-a.txt"
}

resource "local_file" "b" {
  content  = "Second file."
  filename = "${path.module}/${local.prefix}-b.txt"
}

# commands
terraform init
terraform apply -auto-approve

Key points

  • Locals live in a locals block. Each one has a name and an expression.
  • A local is read as local.name. The same value can appear in many places.
  • Locals suit values that are built from other values. A common prefix is a good example.
  • A local cannot be set from outside. Only variables take values from the caller.
  • A local that is used once adds little. Reach for one when a value repeats.

The prefix is built once in the locals block. Both files use it, so the naming stays the same everywhere. Change the project name in one place and both file names follow.

Note

locals are computed during the plan. They never reach a provider on their own.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

When does a local beat a variable?