user12430166
user12430166

Reputation:

Keep YAML list structure in Ansible templates

Say I have a variable file

---
app1:
    environments:
      - test
      - demo
    paths:
      - /home/someuser/_env_/*.log
      - /var/log/something/*.log
    id: _env_

that's included in my playbook like this

---
- hosts: all
  become: yes
  vars:
      apps:
        - app1
  vars_files:
    - ~/vars/app1_vars.yml
  tasks:
  - name: Update config
    template:
      src: foo.j2
      dest: /home/configurer/test.conf
      owner: configurer
      group: configurer
      mode: '0644'
      lstrip_blocks: yes

and the template itself is

{% for app in apps %}
  {% for env in vars[app]['environments'] %}
  - type: log
    enabled: true
    paths:
      {% for path in vars[app]['paths'] %}
      - {{ path | replace("_env_", env) }}
      {% endfor %}
    fields:
      app_id: {{ vars[app]['id'] | replace("_env_", env) }}

  {% endfor %}
{% endfor %}

That gives me as output

- type: log
  enabled: true
  paths:
    - /home/someuser/test/*.log
    - /var/log/something/*.log
  fields:
    app_id: test

- type: log
  enabled: true
  paths:
    - /home/someuser/demo/*.log
    - /var/log/something/*.log
  fields:
    app_id: demo

Is there a more compact and nicer way to iterate over the paths variable list and keep the YAML list structure with the -s?

Upvotes: 0

Views: 1247

Answers (1)

user12430166
user12430166

Reputation:

After some experimenting I did the following as an alternative:

  1. Changed the variable file:
---
app1:
  environments:
  - test
  - demo
  filebeat_properties:
    paths:
    - /home/someuser/_env_/*.log
    - /var/log/something/*.log
    fields:
      app_id: _env_
  1. Used to_nice_yaml to pretty-print the config:
{% for app in apps %}
  {% for env in vars[app]['environments'] %}
- type: log
  enabled: true
  {{ vars[app]["filebeat_properties"] | to_nice_yaml(indent=2, width=9999) | indent(2) | replace("_env_", env) }}
  {% endfor %}
{% endfor %}

Upvotes: 1

Related Questions