19

I have the following vars inside of my ansible playbook I got the following structure

domains:
  - { main: 'local1.com', sans: ['test.local1.com', 'test2.local.com'] }
  - { main: 'local3.com' }
  - { main: 'local4.com' }

And have the following inside of the my conf.j2

{% for domain in domains %}
  [[acme.domains]]

    {% for key, value in domain.iteritems() %}
      {% if value is string %}
        {{ key }} = "{{ value }}"
      {% else %}
        {{ key }} = {{ value }}
      {% endif %}
    {% endfor %}
{% endfor %}

Now when I go in the VM and see the file I get the following:

Output

[[acme.domains]]
  main = "local1.com
  sans = [u'test.local1.com', u'test2.local.com']
[[acme.domains]]
  main = "local3.com"
[[acme.domains]]
  main = "local4.com"

Notice the u inside of the sans array.

Excpeted output

[[acme.domains]]
  main = "local1.com"
  sans = ["test.local1.com", "test2.local.com"]
[[acme.domains]]
  main = "local3.com"
[[acme.domains]]
  main = "local4.com"

Why is this happening and how can I fix it?

techraf
  • 64,883
  • 27
  • 193
  • 198
Steve
  • 1,213
  • 5
  • 16
  • 29
  • I ended up dumping the variable to json, and it fixed it (for jinja2). https://stackoverflow.com/a/50612950/999943 – phyatt May 30 '18 at 20:34

1 Answers1

25

You get u' ' because you print the object containing the Unicode strings and this is how Python renders it by default.

You can filter it with list | join filters:

{% for domain in domains %}
[[acme.domains]]
{% for key, value in domain.iteritems() %}
{% if value is string %}
  {{ key }} = "{{ value }}"
{% else %}
  {{ key }} = ["{{ value | list | join ('\',\'') }}"]
{% endif %}
{% endfor %}
{% endfor %}

Or you can rely on the fact, that the string output after sans = is a JSON and render it with to_json filter:

{{ key }} = {{ value | to_json }}

Either will get you:

[[acme.domains]]
  main = "local1.com"
  sans = ["test.local1.com", "test2.local.com"]
[[acme.domains]]
  main = "local3.com"
[[acme.domains]]
  main = "local4.com"

But the first one is more versatile.

Community
  • 1
  • 1
techraf
  • 64,883
  • 27
  • 193
  • 198
  • 1
    Heads up: Actually it's tojson and not to_json. See: http://jinja.pocoo.org/docs/2.10/templates/#tojson – miron Sep 13 '18 at 08:09
  • 3
    Ansible provides [`to_json` filter](https://docs.ansible.com/ansible/2.6/user_guide/playbooks_filters.html#filters-for-formatting-data) and that's what I meant to use. – techraf Sep 13 '18 at 08:10