Skip to main content
In this lesson you’ll learn the common operators available in Terraform and how to use conditional (ternary) expressions to choose values based on runtime inputs. These constructs are useful when writing dynamic configuration, validating values, or simplifying logic without creating additional resources.
A purple presentation slide with layered hexagon shapes and centered white text that reads "Operators & Conditional Expressions." It appears to be a title slide for a talk or lesson.

Supported operator categories

Terraform supports arithmetic, equality, comparison, and logical operators. You can experiment interactively using the terraform console command. Note: equality checks can compare values of any type, but comparing values of different types (for example, a number vs a string) will evaluate to false.

Equality and comparison examples

Try these examples with terraform console to validate behavior:
Corresponding variables:

Logical operators

  • AND: && — returns true only if both operands are true.
    • Example: 8 > 7 && 8 < 10 is true.
  • OR: || — returns true if either operand is true.
    • Example: 8 > 9 || 8 < 10 is true (second condition is true).
  • NOT: ! — inverts a Boolean value.
    • Example: if var.special = true, then !var.special is false.
Interactive console examples:

Conditional expressions (ternary operator)

Terraform provides a conditional expression (ternary) to select between two values inline: condition ? true_val : false_val Use conditional expressions to determine values inside resource arguments, locals, or outputs without creating conditional resources. Important: both true_val and false_val must be expressions that produce compatible types because the conditional expression must evaluate to a single consistent type.
The true and false branches of a conditional expression must produce compatible types. For example, both should be numbers, both strings, or both lists containing the same element type.

Practical example — password length validation

Use a conditional expression to ensure a generated password has a minimum length (8 characters). If the user supplies a smaller length, Terraform will use 8 instead. variables.tf:
main.tf:
Shell equivalent (for conceptual comparison):

Apply and validate

Initialize and apply your configuration while passing a small length (for example, 5). Terraform will evaluate the conditional and choose 8:
If you pass -var=length=12, Terraform will use 12 because it satisfies the condition.
  • terraform console — interactive REPL for testing expressions and functions.
  • random_password resource — from the random provider (useful for short-lived secrets).
  • For more operator details and expression syntax, see the official Terraform documentation:
That covers the basic operators and how to use conditional expressions in Terraform to select values based on input or calculated conditions.

Watch Video