Using default value if string is empty
This little python trick works great in Ansible.
Let’s say you want to set foo to value of the bar, but only if bar is not empty. If bar is empty, you want to use other value (f.e. string “nothing”).
Normally you write an ugly jinja:
{% if bar!= "" %}{{ bar }}{% else %}nothing{% endif %}
But there is a much better way!
{{ bar or "nothing" }}
This trick uses python or
operator, which return either first value, or second, depending on the truthiness of the first expression. Empty string, empty set, empty list, empty dict, None, all of them are cast to ‘false’, therefore, or
returns second expression.
This trick is especially useful with env
lookup plugin. It returns empty string in environment variable is absent.
foo: '{{ lookup("env", "BAR") or "bar not found" }}'
Big update
Alexey Miasoedov has pointed out in comments, that Ansible’s default
filter has a second option for this case specifically.
Silly me, missed this in the docs.
foo: '{{ lookup("env", "BAR")|d("bar not found", true) }}'
The true
as a second option to default make it applied if left value is falsifiable (is not truthful).
Funny enough, my example is a bit concise and (at my opinion) more expressive.