eddyP23
eddyP23

Reputation: 6863

Ansible yml changes quotes

Using Ansible, in my role, I have defined a variable (defaults/main.yml):

someHosts: "[ \"{{ hosts| join(':' + port + '\", \"') }}:{{ port }}\" ]"

which basically given hosts=["host1", "host2"] and port=5050 is meant to turn the above into:

["host1:5050", "host2:5050"]

No I am using it in my jinja2 template file (*.j2) with template module. My template file has the following line:

  hosts => {{ someHosts }}

But now after running it I see the following on the actual machine (with less):

['host1:5050', 'host2:5050']

Why on earth and how did it change double quotes to single quotes?

EDIT/ANSWER

Building on @techraf's answer, this is what I came up with:

someHosts: "{{ hosts | zip_longest([], fillvalue=':' + port) | map('join') | list | to_json }}"

Upvotes: 0

Views: 852

Answers (2)

ady8531
ady8531

Reputation: 678

If using template:

[{% for host in groups['mygroup']%}
    "{{ host }}:{{port}}"{% if not loop.last %},{% endif %}
 {% endfor %}]

All you have to do is to define or replace mygroup with your group.

Upvotes: 1

techraf
techraf

Reputation: 68629

Why on earth and how did it change double quotes to single quotes?

Because you created a list object not a string; and this is how Jinja2 renders lists of string.

See for yourself by adding:

- debug:
    var: someHosts|type_debug

You get:

ok: [localhost] => {
    "someHosts|type_debug": "list"
}

If your question was however, how to get that list in JSON format, then your template should be:

hosts => {{ someHosts | to_json }}

Upvotes: 3

Related Questions