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.

- 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.
- 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.

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.
variable "environment"expects strings likedev,test, orprod.local.name_prefixderives its value fromvar.environment, producing values such asdemo-dev,demo-test, ordemo-prod.- The resource group name is composed as
demo-dev-rg,demo-test-rg, ordemo-prod-rgdepending onvar.environment.
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.
- Terraform documentation: locals
dynamic or for_each.