Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ansible/jinja2 get unique subelements

I got a list like this:

host_depends:
  - host: abc
    depends:
      - name: item1
      - name: item4
        type: asdf
      - name: item6
  - host: def
    depends:
      - name: item2
      - name: item4
      - name: item6

I need to loop over the unique name of the depends elemnents, so in this example I want to loop over

- item1 
- item2
- item4
- item6

Basically what

debug: var=item.1.name
with_subelements:
  - "{{ host_depends }}"
  - depends

does, but with unique elements only.

How can I get the depends of all host_depends items so I can run a unique filter over them and use them with with_items?

Edit:

I manage to get a list of all depends items like this:

host_depends|map(attribute='depends')|list

But from there, I fail to reduce this list to the name items.

like image 753
Zulakis Avatar asked Dec 19 '25 19:12

Zulakis


1 Answers

If things get too complicated with Ansible and you can't map you mind around it, it's an indicator that it shouldn't be done. Maybe it's possible with some Jinja filters and some set_fact tasks in a loop. But don't, Ansible is not a programming language and should not be used as such. Ansible has two main strengths: readability and extensibility. Don't break the first by ignoring the latter.

with_subelements is in fact a plugin itself, just that it is a core plugin. Just copy it and create your own with_unique_subelements plugin. Here is the code of with_subelements. Line 100 is where the elements are added to the return list. That's where you can hook in and implement a check if that item already was added.

Save your modified version relative to your playbook as lookup_plugins/unique_subelements.py or if you use Ansible 2 you can also store it with the same path inside any role.

like image 138
udondan Avatar answered Dec 22 '25 11:12

udondan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!