Process Flow - Conditional expressions (ternary)
Evaluate condition
Use true
Result assigned
The ternary expression checks a condition and picks one of two values based on whether the condition is true or false.
variable "env" { default = "prod" } output "instance_type" { value = var.env == "prod" ? "t3.large" : "t3.micro" }
| Step | Condition | Condition Result | Value if True | Value if False | Chosen Value |
|---|---|---|---|---|---|
| 1 | var.env == "prod" | True | "t3.large" | "t3.micro" | "t3.large" |
| 2 | var.env == "dev" | False | "t3.large" | "t3.micro" | "t3.micro" |
| 3 | var.env == "test" | False | "t3.large" | "t3.micro" | "t3.micro" |
| 4 | var.env == "prod" | True | "t3.large" | "t3.micro" | "t3.large" |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 |
|---|---|---|---|---|---|
| var.env | "prod" | "prod" | "dev" | "test" | "prod" |
| Chosen Value | N/A | "t3.large" | "t3.micro" | "t3.micro" | "t3.large" |
Terraform conditional expressions use the syntax: condition ? true_value : false_value They evaluate the condition once and return true_value if true, else false_value. Useful for setting resource properties based on variables. Condition must be boolean. Example: var.env == "prod" ? "t3.large" : "t3.micro"
var.is_production ? "prod" : "dev"variable "env" { default = "test" }
output "message" {
value = var.env == "prod" ? "Deploy to production" : "Deploy to staging"
}output "result" {
value = var.enabled ? "yes" "no"
}var.env == "" || var.env == null ? "default" : var.env
Pass the test and this pattern moves unknown