Ansible: tips and tricks¶
Jinja foo filters¶
-
Strip down a string from any special chars
jinja2 {% set a = b | regex_replace ("[^A-Za-z0-9\-]","") %}That will remove all special char but
-. Also in the regex ([^A-Za-z0-9\-]) the last\-]could be turned into just-],-being the last char of that sequence it will be interpreted as a litteral value.
The truncate surprise feature...¶
-
How to truncate a string in a jinja template
jinja2 {% set hash_string = a | hash('sha1') %} {% set a = b | truncate(45, True, hash_string[-6:]) %}
In theory, if a | length exceeds 45 chars, jinja is supposed to truncate the string and replace the last 6 chars
the first 6 chars from the hash_string variable. But in real life, you might you see your string truncated only when
its length exceeds 45+5 chars...
Turns out, Jinja documentation around that filter says the following:
truncate(s, length=255, killwords=False, end='...', leeway=None)
We notice that leeway parameter that is supposed to fallback to None when unspecified, well... when reading carefully
what comes next, we can see an explanation in the following:
The default leeway on newer Jinja versions is 5 and was 0 before but can be reconfigured globally.
So to force truncate to effectively truncate when it should, set leeway=0, e.g:
{% set a = b | truncate(45, True, hash_string[-6:], 0) %}