Sổ tay kỹ thuật

Thu thập inventory IOS XR bằng Ansible

how-to#ansible#iosxr#inventory· cập nhật 2026-11-06

Dùng khi cần lấy nhanh phiên bản, serial, module của nhiều router IOS XR và xuất ra file YAML/CSV.

Sửa trang này
Mục lục

Tóm tắt: Khai báo inventory theo group iosxr, dùng network_cli + module cisco.iosxr.iosxr_facts để lấy facts, rồi ghi ra out/inventory.yml. Chạy được trên Ansible ≥ 2.15 với collection cisco.iosxr.

Luồng hoạt động

flowchart LR A[inventory/hosts.yml] --> B[ansible-playbook] B -->|SSH network_cli| C[(Router IOS XR)] C -->|show version / inventory| B B --> D[iosxr_facts] D --> E[out/inventory.yml]

Cấu hình

Cài collection

python3 -m pip install "ansible-core>=2.15" paramiko
ansible-galaxy collection install cisco.iosxr ansible.netcommon

Inventory

inventory/hosts.yml
all:
  children:
    iosxr:
      hosts:
        pe1-hni: { ansible_host: 198.51.100.11 }
        pe2-hcm: { ansible_host: 198.51.100.12 }
      vars:
        ansible_network_os: cisco.iosxr.iosxr
        ansible_connection: ansible.netcommon.network_cli
        ansible_user: "{{ lookup('env', 'NET_USER') }}"
        ansible_password: "{{ lookup('env', 'NET_PASS') }}"

Không ghi mật khẩu vào inventory. Đọc từ biến môi trường hoặc ansible-vault.

Playbook

collect_inventory.yml
- name: Thu thập inventory IOS XR
  hosts: iosxr
  gather_facts: false
  tasks:
    - name: Lấy facts phần cứng
      cisco.iosxr.iosxr_facts:
        gather_subset: [hardware, default]
 
    - name: Gom kết quả
      ansible.builtin.set_fact:
        row:
          host: "{{ inventory_hostname }}"
          version: "{{ ansible_net_version }}"
          model: "{{ ansible_net_model }}"
          serial: "{{ ansible_net_serialnum }}"
 
    - name: Ghi file
      run_once: true
      delegate_to: localhost
      ansible.builtin.copy:
        dest: out/inventory.yml
        content: "{{ ansible_play_hosts | map('extract', hostvars, 'row') | list | to_nice_yaml }}"

Chạy

export NET_USER=automation NET_PASS='***'
mkdir -p out
ansible-playbook -i inventory/hosts.yml collect_inventory.yml -f 20

Lỗi thường gặp

Triệu chứng Nguyên nhân Cách xử lý
unable to open shell Sai ansible_network_os hoặc thiếu collection Kiểm tra ansible-galaxy collection list | grep iosxr
command timeout triggered show inventory chậm trên chassis lớn Đặt ansible_command_timeout: 120
ssh: Permission denied Tài khoản AAA chưa có task-group đọc Thêm user vào read-only-tg trên router
Facts rỗng ansible_net_serialnum XR 7.x đổi output Cập nhật cisco.iosxr lên bản mới nhất

Tham khảo