Conditional Expressions
A conditional expression picks one of two values from a true-or-false test. It has the shape condition ? value if true : value if false.
Pick a size
Prod gets the large size. Every other environment gets the small size.
variable "environment" {
type = string
default = "dev"
}
locals {
size = var.environment == "prod" ? "large" : "small"
}
output "size" {
value = local.size
}Pick a name
The same pattern works for names. The test decides which string is used.
locals {
name = var.environment == "prod" ? "app-prod" : "app-dev"
}
output "name" {
value = local.name
}Turn a resource on or off
A count of 1 creates the resource. A count of 0 skips it.
resource "local_file" "backup" {
count = var.environment == "prod" ? 1 : 0
content = "Backup enabled."
filename = "${path.module}/backup.txt"
}Example
variable "environment" {
type = string
default = "dev"
}
locals {
size = var.environment == "prod" ? "large" : "small"
message = var.environment == "prod" ? "Prod is large." : "Dev is small."
}
resource "local_file" "report" {
content = "${local.message} Size: ${local.size}."
filename = "${path.module}/report.txt"
}
output "message" {
value = local.message
}
output "size" {
value = local.size
}Key points
- The condition must be true or false.
- Terraform picks the first value when the condition is true.
- Terraform picks the second value when the condition is false.
- Both values should be the same type.
- A conditional can choose a size, a name, or a count.
- One resource can take two shapes from one block of code.
The environment is dev, so both tests are false. Each conditional picks its second value, and the file records the small size.
Note
A conditional with different types on each side is an error.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What does var.environment == "prod" ? "large" : "small" return when the environment is dev?