6

I have yml file with template. Template is a part of keys started from a middle of yml tree.

Templating works is ok, but indent is saved only for last key. How to save indent for all keys?

base.yml:

app:
  config1:
    base: {{ service1.company.backend | to_nice_yaml(indent=2) }}
  config2:
    node: {{ service1.company.addr | to_nice_yaml(indent=2) }}

config.yml:

service1:
  company:
    backend:
      node1: "xxx"
      node2: "yyy"
      node3: "zzz"
    addr:
      street: ""

I need to get:

app:
  config1:
    base:
      node1: "xxx"
      node2: "yyy"
      node3: "zzz"
  config2:
    node:
      street: ""

But really result is:

app:
  config1:
    base:
      node3: "zzz"
node1: "xxx"
node2: "yyy"
  config2:
    node:
      street: ""

node1 and node2 don't save an indent and Jinja2 parser gets the last node. On next step incorrect file is used in other role which doesn't handle it correctly.

techraf
  • 64,883
  • 27
  • 193
  • 198
jimmbraddock
  • 867
  • 2
  • 8
  • 17

1 Answers1

22

Use indent filter in Jinja2 with appropriate indentation set (also to_nice_yaml produces a trailing newline character, so trim is necessary):

app:
  config1:
    base:
      {{ service1.company.backend | to_nice_yaml(indent=2) | trim | indent(6) }}
  config2:
    node:
      {{ service1.company.addr | to_nice_yaml(indent=2) | trim | indent(6) }}

Or create a helper variable and rely on Ansible to_nice_yaml filter for the whole value. For example:

...

vars:
  helper_var:
    app:
      config1:
        base: "{{ service1.company.backend }}"
      config2:
        node: "{{ service1.company.addr }}"

...

tasks:
  - copy:
      content: "{{ helper_var | to_nice_yaml(indent=2) }}"
      dest: my_file
techraf
  • 64,883
  • 27
  • 193
  • 198
  • 3
    Thank you! `indent` works very well but I think to use the helper variable more properly. – jimmbraddock Jun 28 '18 at 14:18
  • 2
    I like both methods. I wound up using the first, though, so I could limit what the user can change in the config file I'm creating. – Mike Diehn Nov 13 '20 at 17:40