Skip to content

Local Variables

Filename Location Group Project/Repository
locals.tf ./locals.tf infrastructure terraform

Why?

In HCL2 locals represent variables that aren't configured by the user calling the code. Instead they're used to compute some value that's internal (or local) to the code using it and nothing more.

They're very handy for constructing things you'll reference a lot in your code but don't want external values to be able to override the value.

Breakdown

Our locals aren't overly complex. First we define the ubuntu_ami local:

1
2
locals {
  ubuntu_ami = "ami-0a43280cfb87ffdba"

The ubuntu_ami local variable is a static AMI ID. We'll be using this with our EC2 Instances to ensure they're all using the same AMI for predictability.

And finally we define the common_tags local:

1
2
3
4
5
6
  common_tags = {
    "Solution"    = "HTTP Cats"
    "Environment" = "MVP"
    "Contact"     = "Michael Crilly mike@opsfactory.com.au"
  }
}

We'll be using the common_tags local variable for ensuring all AWS resources that can be tagged are tagged, and in a manner that's consistent. We'll be doing this using the merge() function in HCL2 to combine the common_tags tags with the Name tag.

Note

The Name tag in AWS is special. If the Name is present on, for example, an EC2 Instance, then the value of the tag is used in the AWS UI "Name" column when displaying the EC2 Instance in data tables.

Here's an example of this local variable being used with the tags:

Note

This is just a demonstration - don't add this to any of the files you've written so far

1
2
3
tags = merge(local.common_tags, {
    "Name" = "httpcats"
})

Because local.common_tags is a map, and we're passing { "Name" = "httpcats" } as the second argument, we're asking merge() to merge the two maps into a single map which will look like this:

1
2
3
4
5
6
{
    "Solution"    = "HTTP Cats"
    "Environment" = "MVP"
    "Contact"     = "Michael Crilly mike@opsfactory.com.au"
    "Name"        = "httpcats"
}

As a result our AWS resource will contain all those tags.

The Solution

1
2
3
4
5
6
7
8
9
locals {
  ubuntu_ami = "ami-0a43280cfb87ffdba"

  common_tags = {
    "Solution"    = "HTTP Cats"
    "Environment" = "MVP"
    "Contact"     = "Michael Crilly mike@opsfactory.com.au"
  }
}

Terraform Documentation

Type Documentation
locals Terraform AWS Provider

Committing the Code

  1. Set your working directory to the infrastructure/terraform repository
  2. Save the file as locals.tf and use git add locals.tf to add it to the Git staging area
  3. Use git commit -am 'defining the static locals we need in our code' to commit the file to our repository
  4. Push the code to GitLab.com: git push

Last update: August 25, 2021