HI i am new to jinja2 and trying to use regular expression as shown below
{% if ansible_hostname == 'uat' %}
{% set server = 'thinkingmonster.com' %}
{% else %}
{% set server = 'define yourself' %}
{% endif %}
{% if {{ server }} match('*thinking*') %}
{% set ssl_certificate = 'akash' %}
{% elif {{ server }} match( '*sleeping*')%}
{% set ssl_certificate = 'akashthakur' %}
{% endif %}
based on the value of "server" i would like to evaluate as which certificates to use. ie if domain contains "thinking" keyword then use these certificates and if it contains "sleeping" keyword then use that certificate.
But didn't found any jinja2 filter supporting this. Please help me.I found some python code and sure that can work but how to use python in jinja2 templates?
Ansible uses Jinja2 templating to enable dynamic expressions and access to variables and facts.
regex - Extracting part of the string using Ansible regex_search and save the output as a variable - Server Fault.
Jinja2 filter is something we use to transform data held in variables. We apply filters by placing pipe symbol | after the variable followed by name of the filter. Filters can change the look and format of the source data, or even generate new data derived from the input values.
Jinja2 templates are simple template files that store variables that can change from time to time. When Playbooks are executed, these variables get replaced by actual values defined in Ansible Playbooks. This way, templating offers an efficient and flexible solution to create or alter configuration file with ease.
Jinja2 can quite easily do substr checks with a simple 'in' comparison, e.g.
{% set server = 'www.thinkingmonster.com' %}
{% if 'thinking' in server %}
do something...
{% endif %}
So your substring regex filter isn't required. However if you want more advanced regex matching, then there are in fact filters available in ansible - see the regex filters in http://docs.ansible.com/playbooks_filters.html#other-useful-filters - funnily enough, your match syntax above is nearly exactly right.
+1 for Bereal's answer though, it gives a nice alternative in the form of a map.
There is a "regex_replace" filter available in Ansible>1.6
Other Useful Filters Scroll down and you'll see this:
New in version 1.6.
To replace text in a string with regex, use the “regex_replace” filter:
# convert "ansible" to "able"
{{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\\1') }}
# convert "foobar" to "bar"
{{ 'foobar' | regex_replace('^f.*o(.*)$', '\\1') }}
# convert "localhost:80" to "localhost, 80" using named groups
{{ 'localhost:80' | regex_replace('^(?P<host>.+):(?P<port>\\d+)$', '\\g<host>, \\g<port>') }}
That being said, regex is overkill for finding a solution to this particular problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With