如何解决Ansible 过滤器 with_items 列表
我使用的是 Ansible 2.10.7,我需要过滤 with_items
列表中的特定项目。
在使用 with_items
之前,msg 看起来像这样:
"ansible_facts": {
"cvp_info": {
"version": "2020.2.3"
},"devices": [
{
"architecture": "","bootupTimeStamp": 1615810038.137913,"bootupTimestamp": 1615810038.137913,"complianceCode": "",
剧本:
---
- name: Playbook to demonstrate cv_container module.
hosts: cvp_servers
connection: local
gather_facts: no
collections:
- arista.cvp
vars:
vars_files:
- vars.yml
tasks:
- name: "collecting facts from CVP {{inventory_hostname}}"
arista.cvp.cv_facts:
facts:
devices
- name: "Print out facts from CVP"
debug:
msg: "{{item.name}}"
with_items: "{{devices}}"
使用 with_items: "{{devices}}"
后,我看到它正在过滤大列表,然后我得到要过滤的输出:
ok: [hq] => (item={'hostname': 'rd-sw055','danzEnabled': False,'mlagEnabled': False,'streamingStatus': 'active','status': 'Registered','bootupTimeStamp': 1605618537.210405,'internalBuildId': '8c8dfbf2-a4d1-420a-9c9c-59f6aa67a14e','taskIdList': [],'tempAction': None,'memTotal': 0,'memFree': 0,'sslConfigAvailable': False,'sslEnabledByCVP': False,'lastSyncUp': 0,'type': 'netelement','dcaKey': None,'containerName': 'HQ','name': 'rd-sw055','deviceSpecificConfiglets': ['rd-sw055'],'imageBundle': ''}) => {
"msg": "rd-sw055"
ok: [hq] => (item={'hostname': 'rd-sw01','name': 'rd-sw01','deviceSpecificConfiglets': ['rd-sw01'],'imageBundle': ''}) => {
"msg": "rd-sw01"
我希望它只显示带有 'name': 'rd-sw01'
的项目,我该怎么做?
我试过使用
loop_control:
label: '{{ item.name }}'
想要的最终结果:
ok: [hq] => (item={'hostname': 'rd-sw01','imageBundle': ''}) => {
"msg": "rd-sw01"
解决方法
您确实需要 when
条件:
- debug:
var: item
loop: "{{ devices }}"
when: item.name == 'rd-sw01'
loop_control:
label: "{{ item.name }}"
或者甚至更简单,跳过循环:
- debug:
var: devices | selectattr("name","eq","rd-sw01")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。