
Supported operator categories
Terraform supports arithmetic, equality, comparison, and logical operators. You can experiment interactively using the terraform console command.| Operator type | Operators | Description | Example | ||
|---|---|---|---|---|---|
| Equality / Inequality | ==, != | Test whether values are exactly equal or not equal. Works with strings, numbers, lists, maps, etc. | "a" == "a" → true | ||
| Comparison | >, <, >=, <= | Numeric comparisons that return a Boolean. | 5 > 3 → true | ||
| Logical | &&, ` | , !` | Combine Boolean expressions (AND, OR, NOT). | true && false → false | |
| Arithmetic | +, -, *, /, % | Numeric operations. | 2 + 3 → 5 |
Equality and comparison examples
Try these examples with terraform console to validate behavior:Logical operators
- AND:
&&— returns true only if both operands are true.- Example:
8 > 7 && 8 < 10is true.
- Example:
- OR:
||— returns true if either operand is true.- Example:
8 > 9 || 8 < 10is true (second condition is true).
- Example:
- NOT:
!— inverts a Boolean value.- Example: if
var.special = true, then!var.specialis false.
- Example: if
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: bothtrue_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:Apply and validate
Initialize and apply your configuration while passing a small length (for example, 5). Terraform will evaluate the conditional and choose 8:-var=length=12, Terraform will use 12 because it satisfies the condition.
Quick reference and links
- 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: