ansible.builtin.ternary filter – Ternary operation filter

Note

This filter plugin is part of ansible-core and included in all Ansible installations. In most cases, you can use the short plugin name ternary. However, we recommend you use the Fully Qualified Collection Name (FQCN) ansible.builtin.ternary for easy linking to the plugin documentation and to avoid conflicting with other collections that may have the same filter plugin name.

Synopsis

  • Return the first value if the input is True, the second if False.

Input

This describes the input of the filter, the value before | ansible.builtin.ternary.

Parameter

Comments

Input

boolean / required

A boolean expression, must evaluate to True or False.

Choices:

  • false

  • true

Positional parameters

This describes positional parameters of the filter. These are the values positional1, positional2 and so on in the following example: input | ansible.builtin.ternary(positional1, positional2, ...)

Parameter

Comments

true_val

any / required

Value to return if the input is True.

false_val

any

Value to return if the input is False.

Keyword parameters

This describes keyword parameters of the filter. These are the values key1=value1, key2=value2 and so on in the following example: input | ansible.builtin.ternary(key1=value1, key2=value2, ...)

Parameter

Comments

none_val

any

added in Ansible 2.8

Value to return if the input is None. If not set, None will be treated as False.

Notes

Note

  • When keyword and positional parameters are used together, positional parameters must be listed before keyword parameters: input | ansible.builtin.ternary(positional1, positional2, key1=value1, key2=value2)

  • Vars as values are evaluated even when not returned. This is due to them being evaluated before being passed into the filter.

Examples

# set first 10 volumes rw, rest as dp
volume_mode: "{{ (item|int < 11)|ternary('rw', 'dp') }}"

# choose correct vpc subnet id, note that vars as values are evaluated even if not returned
vpc_subnet_id: "{{ (ec2_subnet_type == 'public') | ternary(ec2_vpc_public_subnet_id, ec2_vpc_private_subnet_id) }}"

- name: service-foo, use systemd module unless upstart is present, then use old service module
  service:
    state: restarted
    enabled: yes
    use: "{{ (ansible_service_mgr == 'upstart') | ternary('service', 'systemd') }}"

Return Value

Key

Description

Return value

any

The value indicated by the input.

Returned: success

Authors

  • Brian Coca (@bcoca)

Hint

Configuration entries for each entry type have a low to high priority order. For example, a variable that is lower in the list will override a variable that is higher up.