Ansible: K8S ConfigMap generation from multiple YAML

I was trying write an Ansible task that can do:

kubectl create configmap my-configmap — from-file=config/a-config.yaml — from-file=config/b-config.yaml

The tricky part was to merge the a-config.yaml and b-config.yaml into the configmap.yaml while preserving the order and formatting. I’ve tried to use from_yaml and to_nice_yaml filters but to_nice_yaml would not preserve the order

So then I went ahead and wrote a custom filter that can preserve the order which was very important for my application configuration. Here’s how my k8s config-map looks:

to_yaml_preserve_order is a custom filter that generates a YAML while preserving the order. For that I createdfilter_plugins directory in the root of Ansible repository(where I’ve the main playbook.yaml). And here’s my implementation of it:

I’m using oyaml library for this, there’re could be other solutions without requiring an extra module.

Here’s how my a-config.yaml and b-config.yaml files look like:

So when I execute my playbook here’s what output would be: