Terraform Tutorial · Terraform Basics · Lesson 8 of 25

Terraform Locals

Local values give a name to an expression so you can reuse it. Use them to avoid repetition and keep configurations readable.

Declaring locals

Computed names and settings
variable "environment" {
  default = "prod"
}

locals {
  name_prefix = "shop-${var.environment}"
  is_prod     = var.environment == "prod"
  replicas    = local.is_prod ? 3 : 1
}

output "settings" {
  value = {
    bucket   = "${local.name_prefix}-assets"
    replicas = local.replicas
  }
}

Output

settings = {
  "bucket" = "shop-prod-assets"
  "replicas" = 3
}

Run this on your computer — see “Get Started” for setup.

Locals are like variables inside a configuration: they can't be set from outside. Use a variable for values a user chooses and a local for values you compute.

Common uses

locals {
  common_tags = {
    Project     = "shop"
    Environment = var.environment
    ManagedBy   = "terraform"
  }
}

resource "aws_s3_bucket" "assets" {
  bucket = "shop-${var.environment}-assets"
  tags   = local.common_tags
}

Test yourself

Can a user set a local value with -var?

  1. Yes
  2. No
Show answer

Answer: No

Locals are computed inside the configuration. Use a variable for user input.