Terraform Locals

Terraform is not just another open-source infrastructure as a code software tool. Users determine and implement data center infrastructure applying a declarative code language, HashiCorp Code Language, or optionally JSON. So, it allows us to create code. We can create variables to facilitate the design of a dynamic solution with complex scenarios and data. And the Terraform Locals provide us with superb usability in this context.

A good video if you don’t know how the Terraform works:

What are Terraform Locals?

Terraform locals are called values that you can associate with your code. You can create local values to clarify your Terraform code and avoid duplication. Local values (locals) can also help you design a more readable code by applying significant names rather than hard-coding values.

But, what is the difference between Terraform Locals and Variables?


Check our post:

How to use Gitlab to Deploy your Terraform Code.

Do you know How to use Terraform Template?


Terraform Locals vs Varariables

Like many programming languages, the concept around the variables also involves understanding the variables’ scope. When we decide to use and create variables, we need to know how we would like to expose this variable for our application. So, in other words, if need need them global or with a limited scope: locally available only in our method or function.

We can only access a local variable (Terraform Locals) in expressions inside the module where it was declared.

However, unlike variables found in programming languages, Terraform’s locals don’t modify values through or within Terraform commands like the planapply, or destroy. Instead, you can employ locals to provide a name to the result of each Terraform expression and re-use that name during your code. Furthermore, unlike input variables, locals are not introduced directly by users of your configuration.

A local value designates a name to an expression, so you can use it many times within a module without repeating it.

If you’re accustomed to the conventional programming languages, it can be helpful to compare Terraform modules to function representations:

  • Input variables are like function arguments.
  • Output values are like function return values.
  • Local deals are similar to a function’s temporary local variables.

How to declare Terraform Locals

You can declare a collection of corresponding local values commonly in a single locals section.

The locals section represents one or more local variables inside a module. Any locals section can hold as many locals as required, and there can be any amount of locals blocks within a module.

locals {
  instance_name = "bitslovers-server-qa"
  region        = "us-east-1"
}

The expressions in local values are not restricted to literal constants; they can also use other values inside the module to modify or join them, for example, with variables, resource attributes, or different local values.

The names created for the items in the locals section must be unique in the whole module. The returned value can hold any expression that is valid inside the current module.

Terraform Locals Example

Suppose that we would like to create several AWS Elastic IPs according to the availability zone number. First, let’s see this Terraform Locals Example:

locals {
  count_nat_gateways = var.is_nat_gateway_enabled ? length(var.availability_zones) : 0
}

resource "aws_eip" "default" {
  count = local.count_nat_gateways
  vpc   = true

  tags = merge(
    module.private_label.tags,
    {
      "Name" = format(
        "%s%s%s",
        module.private_label.id,
        var.delimiter,
        replace(
          element(var.availability_zones, count.index),
          "-",
          var.delimiter
        )
      )
    }
  )

  lifecycle {
    create_before_destroy = true
  }
}

Maybe you already noticed that it’s advantageous to use the Terraform Locals combined with a count.

Reminder: Local values are generated by a local section (plural). However, you reference them being properties on a local (singular) object. Therefore, be convinced to drop off the “s” when referencing a local value!

Also, you can assign the expression of a local value to other locals, but reference sequences are not allowed as usual. Finally, a local cannot assign itself or a variable that holds (directly or indirectly) back to it.

Also, Terraform Locals variables can be used with for loop.

Terraform locals for each

locals {
  labels = [for l in local.label_order : local.id_context[l] if length(local.id_context[l]) > 0]
}

Terraform Locals map

Following the bellow an example, also merge variables with local values:

locals {
	tags = merge(local.generated_tags, var.tags)

tags_map = flatten([
    for key in keys(local.tags) : {
      key   = key
      value = local.tags[key]
  }])
}

When To Use Terraform Locals

Terraform Locals can be essential to avoid repeating the identical values or expressions many times in your code. Still, if overused, they can also make a code hard to understand by coming maintainers by covering the actual values used.

Use Locals only in balance when a particular value or result is utilized in various places, and that value is reasonable to be changed in the future. The capability to effortlessly modify the value in a convenient location is the principal benefit of locals.

Conclusion

One last tip, it’s suggested to associate collectively logically related local values within a single section, mainly if they depend on each other. So, that way will benefit the others to understand the connections among variables. Otherwise, it’s better to represent unrelated local values within separate sections and explain each section with a commentary explaining each context well-known to all included locals.

I hope that you have learned the main idea of the Locals. Please, send me feedback and take some minutes to support us on social media.

What's your reaction?

Excited
0
Happy
1
In Love
0
Not Sure
0
Silly
0

You may also like

Leave a reply

Your email address will not be published. Required fields are marked *

More in:AWS