Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add quotes to elemens of the list in jinja2 (ansible)

Tags:

ansible

jinja2

I have very simple line in the template:

ip={{ip|join(', ')}}

And I have list for ip:

ip:
 - 1.1.1.1
 - 2.2.2.2
 - 3.3.3.3

But application wants IPs with quotes (ip='1.1.1.1', '2.2.2.2').

I can do it like this:

ip:
 - "'1.1.1.1'"
 - "'2.2.2.2'"
 - "'3.3.3.3'"

But it is very ugly. Is any nice way to add quotes on each element of the list in ansible?

Thanks!

like image 823
George Shuklin Avatar asked Apr 09 '15 11:04

George Shuklin


People also ask

What is j2 Jinja2 used for in Ansible?

Ansible uses Jinja2 templating to enable dynamic expressions and access to variables and facts.

What is Jinja2 templating in Ansible?

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.

What is Jinja2 format?

What is Jinja 2? Jinja2 is a modern day templating language for Python developers. It was made after Django's template. It is used to create HTML, XML or other markup formats that are returned to the user via an HTTP request.


2 Answers

This will work :

ip={{ '\"' + ip|join('\", \"') + '\"' }}

A custom filter plugin will also work. In ansible.cfg uncomment filter_plugins and give it a path, where we put this

def wrap(list):
    return [ '"' + x + '"' for x in list]

class FilterModule(object):
    def filters(self):
        return {
            'wrap': wrap
        }

in a file called core.py. Like this. Then you can simply use

ip|wrap|join(', ')

And it should produce comma seperated list with each ip wrapped in quotes.

like image 198
Zasz Avatar answered Oct 16 '22 23:10

Zasz


Actually there is a very simple method to achieve this:

{{ mylist | map('quote') | join(', ') }}

The filter map iterates over every item and let quote process it. Afterwards you can easily join them together.

like image 28
Max Avatar answered Oct 17 '22 00:10

Max