Based on already given answers under
I've found the following approach
---
- hosts: localhost
become: false
gather_facts: false
vars:
input:
0: '0'
1: '1'
tasks:
- set_fact:
conditionalVar: "{{ 'v1' if (input.1 == '1') else 'v2' if (input.0 != '1' and input.1 != '2') else 'v3' if (input.0 == '2') }}"
- name: Show value
debug:
msg: "{{ conditionalVar }}"
resulting into an output of
TASK [Show value] ***
ok: [localhost] =>
msg: v1
for
input:
0: '0'
1: '1'
TASK [Show value] ***
ok: [localhost] =>
msg: v2
for
input:
0: '0'
1: '0'
and
TASK [Show value] ***
ok: [localhost] =>
msg: v3
for
input:
0: '2'
1: '2'
To prevent runtime errors like
TASK [set_fact] ***************************************************************************************************************************************
fatal: [localhost]: FAILED! =>
msg: |-
The task includes an option with an undefined variable. The error was: the inline if-expression on line 1 evaluated to false and no else section was defined.
as for
input:
0: '1'
1: '0'
one could implement an additional cleanup statement which comes in place if no condition is met.
- set_fact:
conditionalVar: "{{ 'v1' if (input.1 == '1')
else 'v2' if (input.0 != '1' and input.1 != '2')
else 'v3' if (input.0 == '2')
else '' }}"