Ansible ternary Filter: Inline If-Else Conditions in Jinja2 (Guide)
By Luca Berton · Published 2024-01-01 · Category: installation
Complete guide to Ansible ternary filter. Write inline if-else conditions in Jinja2 templates and variable assignments. Handle boolean logic, undefined variables, nested conditions, and default values with practical examples.
The ternary filter is Ansible's inline if-else — it returns one value when a condition is true, another when false. It replaces verbose when + set_fact patterns with a single expression.
Basic Syntax
Common Patterns
Boolean to String
Environment-Based Config
Conditional Package Names
Conditional Service Names
Three-Value Ternary (with None/Undefined)
The ternary filter accepts a third argument for None values:
Nested Ternary (Multiple Conditions)
Cleaner with Jinja2 if/elif:
ternary in Templates
ternary in Loops
ternary with Default Values
ternary vs when vs Jinja2 if
| Pattern | Best For | |---------|----------| | ternary | Inline value selection in a single expression | | when | Skip/run entire tasks conditionally | | Jinja2 {% if %} | Multi-line template logic | | default() | Provide fallback for undefined variables |
FAQ
What is the Ansible ternary filter?
The ternary filter is a Jinja2 filter that returns one of two (or three) values based on a boolean condition. Syntax: {{ condition | ternary(true_value, false_value) }}. It's equivalent to the ternary operator (?:) in other programming languages.
Can I chain multiple ternary filters?
Yes, but nested ternary filters become unreadable fast. For 2 conditions, nesting is fine. For 3+, use Jinja2 {% if %}{% elif %}{% else %} blocks or a dictionary lookup:
Does ternary work with undefined variables?
If the condition variable is undefined, ternary raises an error. Always use default() or is defined check:
What's the difference between ternary and the Jinja2 inline if?
They're equivalent. Jinja2 also supports inline if: {{ 'yes' if condition else 'no' }}. The ternary filter is more Ansible-idiomatic; inline if is standard Jinja2. Both work.
Conclusion
The ternary filter is the cleanest way to write inline conditionals in Ansible. Use it for variable assignments, template values, and anywhere you need a one-liner if-else. For complex multi-branch logic, switch to Jinja2 {% if %} blocks or dictionary lookups.
Related Articles • Ansible Conditionals and when Guide • Ansible map vs selectattr vs json_query Guide • Ansible set_fact vs vars vs extra_vars Guide • Ansible Jinja2 Templates Guide
Category: installation