Reputation: 3113
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"
Upvotes: 11
Views: 11272
Reputation: 59989
The best solution seems to be
hosts | map('quote') | join(', ')
You can also use the join
including the quotes, and ensure the whole expression is surrounded with quotes, to get the left and right outer quote. But this will leave empty quotes, in case the list is empty. Depending on your scenario:
"{{ hosts | join('", "') }}"
or
'"' + hosts | join('", "') + '"'
or
"'\"' + hosts | join('\", \"') + '\"'"
Upvotes: 12
Reputation: 1
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('\"'', ''\"') + '\"' }}"
Upvotes: 0
Reputation: 7332
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
Upvotes: 4
Reputation: 71
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(',')}}
Upvotes: 4