Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use jinja2 to join with quotes in Ansible?

Tags:

ansible

I have an ansible list value:

hosts = ["site1", "site2", "site3"]

if I try this:

hosts | join(", ")

I get:

site1, site2, site3

But I want to get:

"site1", "site2", "site3"
like image 1000
Karl Avatar asked Jul 13 '16 13:07

Karl


3 Answers

Why not simply join it with the quotes?

"{{ hosts | join('", "') }}"
like image 178
udondan Avatar answered Oct 23 '22 11:10

udondan


Ansible has a to_json, to_nice_json, or a to_yaml in it's filters:

{{ some_variable | to_json }}
{{ some_variable | to_yaml }}

Useful if you are outputting a JSON/YAML or even (it's a bit cheeky, but JSON mostly works) a python config file (ie Django settings).

For reference: https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#filters-for-formatting-data

like image 32
Danny Staple Avatar answered Oct 23 '22 12:10

Danny Staple


The previous answer leaves "" if the list is empty. There is another approach that may be more robust, e.g. for assigning the joined list as a string to a different variable (example with single quotes):

{{ hosts | map("regex_replace","(.+)","\'\\1\'") | join(',')}}
like image 2
Notabee Avatar answered Oct 23 '22 11:10

Notabee