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!
Ansible uses Jinja2 templating to enable dynamic expressions and access to variables and facts.
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 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.
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.
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.
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