thinkingmonster thinkingmonster - 1 year ago 360
Python Question

using regex in jinja 2 for ansible playbooks

HI i am new to jinja2 and trying to use regular expression as shown below

{% if ansible_hostname == 'uat' %}
{% set server = '' %}

{% 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?

Answer Source

So after googling for long time and with the help of some bloggers here is the final solution to my problem:-

1. Jinja2 is not having any filter for finding sub-string or regexp so only solution was to create a custom filter i followed below steps to fix my problem.

2. Inside root directory of my playbook, i created a directory "filter_plugins" and wrote custom module in python and placed the file inside this directory.Name of the python file can be anything.My python code looks as below

 __author__ = 'akthakur'
class FilterModule(object):
    ''' Custom filters are loaded by FilterModule objects '''

    def filters(self):
        ''' Filter Module objects return a dict mapping filter names to
            filter functions. '''
        return {
            'substr': self.substr,

        ''' def substr(self, check,checkin):
        return value1+value2'''
    def substr(self,check,checkin):
         if check in checkin:
            return True
            return False

3. Now once this file is created our brand new filter "substr" is ready to be used and can be used inside template as shown below.

{% if 5==5 %}
 {% set server = '' %}
{% endif %}
{% if 'thinking' | substr(server) %}
   {% set ssl_cert = 'abc.crt'%}
{% endif %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download