Terraform Conditional Expressions Explained Simply
Conditional expressions in Terraform allow you to dynamically choose values based on logic. They help you build flexible infrastructure code that adapts to different environments, inputs, and deployment requirements without duplicating configuration.
If you've ever needed to deploy different instance sizes for development and production environments, enable resources only when a feature flag is set, or enforce configuration standards automatically, you'll use conditional expressions regularly.
In this guide, you'll learn how conditional expressions work, how logical operators support them, and how to use them in real Terraform projects.
Before continuing, make sure you're familiar with Terraform variables and the basics of Terraform configuration syntax.
What Are Conditional Expressions in Terraform?
A conditional expression evaluates a condition and returns one of two values depending on whether the condition is true or false.
Terraform uses a syntax similar to the ternary operator found in many programming languages:
condition ? true_value : false_value
The expression works as follows:
- If the condition evaluates to
true, Terraform returnstrue_value. - If the condition evaluates to
false, Terraform returnsfalse_value.
This makes Terraform configurations more reusable and easier to maintain because you can make decisions directly inside your code.
Operators You Need Before Using Conditional Expressions
Conditional expressions rely on comparison and logical operators. Understanding these operators makes it easier to write and troubleshoot Terraform logic.
Arithmetic Operators
Terraform supports standard arithmetic operations:
5 + 2 # 7
10 - 3 # 7
4 * 2 # 8
8 / 2 # 4
While arithmetic operators are not conditional expressions themselves, they're often used to calculate values that later become part of a condition.
Equality and Comparison Operators
Comparison operators return either true or false.
5 == 5 # true
"5" == 5 # false
7 < 10 # true
10 >= 5 # true
Common comparison operators include:
==Equal to!=Not equal to>Greater than<Less than>=Greater than or equal to<=Less than or equal to
Terraform Logical Operators Explained
Logical operators allow you to combine multiple conditions.
AND (&&)
Returns true only when both conditions are true.
true && false
Output:
false
Real-world example:
var.environment == "prod" && var.enable_monitoring
This condition returns true only when the deployment is production and monitoring is enabled.
OR (||)
Returns true when at least one condition is true.
true || false
Output:
true
Example:
var.environment == "prod" || var.environment == "staging"
NOT (!)
Reverses the result of a Boolean value.
!true
Output:
false
Another example:
!false
Output:
true
Logical operators become especially useful when building more advanced conditional expressions.
How Conditional Expressions Work in Terraform
Terraform evaluates the condition first.
If the condition is true, Terraform returns the value before the colon. If it's false, Terraform returns the value after the colon.
Example:
var.environment == "prod" ? "t3.large" : "t3.micro"
In this example:
- Production environments receive a larger EC2 instance.
- Non-production environments receive a smaller and less expensive instance.
This pattern is common in production Terraform code because it helps reduce costs while maintaining performance where needed.
Practical Example: Enforcing Minimum Password Length
Suppose you're using the Random provider to generate passwords and want to enforce a minimum password length.
Step 1: Define the Variable
variable "length" {
type = number
}
Step 2: Use a Conditional Expression
resource "random_password" "default" {
length = var.length < 8 ? 8 : var.length
special = true
}
What happens here?
- If a user provides
5, Terraform uses8. - If a user provides
12, Terraform uses12. - Passwords are never created with fewer than 8 characters.
This approach keeps validation logic inside the configuration instead of relying on external scripts.
Real-World Example: Environment-Based Instance Sizing
A common pattern is using conditional expressions to select infrastructure sizes based on the deployment environment.
variable "environment" {
default = "dev"
}
resource "aws_instance" "example" {
ami = "ami-xxxxxxxx"
instance_type = var.environment == "prod" ? "t3.large" : "t3.micro"
}
Benefits:
- Lower costs in development environments.
- Larger instances in production.
- Single reusable Terraform configuration.
If you're provisioning AWS resources, check out:
Using Conditional Expressions with Count
One of the most common production use cases is controlling whether a resource should exist.
variable "enable_logging" {
default = true
}
resource "aws_s3_bucket" "logs" {
count = var.enable_logging ? 1 : 0
bucket = "application-logs-bucket"
}
When enable_logging is true, Terraform creates the bucket.
When it's false, Terraform skips the resource entirely.
For a deeper understanding of this pattern, read the guide on using count meta-argument in Terraform.
Combining Variables and Conditional Logic
You can combine comparison operators and logical operators in a single expression.
variable "a" {
default = 5
}
variable "b" {
default = 10
}
output "result" {
value = var.a < var.b && var.a > 0 ? "Valid input" : "Invalid input"
}
Terraform evaluates both conditions:
var.a < var.bvar.a > 0
If both are true, the output becomes:
Valid input
In real projects, these expressions are often combined with Terraform functions such as length(), contains(), lookup(), and try().
Common Mistakes When Using Conditional Expressions
Returning Different Data Types
Both branches should return compatible types.
Incorrect:
var.enabled ? "enabled" : 0
Correct:
var.enabled ? "enabled" : "disabled"
Overcomplicating Expressions
Avoid deeply nested conditional expressions when readability starts to suffer.
Instead of writing complex one-line expressions, consider using local values.
locals {
instance_type = var.environment == "prod" ? "t3.large" : "t3.micro"
}
Forgetting Operator Precedence
When combining multiple conditions, use parentheses where appropriate.
(var.environment == "prod" || var.environment == "staging") && var.enable_monitoring
This makes your intent clearer and reduces mistakes.
Pro Tip: Type Compatibility Matters
Pro Tip
Terraform expects conditional expressions to return compatible data types. Returning a string in one branch and a number in another branch can cause validation errors or unexpected behavior.
When in doubt, keep both return values the same type.
Test Conditional Expressions with Terraform Console
The terraform console command is one of the fastest ways to test expressions.
Example:
> 5 < 8 ? "Yes" : "No"
"Yes"
You can also test logical operators:
> true && false
false
Or more advanced expressions:
> "prod" == "prod" ? "Deploy" : "Skip"
"Deploy"
The console is particularly useful when troubleshooting complex expressions before running terraform plan.
Learn more from the official Terraform CLI documentation.
Best Practices for Terraform Conditional Expressions
Follow these guidelines to keep your code maintainable:
- Keep expressions simple and readable.
- Use local values for complex logic.
- Prefer descriptive variable names.
- Test expressions with
terraform console. - Ensure both return values are compatible types.
- Add comments when business logic isn't obvious.
Conditional expressions become even more powerful when combined with:
You can also explore the official Terraform language documentation and the Terraform Registry for provider-specific examples.
Frequently Asked Questions (FAQs)
What is a conditional expression in Terraform?
A conditional expression allows Terraform to return different values depending on whether a condition evaluates to true or false.
Is a conditional expression the same as a ternary operator?
Yes. Terraform's conditional expression syntax follows the same concept as the ternary operator used in many programming languages.
Can I use conditional expressions inside resource blocks?
Yes. They're commonly used for resource arguments such as instance types, tags, counts, and feature toggles.
Can conditional expressions be used with count?
Yes. A common pattern is:
count = var.enabled ? 1 : 0
This creates a resource only when the condition is true.
How do I test conditional expressions safely?
Use the terraform console command. It lets you evaluate expressions without modifying infrastructure.
Can I combine logical operators with conditional expressions?
Yes. Terraform supports:
&&(AND)||(OR)!(NOT)
These operators can be combined to build more advanced conditions.
Final Thoughts
Conditional expressions are one of the most practical features in Terraform. They help reduce duplication, enforce standards, enable optional resources, and adapt infrastructure to different environments.
Once you're comfortable with them, you'll find yourself using conditional expressions alongside variables, functions, modules, count, and for_each in almost every Terraform project.
8 free, 100% client-side tools for developers — no signup, no data uploads.
Explore all tools