8

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"
slm
  • 14,096
  • 12
  • 98
  • 116
Karl
  • 2,483
  • 5
  • 24
  • 39

3 Answers3

6

Why not simply join it with the quotes?

"{{ hosts | join('", "') }}"
udondan
  • 52,841
  • 19
  • 186
  • 168
  • 1
    I know this is 4 years old, but ... This fails on the ther first and last entry of the list: You end up with site1", "site2", "site3 – Myles Merrell Jan 08 '21 at 02:46
  • 1
    That's why you have quotes around the whole thing. – udondan Jan 08 '21 at 08:45
  • wondering if this solution still works in the latest ansible. i did the test and getting error related to quotes. --We could be wrong, but this one looks like it might be an issue with missing quotes. Always quote template expression brackets when they start a value-- – Marek Feb 11 '22 at 02:48
3

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

Danny Staple
  • 6,697
  • 3
  • 42
  • 55
1

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(',')}}
Notabee
  • 11
  • 1