How to Use Conditional Expression in Terraform
In Terraform, use a
conditional expression with the syntax condition ? true_value : false_value to choose values based on a condition. This lets you set resource properties dynamically depending on variables or other inputs.Syntax
The conditional expression in Terraform uses the format condition ? true_value : false_value. Here, condition is a boolean expression that evaluates to true or false. If true, Terraform uses true_value; if false, it uses false_value.
This is useful for setting values dynamically based on input or environment.
terraform
variable "is_production" { type = bool default = false } output "instance_type" { value = var.is_production ? "t3.large" : "t3.micro" }
Example
This example shows how to select an AWS instance type based on whether the environment is production or not. If is_production is true, it uses a larger instance; otherwise, a smaller one.
terraform
variable "is_production" { type = bool default = true } output "selected_instance_type" { value = var.is_production ? "t3.large" : "t3.micro" }
Output
selected_instance_type = "t3.large"
Common Pitfalls
Common mistakes include:
- Using non-boolean expressions as the condition, which causes errors.
- Forgetting the colon
:between true and false values. - Using complex expressions without parentheses, leading to unexpected results.
Always ensure the condition is boolean and the syntax is exactly condition ? true_value : false_value.
terraform
/* Wrong: missing colon */ output "wrong_example" { value = var.is_production ? "t3.large" "t3.micro" } /* Correct: includes colon */ output "correct_example" { value = var.is_production ? "t3.large" : "t3.micro" }
Quick Reference
| Part | Description |
|---|---|
| condition | A boolean expression that evaluates to true or false |
| ? | Separates the condition from the true value |
| true_value | Value used if condition is true |
| : | Separates the true value from the false value |
| false_value | Value used if condition is false |
Key Takeaways
Use the syntax condition ? true_value : false_value for conditional expressions in Terraform.
The condition must be a boolean expression to avoid errors.
Conditional expressions help make configurations flexible and environment-aware.
Always include the colon ':' between true and false values.
Test expressions with simple outputs to verify correctness.