Locals

Terraform offers defining local values

About Local Values

  • A local value assigns a name to an expression, so you can use the name multiple times within a module instead of repeating the expression.
  • If you're familiar with traditional programming languages, it can be useful to compare Terraform modules to function definitions:
    • Input variables are like function arguments.
    • Output values are like function return values.
    • Local values are like a function's temporary local variables.

Declaring and using a Local Value

  • Here's a basic declaration
1locals {
2  service_name = "forum"
3  owner        = "Community Team"
4}
  • This one references the previous locals declaration:
 1locals {
 2  # Ids for multiple sets of EC2 instances, merged together
 3  instance_ids = concat(aws_instance.blue.*.id, aws_instance.green.*.id)
 4}
 5
 6locals {
 7  # Common tags to be assigned to all resources
 8  common_tags = {
 9    Service = local.service_name
10    Owner   = local.owner
11  }
12}
  • Using a local value in a resource:
1resource "aws_instance" "example" {
2  # ...
3
4  tags = local.common_tags
5}