DEV Community

Cover image for Use locals with Terraform
Dennis Groß (he/him)
Dennis Groß (he/him)

Posted on

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

Top comments (0)