首页 > 解决方案 > 寻求帮助过滤 ansible stdout_lines

问题描述

我有一组交换机,用户一直要求我找到 mac 地址,以便追踪确切的端口并将该端口编辑到新的 vlan。我没有登录每个交换机并跟踪 mac 所在的交换机,而是创建了一个 ansible 一个基本的 ansible playbook 来帮助我解决这个问题:

---
- name: Find mac address in sec-switches
  hosts: sec-switch
  gather_facts: false
  connection: local
  vars_prompt:
     - name: mac
       prompt: What is the mac address?
       private: no
  tasks:
    -
      name: debugging
      ansible.builtin.debug:
        msg: 'Searching for {{ mac }}'
    -
      name: "search"
      register: output
      ios_command:
        commands:
          - "show mac address-table | include {{ mac }}"
    -
      debug: var=output.stdout_lines

运行时,我的调试给了我:(片段)

}
ok: [10.1.1.32] => {
    "output.stdout_lines": [
        [
            "24    0050.f967.5cb7    DYNAMIC     Gi1/0/48"
        ]
    ]
}
ok: [10.1.1.33] => {
    "output.stdout_lines": [
        [
            "24    0050.f967.5cb7    DYNAMIC     Gi1/0/48"
        ]
    ]
}
ok: [10.1.1.30] => {
    "output.stdout_lines": [
        [
            "4    0050.f967.5cb7    DYNAMIC     Gi1/1/1",
            " 24    0050.f967.5cb7    DYNAMIC     Gi1/1/1"
        ]
    ]
}

我想过滤输出并为每个开关运行 sh 接口描述 | inc {使用返回的接口}。这样我可以排除上行链路。

IE:在交换机 10.1.1.33 上我运行:sh 接口描述 | inc Gi1/0/48 并返回: Gi1/0/48 up up UPLINK

这让我知道我不需要担心那个开关是上行链路。

所以我想知道是否有办法过滤 output.stdout_lines 的输出,只显示输出的第 4 个条目:所以对于这个输出:“24 0050.f967.5cb7 DYNAMIC Gi1/0/48”有没有它只显示的方式:“Gi1/0/48”如果它可以做到这一点,我可以将其设置为事实并运行:ios_command:commands:-“show sh interfaces description | inc {{registered fact}}”

任何帮助,将不胜感激。我查看了https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html

提前致谢。

标签: ansiblecisco-ios

解决方案


最后一块拼图来自 rajthecomputerguy:

使用 strip() 方法去除空白

  debug:
    var: intf[0].strip()

完整代码:

---

- name: Find mac address in sec-switches

  hosts: sec-switch

  gather_facts: false

  connection: local

  vars_prompt:

     - name: mac

       prompt: What is the mac address?

       private: no

  tasks:

    -

      name: debugging

      ansible.builtin.debug:

        msg: 'Searching for {{ mac }}'

    -

      name: search

      ios_command:

        commands:

          - "show mac address-table | include {{ mac }}"

      register: printout

    - set_fact:

        intf: |

          {{printout.stdout_lines[0] |

            map('regex_replace','^(?:[^ ]*\ ){12}([^ ]*)') |

            list }}

    -

      name: show int desc

      ios_command:

        commands:

          - "sh interfaces description | inc {{ intf[0].strip() }}"

      register: printout2

    - name: View output

      debug:

        var: printout2

推荐阅读