Using Terraform locals to minimize repetition

Locals tags can be used to minimize code repetition in terraform.

Using Terraform locals to minimize repetition
Photo by Jed Adan / Unsplash

A useful practice, especially for things like tagging in AWS, is to utilize the Terraform locals to reduce repeated blocks of code.

locals {
  local_resource_tag = {
    pii           = "true",
    owner         = "nmmes",
    more_tags 	  = "true"
  }
}
A locals block of tags for future use

Then, on each resource, you can merge those locals in, and override and supliment as necessary without repeating them:

  tags = merge(local. local_resource_tag, {
    Name = "Name_of_thing"
  })
Terraform merge function enables the tag block to be easily merged in and used

Locals are useful in more places than just tags, anywhere you repeat something throughout a file.
Of course, for tags specifically, you can also put tags in your providers block that are applied to all the resources in a project, but this is useful for cases where you want the tags on a bunch of related resources within the project.