Let’s say I have a dictionary called packages
in an Ansible playbook:
---
- name: Question
hosts: localhost
gather_facts: false
vars:
package_key: "ubuntu"
packages:
openssh-server:
archlinux:
- pkg1
- pkg2
ubuntu:
- pkg3
cowsay:
archlinux:
- pkg4
app-armor:
archlinux:
- pkg5
ubuntu:
- pkg6
- pkg7
tasks:
- name: Transformation
debug:
msg={{ packages | dict2items | <something> | items2dict }}
If I know the package_key
to be ubuntu
on such a system, I would like to transform the dictionary so that I get:
transformed_packages:
openssh-server:
- pkg3
app-armor:
- pkg6
- pkg7
What <something>
do I need for this transformation? (Where the ubuntu packages are children of the applications, and when there is no ubuntu package, it’s not part of the transformed dict).
My reason for this transformation is that I find it more convenient to group per app when I edit what packages are needed for different distros. But at the same time, it’s more convenient to just keep what I need when I know the OS.
2
Answers
One way to transform the packages dictionary is by using a
loop
andcombine
:Create a dictionary of all packages
gives
Optionally, you can use json_query
Select non-empty lists
gives what you want
Example of a complete playbook for testing
You can make the declaration more robust if you don’t trust the method keys() and the filter dict2items provides the same order of keys