Local Values
Locals name a computed expression once so you can reuse it without repetition.
Syntax
locals {
name = expression
}Local values (locals) assign a name to an expression so you can use it many times within a module. Unlike variables, locals cannot be set from outside — they are computed inside the configuration.
When to use locals
- Build a common set of tags once and reuse everywhere.
- Compute a derived name like
"${var.project}-${var.environment}". - Avoid repeating a complex expression.
Reference them with local.name.
Example
locals {
name_prefix = "${var.project}-${var.environment}"
common_tags = {
Project = var.project
Environment = var.environment
ManagedBy = "Terraform"
}
}
resource "aws_s3_bucket" "data" {
bucket = "${local.name_prefix}-data"
tags = local.common_tags
}When to use it
- An engineer defines a local for the full resource name prefix (e.g., myapp-prod-) so it is computed once and reused across 20 resource blocks without duplication.
- A team uses a local to merge common_tags with resource-specific tags, producing a consistent tag map they spread into every resource's tags argument.
- A module uses locals to compute derived values like availability zones from a region variable, keeping expressions out of resource blocks.
More examples
Name prefix local value
Computes a reusable name prefix once in locals and references it across multiple resources to ensure naming consistency.
locals {
name_prefix = "${var.project}-${var.environment}"
}
resource "aws_s3_bucket" "data" {
bucket = "${local.name_prefix}-data"
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
tags = { Name = "${local.name_prefix}-web" }
}Merged tags local
Defines a common tag map as a local and merges it with resource-specific tags, avoiding repetitive tag blocks.
locals {
common_tags = {
Project = var.project
Environment = var.environment
ManagedBy = "terraform"
}
}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
tags = merge(local.common_tags, { Name = "main-vpc" })
}
resource "aws_subnet" "public" {
cidr_block = "10.0.1.0/24"
vpc_id = aws_vpc.main.id
tags = merge(local.common_tags, { Name = "public-subnet" })
}Derived computation in locals
Computes derived values (is_production, instance size, capacity) in locals so resource blocks contain only clean references.
locals {
is_production = var.environment == "production"
instance_type = local.is_production ? "m5.large" : "t3.micro"
min_capacity = local.is_production ? 3 : 1
}
resource "aws_autoscaling_group" "app" {
min_size = local.min_capacity
max_size = local.min_capacity * 4
# ...
}
Discussion