Skip to main content
Let’s start with the first advanced construct: locals. In Terraform, locals are named values evaluated during configuration processing and reused throughout your configuration. Unlike input variables, locals are derived values (computed from variables, expressions, and functions). They centralize repeated logic and computed expressions so you avoid duplicating the same interpolation, concatenation, or function call across multiple resources.
The image illustrates the role of "locals" in Terraform. It highlights that locals define computed values and help avoid repeating the same expression.
Why use locals?
  • Define computed values (for example, transform environment names into standardized prefixes).
  • Reduce repetition of identical expressions across resources.
  • Improve readability and reduce the chance of copy/paste errors.
  • Make refactoring easier by centralizing logic in one place.
When should you use locals? Common scenarios include:
  • Naming conventions: construct consistent resource names using environment, project, or workload identifiers.
  • Tags: define a standard set of tags once and reuse them across resources.
  • Derived values used in multiple places: any calculated value referenced more than once should live in a local.
The image is a slide titled "When to Use Locals" and lists three points: "Naming convention," "Tags," and "Derived values used in multiple places."
Any value that is calculated and reused more than once should be a local.
Use locals to centralize computed logic. If you find yourself duplicating the same interpolation, concatenation, or function call across resources, move that expression into a local.
Example Below is a concise example showing a variable, a computed local, and the local referenced in a resource name:
Explanation
  • variable "environment" expects strings like dev, test, or prod.
  • local.name_prefix derives its value from var.environment, producing values such as demo-dev, demo-test, or demo-prod.
  • The resource group name is composed as demo-dev-rg, demo-test-rg, or demo-prod-rg depending on var.environment.
When to prefer locals (quick reference) Best practices
  • Give locals clear, descriptive names (e.g., name_prefix, default_tags, subnet_cidrs).
  • Keep locals focused on computation; avoid embedding complex side effects.
  • Use locals to simplify dynamic blocks and for_each expressions by computing maps or lists up front.
  • Limit the number of nested computations in a single local—split complex logic into multiple small locals for readability.
References
  • Terraform documentation: locals
Takeaway: locals clarify intent and reduce duplication. As a rule of thumb, if a value is derived and reused anywhere in your configuration, move it into a local. This pattern is particularly useful when working with dynamic blocks and computed collections—compute the list or map in a local, then iterate over it with dynamic or for_each.

Watch Video