Course contentsShow
← Cloud and Infrastructure
Lesson 737 of 2,98914. Terraform FundamentalsFree lesson

Conditional Expressions

Using the ternary operator (condition ? true_val : false_val) for conditional logic in configurations.

Conditional Expressions

What you'll learn: How to use Terraform's ternary operator to make your infrastructure configurations dynamically choose between values based on conditions.

The Core Idea

In Terraform, a conditional expression lets you pick one value or another based on whether a condition is true or false. Think of it like a fork in the road: if a condition is met, go left (use value A); otherwise, go right (use value B).

The syntax follows the ternary operator pattern you may have seen in programming:

condition ? true_val : false_val

If condition evaluates to true, Terraform uses true_val. If condition is false, it uses false_val.

Real-World Analogy

Imagine ordering coffee: "If it's cold outside, give me hot coffee; otherwise, give me iced coffee." The condition is the weather, and the outcome is your drink choice. Conditional expressions work the same way in your infrastructure code.

Practical Examples

Choosing instance size based on environment:

instance_type = var.environment == "production" ? "t3.large" : "t3.micro"

Setting resource count conditionally:

count = var.enable_monitoring ? 1 : 0

Dynamic tagging:

Name = var.is_public ? "public-server" : "private-server"

You can use any expression or operator you've learned as the condition: equality checks (==), comparisons (>, <), or boolean logic.

Why This Matters

Conditional expressions make your Terraform configurations flexible and reusable. Instead of writing separate configurations for development and production, you use one configuration that adapts based on variables.

Key Takeaway: Terraform's conditional expressions use the ternary operator condition ? true_val : false_val to dynamically select values, enabling flexible, environment-aware infrastructure configurations without code duplication.