I have a playbook like this:
- name: Testing
hosts: localhost
gather_facts: False
tasks:
- name: Set things
set_fact:
my_things:
- parameters:
dog: true
opts:
DO_THIS: true
DO_THAT: "false"
role: Samba
action: dance
- parameters:
cat: true
opts:
DO_THIS: no
DO_THAT: "yes"
role: Funk
action: dance
that I want to write in a jinja2 template that looks like this:
apiVersion: v1
kind: ConfigMap
metadata:
name: "test"
data:
myfile.yml: |+
---
dancers:
{% for thing in my_things %}
- {{ thing.action }}:
{% for key, value in thing.parameters.items() %}
{% if value is string and not (value) %}
{{ key }}: "{{ value }}"
{% elif value is mapping %}
{{ key }}:
{{ value | to_nice_yaml | indent(12) -}}
{% elif value | bool %}
{{ key }}: {{ (value) }}
{% elif not value | bool %}
{{ key }}: {{ (value) }}
{% else %}
{{ key }}: {{ value | to_yaml }}
{% endif %}
{% endfor %}
{% endfor %}
This is doing its thing, but it looks extremly ugly and will also break if there is a mapping
inside of a mapping
. Ideally, I would like to do something like this:
apiVersion: v1
kind: ConfigMap
metadata:
name: "test"
data:
myfile.yml: |+
---
dancers:
{% for thing in my_things %}
- {{ thing.action }}:
{% thing.parameters | to_yaml %}
This works for role
, dog
and cat
but breaks for opts
as it is not recursive.
Since I am deploying this configmap using the operator-sdk and a lookup
filter I cannot use jinja's env
to write a custom filter.
- name: 'Creating v1.ConfigMap'
community.kubernetes.k8s:
definition: "{{ lookup('template', 'my_template.yml.j2') }}"
Hence, my question would be: Is there any way to inline some python code or alternatively, is there something like a recursive to_yaml
filter?