0
0
TerraformHow-ToBeginner · 3 min read

How to Use Ternary Operator in Terraform: Syntax and Examples

In Terraform, use the 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.

terraform
variable "is_production" {
  type    = bool
  default = false
}

output "environment" {
  value = var.is_production ? "prod" : "dev"
}
Output
environment = "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.

terraform
variable "is_production" {
  type    = bool
  default = true
}

resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = var.is_production ? "t3.large" : "t3.micro"
}
Output
Creates an AWS instance with type "t3.large" if is_production is true, else "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.

terraform
/* 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

Use the ternary operator condition ? true_value : false_value for inline conditional logic in Terraform.
The condition must be a boolean expression to avoid errors.
Always include the colon : separating true and false values.
Ternary expressions simplify your Terraform code by replacing longer if-else blocks.
Use parentheses for complex expressions to ensure correct evaluation.