Terraform
Use locals to reuse expressions
Hands-on: Try the Simplify Terraform Configuration with Locals tutorial.
Local values are similar to function-scoped variables in other programming languages. Local values assign names to expressions, letting you use the name multiple times within a module instead of repeating that expression.
Define locals
Add a locals block when you want to reuse an expression throughout your configuration. You can define the locals block in any module and can assign any valid Terraform expression as its value. You can reference the following constructs:
- Variables
- Resource attributes
- Function outputs
- Other local values
For example, you could define a locals block to create a consistent naming convention, identify your primary subnet, and to set aside environmental configuration settings:
locals {
# Naming convention
resource_name = "${var.project_name}-${var.environment}"
# Process the subnet list
primary_public_subnet = var.subnet_ids[0]
subnet_count = length(var.subnet_ids)
# Environmental deployment settings
is_production = var.environment == "prod"
monitoring_enabled = var.monitoring || local.is_production
}
Refer to the locals block reference for more information about configuring local variables.
Reference local variables
Use the local.<NAME> syntax to reference values from a locals block in your configuration. The locals block defines local values, but you must use the singular local keyword to reference the individual values.
For example, in your configuration you can reference local.resource_name to name resources, and use local.primary_public_subnet with local.monitoring_enabled to configure a web server:
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = var.instance_type
subnet_id = local.primary_public_subnet
monitoring = local.monitoring_enabled
tags = {
Name = local.resource_name
Environment = var.environment
}
}
resource "aws_security_group" "web" {
name = "${local.resource_name}-sg"
tags = {
Name = "${local.resource_name}-security-group"
}
}
You can access local values in the module where you define them, but not in other modules. However, you can pass a local value to a child module as an argument.
Local values help avoid repetition and give a meaningful name to the value of an expression. However, they can make configuration harder to read because they obscure where values originate. Use local values in situations where you either reuse a single value in many places to let you change a value in a single place or when the value is the result of a complex expression.
To learn more about the locals block, refer to the locals block reference.