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}"
}
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
}
Top comments (0)