9

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
  • 15,396
  • 12
  • 109
  • 124
Karl
  • 2,903
  • 5
  • 27
  • 43

4 Answers4

9

Why not simply join it with the quotes?

"{{ hosts | join('", "') }}"
udondan
  • 57,263
  • 20
  • 190
  • 175
  • 2
    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
  • 2
    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
  • still works you just need to escape the quotes `joined_string: "{{ hosts | join('\", \"') }}"` missing first and last quotes need to be added when you use the string `new_string: " '"' + {{ joined_string }} + '"' "` – Arno Dec 13 '22 at 15:25
4

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
  • 7,101
  • 4
  • 43
  • 56
3

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
  • 51
  • 2
  • Maybe my context is different, but this only worked for me after removing the excessive quoting/escaping: `{{ hosts | map("regex_replace","(.+)","\1") | join(',')}}` - but this was definitely useful. – bitinerant Jun 28 '22 at 08:13
0

From a json file file_name.json array like this

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

Set_fact from a json file

- name: Set variables from parameters file
  set_fact:
    vars_from_json: "{{ lookup('file', 'file_name.json') | from_json }}"

Use join with double quote and comma, and wrap all around in double quote

- name: Create host list
  set_fact:    
    host_list: "{{ '\"' + vars_from_json.hosts | join('\"'', ''\"') + '\"' }}"
sebo
  • 1