π Terraform Series β Day 10

Conditional Expressions (Ternary Operator)
π Abstract
In real-world DevOps projects, infrastructure often needs to behave differently based on environments such as development, staging, and production. Instead of writing separate configurations, Terraform provides conditional expressions (ternary operators) to dynamically assign values.
This blog explains how to use conditional expressions in Terraform to make infrastructure more flexible, reusable, and environment-aware.
π― Objectives
After completing this blog, you will be able to:
Understand conditional expressions in Terraform
Use the ternary operator syntax
Apply conditions in real resources (EC2 example)
Configure infrastructure based on environment (
dev,prod)Test and verify conditional logic
π· Step 1: What is a Conditional Expression?
A conditional expression (also called a ternary operator) is used to assign values based on a condition.
π§ Syntax
condition ? true_value : false_value
π Meaning
If condition is true β use
true_valueIf condition is false β use
false_value
π· Step 2: Real Example (EC2 Root Volume)
root_block_device {
volume_size = var.env == "prod" ? 20 : var.ec2_root_default_storage_size
volume_type = "gp3"
}
π§ Logic Explained
If
env = "prod"β volume size = 20 GBElse β volume size = default value (10 GB)
π This helps in automatically adjusting infrastructure based on environment
π· Step 3: Variables Used
variable "env" {
default = "dev" or # "prod"
type = string
}
variable "ec2_root_default_storage_size" {
default = 10
type = number
}
π· Step 4: Testing the Conditional Expression
β Case 1: Production Environment
env = "prod"
π Output Behavior
Condition β
trueVolume Size β 20 GB
β Instance will be created with larger storage (production-ready)
β Case 2: Development Environment
env = "dev"
π Output Behavior
Condition β
falseVolume Size β 10 GB
β Instance will be created with default storage (cost-saving)
π· Step 5: Why Use Conditional Expressions?
Using conditional expressions helps in:
Reducing duplicate code
Managing multiple environments easily
Improving infrastructure flexibility
Writing clean and reusable Terraform code
π· Step 6: Best Practices
Use conditions for environment-based configurations
Keep values simple and readable
Avoid overly complex nested conditions
Combine with variables for better control
π Conclusion
Conditional expressions allow dynamic value assignment
Syntax is simple:
condition ? true_value : false_valueUseful for handling prod vs dev differences
Makes Terraform code clean, scalable, and reusable
π¨βπ» About the Author
βA complete Terraform series covering everything from fundamentals to advanced real-world infrastructure automation in a DevOps environment.β
π¬ Let's Stay Connected
π§ Email: gujjarapurv181@gmail.com
π GitHub: github.com/ApurvGujjar07
πΌ LinkedIn: linkedin.com/in/apurv-gujjar





