Local Values
Crumb's configuration now writes "crumb-${var.environment}" in five places and repeats the same tags on every resource. Change the naming pattern and you must find all five. Local values give such expressions a single name.
The rule
Name it once in locals, read it as local.
locals {
name_prefix = "crumb-${var.environment}"
common_tags = {
project = "crumb"
environment = var.environment
managed_by = "terraform"
}
}
resource "aws_s3_bucket" "assets" {
bucket = "${local.name_prefix}-assets"
tags = local.common_tags
}
resource "aws_instance" "web" {
ami = "ami-0123456789abcdef0"
instance_type = var.instance_type
tags = merge(local.common_tags, { Name = "${local.name_prefix}-web" })
}Rules to keep straight:
- Declared in a
localsblock (plural); read aslocal.name(singular). - A configuration can have several
localsblocks; each name must still be unique. - A local can use variables, resource attributes, functions and other locals.
- A local cannot be set from outside. There is no
-varfor it.
That last rule is the difference from a variable. A variable is an input: the person running Terraform chooses it. A local is a derived value: the configuration's author defines it, and it follows from other values.
merge() in the example combines the shared tags with one extra tag for the server.
Common homes for locals are naming patterns, shared tags, and small lookups such as a map from environment to server size. A local that depends on a resource attribute, like an ID, is (known after apply) just as that attribute is. To check a local's value, type local.name_prefix into terraform console.
The shortcut
For each repeated value, ask "Should the user be able to choose this?" Yes: variable. No, it follows from other values: local.
Spot the repeat
"crumb-${var.environment}"appears five times; three tags repeat on every resource.
The trap: turning every expression into a local. A local used once only adds a jump for the reader. Use them for repeated or genuinely complex values.
Drills
Answer fast — trust the rule.
How do you read a local called name_prefix?
Can a local value be overridden with -var on the command line?
The server size should be chosen per environment by whoever runs Terraform. Local or variable?
Which can a local's expression refer to?
Remember
locals { x = ... }declares;local.xreads.- Shortcut: user chooses it → variable; it follows from other values → local.
- Trap: a local used once is just an extra hop for the reader.
