Spec-Zone.ru › OpenTofu 1.9

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 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.
Note

For brevity, local values are often referred to as just "locals" when the meaning is clear from context.

Declaring a Local Value​

A set of related local values can be declared together in a single locals block:

Code Block
locals {
  service_name = "forum"
  owner        = "Community Team"
}

The expressions in local values are not limited to literal constants; they can also reference other values in the module in order to transform or combine them, including variables, resource attributes, or other local values:

Code Block
locals {
  # Ids for multiple sets of EC2 instances, merged together
  instance_ids = concat(aws_instance.blue.*.id, aws_instance.green.*.id)
}

locals {
  # Common tags to be assigned to all resources
  common_tags = {
    Service = local.service_name
    Owner   = local.owner
  }
}

Using Local Values​

Once a local value is declared, you can reference it in expressions as local.<NAME>.

Note

Local values are created by a locals block (plural), but you reference them as attributes on an object named local (singular). Make sure to leave off the "s" when referencing a local value!

Code Block
resource "aws_instance" "example" {
  # ...

  tags = local.common_tags
}

A local value can only be accessed in expressions within the module where it was declared.

When To Use Local Values​

Local values can be helpful to avoid repeating the same values or expressions multiple times in a configuration, but if overused they can also make a configuration hard to read by future maintainers by hiding the actual values used.

Use local values only in moderation, in situations where a single value or result is used in many places and that value is likely to be changed in future. The ability to easily change the value in a central place is the key advantage of local values.

Copyright (c) The OpenTofu Authors
Copyright (c) 2014 HashiCorp, Inc.
Mozilla Public License, version 2.0
https://opentofu.org/docs/v1.9/language/values/locals/

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API