My playbook:
---
- hosts: "localhost"
connection: "local"
gather_facts: false
vars:
x: null
y:
z: null
var1: "{{ x }}"
var2: "{{ y.z }}"
tasks:
- debug:
msg: |
{% if (var1 | default(none)) is none %}
var1 is none/null
type: {{ var1 | type_debug }}
{% else %}
var1 is NOT none/null
type: {{ var1 | type_debug }}
value: [{{ var1 }}]
{% endif %}
- debug:
msg: |
{% if (var2 | default(none)) is none %}
var2 is none/null
type: {{ var2 | type_debug }}
{% else %}
var2 is NOT none/null
type: {{ var2 | type_debug }}
value: [{{ var2 }}]
{% endif %}
My test:
$ ansible --version
ansible [core 2.11.6]
config file = /workdir/ansible.cfg
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.8/site-packages/ansible
ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/local/bin/ansible
python version = 3.8.10 (default, Jun 23 2021, 15:19:53) [GCC 8.3.0]
jinja version = 3.0.3
libyaml = True
$ ansible-playbook quick.yml -i 'localhost,'
[WARNING]: Unable to parse localhost, as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the
implicit localhost does not match 'all'
PLAY [localhost] ********************************************************************
TASK [debug] ************************************************************************
ok: [localhost] => {
"msg": "var1 is none/null\ntype: NoneType\n"
}
TASK [debug] ************************************************************************
ok: [localhost] => {
"msg": "var2 is NOT none/null\ntype: str\nvalue: []\n"
}
PLAY RECAP **************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
- Why
var2
is notnone/null
? - How to pass/keep the
none/null
value tovar2
?
Solved:
export ANSIBLE_JINJA2_NATIVE=1
environment variable during the Ansible run.jinja2_native = 1
inansible.cfg
in the[defaults]
section.See https://docs.ansible.com/ansible/latest/reference_appendices/config.html#default-jinja2-native.
Note: jinja2_native option is enabled by default since ansible-core 2.12.0.