我有两个列表list1
和list2
。
list1
包含可变数量的名称。 list2
包含三个常量名称。
当我遍历list1
时,如何写我的when
条件来检查item
中是否包含list2
?
这是我尝试过的
---
- 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
谢谢。
答案 0 :(得分:1)
你快到了。
msg
参数中存在错误:双引号必须包含在字符串中,而不仅仅是围绕jinja2模板var in
jinja2运算符这是一个示例剧本
注意:在您的问题中尚不清楚,您是否要检查清单的一部分或不是。根据您的确切要求,如果需要=> 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
产生的结果
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
答案 1 :(得分:1)
您可能正在寻找intersect过滤器。
下面的戏
- 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) }}"
给予(grep msg):
"msg": "the user1 name can be used"
"msg": "the user2 name can be used"
"msg": "the user3 name can be used"