What is locals in Terraform: Simple Explanation and Usage
locals in Terraform are named values you define inside a configuration to hold reusable expressions or constants. They help keep your code clean by storing values you want to use multiple times without repeating them.How It Works
Think of locals in Terraform like sticky notes you put on your desk. Instead of writing the same information over and over, you write it once on a note and refer to it whenever needed. This makes your workspace tidy and your work faster.
In Terraform, locals let you create named values inside your configuration files. These values can be simple strings, numbers, or even complex expressions. Once defined, you can use these names anywhere in your Terraform code, which helps avoid mistakes and makes updates easier.
Example
This example shows how to define locals and use them to set tags for AWS resources.
locals {
environment = "production"
owner = "team-ops"
tags = {
Environment = local.environment
Owner = local.owner
}
}
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = local.tags
}When to Use
Use locals when you have values or expressions that repeat in your Terraform code. This helps avoid repeating the same text or logic multiple times, making your code easier to read and maintain.
For example, if you use the same tag values across many resources, or if you calculate a value from other inputs, locals keep your code DRY (Don't Repeat Yourself). They are also useful for organizing complex expressions into simpler parts.
Key Points
- locals store reusable values inside Terraform configurations.
- They help keep code clean and reduce repetition.
- Values in
localscannot be changed after definition. - They are evaluated each time Terraform runs, so they can use other variables or expressions.
Key Takeaways
locals hold reusable values to simplify Terraform code.locals can store simple or complex expressions.locals to organize and clarify your configurations.