In Ansible playbooks, it is often a good practice to test if a variable exists and what is its value.
Particularity this helps to avoid different “VARIABLE IS NOT DEFINED” errors in Ansible playbooks.
In this context there are several useful tests that you can apply using Jinja2 filters in Ansible.
In this article, i’ll show the examples of how to test a variable in Ansible: if it exists or not, if it is empty or not and if it is set to True
or False
.
Cool Tip: Test if the variable in Jinja2 is Empty | Exists | Defined | True. Read more →
Ansible ‘When’ Statement: Check If Variable Is…
Check if Ansible variable is defined (exists):
tasks: - shell: echo "The variable 'foo' is defined: '{{ foo }}'" when: foo is defined - fail: msg="The variable 'bar' is not defined" when: bar is undefined
Check if Ansible variable is empty:
tasks: - fail: msg="The variable 'bar' is empty" when: bar|length == 0 - shell: echo "The variable 'foo' is not empty: '{{ foo }}'" when: foo|length > 0
Check if Ansible variable is defined and not empty:
tasks: - shell: echo "The variable 'foo' is defined and not empty" when: (foo is defined) and (foo|length > 0) - fail: msg="The variable 'bar' is not defined or empty" when: (bar is not defined) or (bar|length == 0)
Cool Tip: Ansible Playbook – Print Variable & List All Variables! Read more →
Check if Ansible variable is True or False:
tasks: - shell: echo "The variable 'foo' is 'True'" when: foo|bool == True - shell: echo "The variable 'bar' is 'False'" when: bar|bool == False
Maybe “when: for|length > 0” -> “when: foo|length > 0”..
btw. can True|False be replaced with 1|0?
Thanks. Yes, True|False can be replaced with 1|0.
Thanks for useful article.
There are two new jinja2 tests: truthy and falsy:
https://github.com/ansible/ansible/pull/62602
…actually, there *will be* (when Ansible 2.10 gets released).
Great article.
I found this also works well when testing if a defined variable is not empty.
fail:
msg: “foo is defined but empty”
when: not foo
from: https://stackoverflow.com/a/53362496/2413876
Thanks for a useful article.