Torben
Torben

Reputation: 13

Jinja2 templating - Filter specific items - Ansible

I am wondering how it's possible to compare two lists in ansible with jinja2 templating and just get the difference between the lists.

Let's say we have two lists: customers and exclude_customers

customers:
  - name: A
    git: true
    version: 7.2.8
  - name: B
    git: true
  - name: components
    git: true
  - name: Editor
    git: true

exclude_customers:
  - name: components
  - name: Editor

In this example, I would expect a result with the values A and B.

{% for customer in customers| difference(['exclude_customers']) | map (attribute='name') %}
{{ customer.name }}
{% endfor %}

But I got this error:

 AnsibleUndefinedVariable: 'ansible.parsing.yaml.objects.AnsibleUnicode object' has no attribute 'name'

Thanks

Upvotes: 1

Views: 84

Answers (1)

P....
P....

Reputation: 18371

If I understand the objective correctly, this should work,

---
- hosts: localhost
  gather_facts: False
  vars:
    customers:
    - name: A
      git: true
      version: 7.2.8
    - name: B
      git: true
    - name: components
      git: true
    - name: Editor
      git: true

    exclude_customers:
    - name: components
    - name: Editor
      git: true

  tasks:
  - debug:
      msg: "{{ customers |map (attribute='name')|list |difference(exclude_customers|map (attribute='name')|list) }}"

Would return:

PLAY [localhost] *************************************************************************************************************************************************************************************************************************

TASK [debug] *****************************************************************************************************************************************************************************************************************************
ok: [localhost] =>
  msg:
  - A
  - B

PLAY RECAP *******************************************************************************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Upvotes: 2

Related Questions