How to make sure Jinja2 templates used within Ansible plays / roles are prone to "false"
being evaluated to True
?
Background:
Boolean handling in Ansible is tricky and may lead to an unexpected results when used along with Jinja2 templating.
Turns out that Ansible handles differently "false"
value:
- When used in
when
clause it evaluates toFalse
- When used in Jinja2 template it evaluates to
True
Take a look at this simple example:
---
- name: Sample play
hosts: localhost
gather_facts: false
vars:
enabled: 'false'
tasks:
- name: Print enabled / disabled with Jinja2 inline condition
debug:
msg: "{{ 'enabled' if enabled else 'disabled' }}"
- name: Print enabled
debug:
msg: Enabled
when: enabled
First task prints enabled
even though variable is 'false'
, the second task skips:
PLAY [Sample play] *********************************************************************************************************************************************************************
TASK [Print enabled / disabled with Jinja2 inline condition] ***************************************************************************************************************************
ok: [localhost] => {
"msg": "enabled"
}
TASK [Print enabled] *******************************************************************************************************************************************************************
skipping: [localhost]