Learn to use local values in OpenTofu to reduce duplication, enhance readability, and maintain a DRY configuration.
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).
Running tofu plan or tofu apply now shows both instances using the shared tags:
Copy
Ask AI
$ tofu applyAn execution plan has been generated and is shown below.Resource actions are indicated with the following symbols: + createOpenTofu will perform the following actions:# aws_instance.db will be created+ resource "aws_instance" "db" { + tags = { + "Department" = "finance" + "Project" = "cerberus" }}# aws_instance.web will be created+ resource "aws_instance" "web" { + tags = { + "Department" = "finance" + "Project" = "cerberus" }}Plan: 2 to add, 0 to change, 0 to destroy.
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:
Copy
Ask AI
variable "project" { description = "Name of the project" type = string default = "cerberus"}resource "random_string" "random_suffix" { length = 6 special = false upper = false}locals { bucket_prefix = "${var.project}-${random_string.random_suffix.id}-bucket"}resource "aws_s3_bucket" "finance_bucket" { acl = "private" bucket = local.bucket_prefix}
HCL supports both legacy interpolation ("${...}") and the newer direct syntax (var.project). Both work in locals, but be consistent across your codebase.