You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible Playbook优化:按路由器名称排序CSV输出

解决Ansible生成CSV按路由器名称排序的问题

你当前的Playbook通过逐行写入CSV导致内容顺序混乱,要实现按路由器名称排序,可通过先汇总所有设备数据、统一排序后一次性写入的方式解决,修改后的Playbook如下:

---
- name: Cisco get ints
  hosts: test
  gather_facts: false
  connection: local
  become: false

  vars:
    csv_path: /tmp
    csv_filename: int_audit.csv
    headers: "Hostname,Interface,Description"

  tasks:
    - name: Gather interface facts from devices
      iosxr_facts:
        gather_subset: interfaces
      register: output

    - name: Generate sorted CSV content
      delegate_to: localhost
      run_once: true
      set_fact:
        sorted_csv_content: >
          {{ headers }}
          {% for host in groups['test'] | sort %}
          {% for intf in hostvars[host].output.ansible_facts.ansible_net_interfaces | dict2items | sort(attribute='key') %}
          {{ hostvars[host].output.ansible_facts.ansible_net_hostname }},{{ intf.key }},{{ intf.value.description | replace(',', ';') }}
          {% endfor %}
          {% endfor %}

    - name: Write sorted content to CSV file
      delegate_to: localhost
      run_once: true
      copy:
        content: "{{ sorted_csv_content | trim }}"
        dest: "{{ csv_path }}/{{ csv_filename }}"
        mode: '0644'

关键改动说明

  1. 移除逐行写入逻辑:放弃原有的lineinfile逐行追加方式,避免执行顺序导致的混乱
  2. 统一汇总排序:
    • 按主机组内的路由器名称排序(groups['test'] | sort),确保同名称路由器的接口集中展示
    • 可选:对单台路由器的接口按名称排序(sort(attribute='key')),让同一设备下的接口也保持有序
    • 处理描述中的逗号(replace(',', ';')),避免特殊字符破坏CSV格式
  3. 一次性写入文件:用copy模块将排序后的完整内容写入文件,完全控制输出顺序

修改后预期输出

$ cat /tmp/int_audit.csv

Hostname,Interface,Description
RTR1.LAB1,BVI13,LOCAL:RTR2.LAB1:[L3]
RTR1.LAB1,Bundle-Ether1100.128,LOCAL:RTR2.LAB1:BUNDLE1100:20GE[UTIL]
RTR1.LAB1,Loopback0,LOOP:LOOP0-RTR1.LAB1:[N/A]
RTR2.LAB1,Bundle-Ether1100.128,LOCAL:RTR1.LAB1:BUNDLE1100:20GE[UTIL]
RTR2.LAB1,Loopback0,LOOP:LOOP0-RTR2.LAB1:[N\A]

内容的提问来源于stack exchange,提问作者William McGuire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 14:30:51