How to Use Ternary Operator in Terraform: Syntax and Examples
condition ? true_value : false_value syntax for ternary operations to choose between two values based on a condition. This lets you write simple conditional logic inline within your configuration.Syntax
The ternary operator in Terraform uses the pattern condition ? true_value : false_value. Here, condition is a boolean expression that evaluates to true or false. If true, Terraform returns true_value; if false, it returns false_value.
This operator helps you write concise conditional expressions without using full if blocks.
variable "is_production" { type = bool default = false } output "environment" { value = var.is_production ? "prod" : "dev" }
Example
This example shows how to use the ternary operator to set an instance type based on an environment variable. If is_production is true, it uses a larger instance; otherwise, a smaller one.
variable "is_production" { type = bool default = true } resource "aws_instance" "example" { ami = "ami-12345678" instance_type = var.is_production ? "t3.large" : "t3.micro" }
Common Pitfalls
Common mistakes include:
- Using non-boolean expressions as the condition.
- Forgetting the colon
:between true and false values. - Trying to use complex expressions without parentheses, which can cause errors.
Always ensure the condition is boolean and the syntax is exactly condition ? true_value : false_value.
/* Wrong: missing colon */ output "wrong_example" { value = var.is_production ? "prod" "dev" } /* Correct: includes colon */ output "correct_example" { value = var.is_production ? "prod" : "dev" }
Quick Reference
Use the ternary operator to simplify conditional logic in Terraform expressions. It works like a shortcut for if-else statements.
- Syntax:
condition ? true_value : false_value - Condition: Must be boolean
- Values: Can be any Terraform expression
- Use cases: Choosing resource properties, outputs, or variable defaults
Key Takeaways
condition ? true_value : false_value for inline conditional logic in Terraform.: separating true and false values.