How to remove the comma at the end of the line in ansible-template?

2.4k Views Asked by At

Can you tell me how to remove the comma at the end of the line?

Final output:

{name: "name1", My country = "region1a", My country = "region1b"},

{name: "name2", My country = "region2a", My country = "region2b"},

you only need to delete one (highlighted) comma at the end of the second line. The output is generated in this way

{% for country in AllСountry %}
{name: "{{ country }}",{% for count in lookup('vars', country) %} My country = "{{ count }}",{% if loop.last %} My country = "{{ count }}"{% endif %}{% endfor %}},
{% endfor %}

as a result, we need this output

{name: "name1", My country = "region1a", My country = "region1b"},
{name: "name2", My country = "region2a", My country = "region2b"}
1

There are 1 best solutions below

5
On BEST ANSWER

You could use loop.last for this, and so enclose you comma in a condition testing if you are looping on the last item or not.

You template would then end up being:

{% for country in AllСountry %}
{name: "{{ country }}",{% for count in lookup('vars', country) %} My country = "{{ count }}",{% if loop.last %} My country = "{{ count }}"{% endif %}{% endfor %}}{% if not loop.last %},{% endif %}
{% endfor %}

This said, and as raised on your other question, I feel like you are making things complex for yourself, what exactly are you trying to achieve? Are you trying to build a JSON? (in which case, please note that My country = "region2a" is invalid).

If you are indeed trying to construct a data structure, then you should create lists and dictionaries that represent those and then use simple existing filters like to_json, to_yaml, etc.

Otherwise, the point still apply: if you want to create a comma separated list of string, create a list of string in Ansible, then just join them.

For example:

- debug:
    msg: "{{ some_list | join(', ') }}"
  vars:
    some_list:
      - foo
      - bar
      - baz

Would give you

foo, bar, baz