BacklogZero®

Ansible in a Minute · Ansible Core ·

Use ternary to choose a value for true or false

Short answer

Use the ternary filter to return one value when a test is true and another when it is false.

Subscribe for updates

Get an email whenever we publish new guides and blog posts. Unsubscribe anytime.

By subscribing you agree we may email you about Ansible in a Minute and related Level Up Labs updates. We store your address in the same lead sheet as our contact form.

Request

print restart when status is needs_restart, otherwise print continue

Example

A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.

YAML
---
- name: Choose restart or continue with ternary
  hosts: all
  gather_facts: false
  vars:
    status: needs_restart
  tasks:
    - name: Print the action
      ansible.builtin.debug:
        msg: "{{ (status == 'needs_restart') | ternary('restart', 'continue') }}"

How it works

ternary evaluates the expression on the left. It returns the first argument when the expression is true and the second argument when the expression is false.

When to use it

  • Mapping a boolean or comparison to a command or state string
  • Choosing one of two values in a template without a long if expression

Requirements

  • Ansible: >=2.14

Validation

  • Syntax validated
  • Not execution-tested
  • Last verified 2026-09-17

Notes

From Ansible 2.8 you can pass a third argument for null. enabled | ternary('no shutdown', 'shutdown', omit) returns omit when enabled is none. Without the third argument, none is treated as false.

Reference

Built for every Ansible use case in every organization

BacklogZero can generate this kind of automation in your environment, just like it did here.

Get BacklogZero today

Related guides

Back to Ansible in a Minute

Use ternary to choose a value for true or false · Level Up Labs