0

I can't get this jinja2 template to work. Can somebody help me out? I've tried the Jinja2 Live templater but I don't get the result I need.

Let's say I have the following group_vars/all.yml file:

disk_iops: 500
disk_space: 
  "C:": 10
  "D:": 10
  "E:": 10
core_count: 8

And the following template: name.json.j2

{
  "DiskIO": "{{ disk_iops }}",
  {% if disk_space is defined and disk_space -%}
  "DiskSpace": {
    {%- set comma = joiner(",") -%}
    {%- for key, value in disk_space.items() -%}
    {{ comma() }}
    "{{ key }}": "{{ value }}"
    {%- endfor %}
  },
  {% endif -%}
  "CoreCount": "{{ core_count }}"
}

I get the following result:

{
  "DiskIO": "500",
  "DiskSpace": {
    "C:": "70",
    "D:": "100",
    "E:": "10"  },
  "CoreCount": "4"
}

But I would like the } to be on a new line

  • I think that `-%}` the dash removes the whitespaces. Try removing it and see. – Kostas Charitidis Aug 26 '19 at 08:35
  • 2
    FWIW, using a Jinja template to create YAML/JSON is a bit misdirected. You should simply create the data structure as dict/list and encode it with the appropriate library call. – deceze Aug 26 '19 at 08:36
  • @deceze Could you ellaborate? I'm new with this and I am not sure what 'as dict/list and encode it with the appropriate library call.' is. – Lovász Botond Aug 26 '19 at 08:44
  • as @deceze said, you should try dumping the json directly. And if you want it to be pretty, you could always use the `indent` option and set the `level`, like `json.dump(obj, fp, indent=4)` – han solo Aug 26 '19 at 08:45
  • @hansolo I'm not actually writing python code, but using ansible. – Lovász Botond Aug 26 '19 at 08:49
  • May be you check following stackoverflow link : https://stackoverflow.com/questions/22350175/how-do-i-get-an-ansible-template-to-honor-new-lines-after-a-conditional – Ravi Kulkarni Aug 26 '19 at 08:56

1 Answers1

0

This is the solution after all...

{
  "DiskIO": "{{ disk_iops }}",
  {% if disk_space is defined and disk_space -%}
  "DiskSpace": {
    {%- set comma = joiner(",") -%}
    {%- for key, value in disk_space.items() -%}
    {{ comma() }}
    "{{ key }}": "{{ value }}"
    {%- endfor %}

  },
  {% endif -%}
}