Use locals with Terraform

gdenn

Dennis Groß (he/him)

Posted on December 20, 2022

Use locals with Terraform

Locals are like variables another tool to avoid hard coding values in terraform scripts and keep the code DRY.

The scope of locals is restricted to the current module and can yield

  • a hard value like a string, integer etc.
  • an expression

Locals cannot be passed through the CLI or environment and represent a more permanent, constant value or expression in your code.

Create Locals

Locals can be defined in the locals block and used in the same module.

locals {
  uuidv4 = "4c67baa1-f139-45c0-85d4-451e615ece9a"
  bucket_name = "my-fancy-bucket-${uuidv4}"
}
Enter fullscreen mode Exit fullscreen mode

Use Locals With Ternary Operator

Locals can be used together with the Ternary operator to assign a conditional value to a local variable.

This can be e.g. useful if you want to differentiate the instance count of EC2 instances in a development vs. production environment.

locals {
  ec2_count = var.stage == "production" ? 3 : 1
}

resource "aws_instance" "my_instance" {
  ami           = "ami-005e54dee72cc1d00"
  instance_type = "t2.micro"

  count = local.ec2_count
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
gdenn
Dennis Groß (he/him)

Posted on December 20, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Use locals with Terraform
terraform Use locals with Terraform

December 20, 2022

How to configure Provider in Terraform
terraform How to configure Provider in Terraform

December 19, 2022

How to use templates in Terraform
terraform How to use templates in Terraform

December 18, 2022

How to use count in Terraform
terraform How to use count in Terraform

December 18, 2022