Ansible 过滤器 with_items 列表

Ansible Filter with_items list

我正在使用 Ansible 2.10.7,我需要过滤 with_items 列表中的特定项目。

在使用 with_items 之前,消息如下所示:

"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', '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-sw01','deviceSpecificConfiglets': ['rd-sw01'], 'imageBundle': ''}) => {
  "msg": "rd-sw01"

我希望它只显示带有 'name': 'rd-sw01' 的项目,我该怎么做?

我试过使用

loop_control:
   label: '{{ item.name }}'

在 playbook 的末尾,但这只会显示名称值而不是整个项目值。

想要的最终结果:

ok: [hq] => (item={'hostname': 'rd-sw01', '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-sw01','deviceSpecificConfiglets': ['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")