Reputation: 13
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
Reputation: 44615
You were almost there.
msg
param: double quotes must be all around the string not just arround the jinja2 template varin
jinja2 operatorHere 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
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