The Problem: Repeated Tag Definitions
Imagine you have two AWS EC2 instances—web and db—that share identical tags. Without locals, your HCL might look like this:
Defining the same tags in multiple resources increases maintenance overhead. Locals allow you to declare shared values in one place.
Step 1: Define a locals Block
Create a locals block to hold your common tag set:
Step 2: Reference the Local Value
Uselocal.common_tags within each resource:
Step 3: Preview and Apply
Runningtofu plan or tofu apply now shows both instances using the shared tags:
Advanced Example: Combining Variables and Resource Attributes
Locals aren’t limited to static maps—they can also concatenate variables, resource attributes, and more. For instance, to generate a globally unique S3 bucket name:tofu apply, you’ll see:
HCL supports both legacy interpolation (
"${...}") and the newer direct syntax (var.project). Both work in locals, but be consistent across your codebase.When to Use Local Values
Further Reading and References
- OpenTofu Locals Documentation
- Terraform Best Practices
- Random Provider on Terraform Registry
- AWS Provider on Terraform Registry