Variable as a YAML tree. How to save indent?
Asked Answered
M

1

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.

Merideth answered 28/6, 2018 at 13:35 Comment(0)
S
23

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
Stretchy answered 28/6, 2018 at 13:46 Comment(2)
Thank you! indent works very well but I think to use the helper variable more properly.Merideth
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.Chavez

© 2022 - 2024 — McMap. All rights reserved.