Petro Pavlov
Petro Pavlov

Reputation: 13

How to check if an element is contained in a list?

I have two lists list1 and list2.

list1 contains a variable amount of names. list2 contains three constant names.

When I loop over list1, how can I write my when condition to check if item is contained in list2 ?

This is what I have tried

---
- hosts: localhost

  vars:
    list1:
      - user1
      - user2
      - user3
      - userN

    list2:
      - user1
      - user2
      - user3

  tasks:
    - name: check
      debug:
        msg: the "{{item}}" name can be used
      loop: "{{ list1 }}"
      when:  item != list2

Thanks.

Upvotes: 1

Views: 317

Answers (2)

Zeitounator
Zeitounator

Reputation: 44615

You were almost there.

  • You have an error in your msg param: double quotes must be all around the string not just arround the jinja2 template var
  • Your test should use the in jinja2 operator

Here is an example playbook

Note: It's unclear in your question whether you want to check names part of or not part of the checklist. Depending on your exact requirement, you can easily revert the condition below if needed => when: item not in authorized_users.

---
- name: Test 'in' operator
  hosts: localhost
  gather_facts: false

  vars:

    users:
      - user1
      - user2
      - user3
      - userN
      - toto
      - pipo
      - bingo

    authorized_users:
      - user1
      - user2
      - pipo

  tasks:
    - name: Check if user is authorized
      debug:
        msg: "User {{ item }} is authorized"
      loop: "{{ users }}"
      when: item in authorized_users

Which results in


PLAY [Test 'in' operator] ******************************************************

TASK [Check if user is authorized] *********************************************
ok: [localhost] => (item=user1) => {
    "msg": "User user1 is authorized"
}
ok: [localhost] => (item=user2) => {
    "msg": "User user2 is authorized"
}
skipping: [localhost] => (item=user3) 
skipping: [localhost] => (item=userN) 
skipping: [localhost] => (item=toto) 
ok: [localhost] => (item=pipo) => {
    "msg": "User pipo is authorized"
}
skipping: [localhost] => (item=bingo) 

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

Upvotes: 1

Vladimir Botka
Vladimir Botka

Reputation: 68064

The intersect filter might be what you're looking for.

The play below

- hosts: localhost
  vars:
     list1:
       - user1
       - user2
       - user3
       - userN
     list2:
       - user1
       - user2
       - user3
  tasks:
    - debug:
        msg: "the {{ item }} name can be used"
      loop: "{{ list1 | intersect(list2) }}"

gives (grep msg):

"msg": "the user1 name can be used"
"msg": "the user2 name can be used"
"msg": "the user3 name can be used"

Upvotes: 2

Related Questions