In this lesson, you’ll discover how to use local values (locals) in OpenTofu to eliminate duplication, improve readability, and keep your configuration DRY (Don’t Repeat Yourself).Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
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
| Use Case | Local Value Example |
|---|---|
| Share common configuration across resources | local.common_tags |
| Build dynamic names or identifiers | local.bucket_prefix |
| Simplify complex expressions | Intermediate computed values |
Further Reading and References
- OpenTofu Locals Documentation
- Terraform Best Practices
- Random Provider on Terraform Registry
- AWS Provider on Terraform Registry