Ansible Network Automation: Facts Collection and Config Backup - 夜莺博客

Ansible Network Automation: Facts Collection and Config Backup

Ansible is the standard tool for multi-vendor network automation because it separates data from logic: your inventory defines what each device is, the network modules handle the vendor-specific CLI work, and the same playbook runs against Arista, Cisco and VyOS switches. Based on the official Ansible Network Examples documentation, this guide builds a complete facts-collection and configuration-backup workflow — inventory with network_cli connection, per-platform group variables, facts modules, and the built-in backup: option of config modules.

Inventory with Network Variables

[all:vars]
ansible_connection=ansible.netcommon.network_cli
ansible_user=ansible

[switches:children]
eos
ios
vyos

[eos]
veos01 ansible_host=veos-01.example.net

[eos:vars]
ansible_become=yes
ansible_become_method=enable
ansible_network_os=arista.eos.eos

Three variables matter most: ansible_connection must be a network connection plugin (network_cli), ansible_network_os selects the platform module set, and ansible_become_method=enable raises privileges where needed (EOS/IOS). Never store passwords in plain text — encrypt them with Ansible Vault.

Collecting Facts with Platform Modules

- name: Gather facts (eos)
  arista.eos.eos_facts:
  when: ansible_network_os == 'arista.eos.eos'

- name: Gather facts (ios)
  cisco.ios.ios_facts:
  when: ansible_network_os == 'cisco.ios.ios'

- name: Gather facts (vyos)
  vyos.vyos.vyos_facts:
  when: ansible_network_os == 'vyos.vyos.vyos'

- name: Display some facts
  debug:
    msg: "Hostname {{ ansible_net_hostname }} OS {{ ansible_net_version }}"

Backing Up Running Configurations

Config modules such as arista.eos.eos_config and vyos.vyos.vyos_config have a backup: option that saves a full copy of the running config before any change. Register the result and move it to a backup directory:

- name: Backup switch (eos)
  arista.eos.eos_config:
    backup: yes
  register: backup_eos_location
  when: ansible_network_os == 'arista.eos.eos'

- name: Create backup dir
  file:
    path: "/tmp/backups/{{ inventory_hostname }}"
    state: directory

- name: Copy backup files
  copy:
    src: "{{ backup_eos_location.backup_path }}"
    dest: "/tmp/backups/{{ inventory_hostname }}/{{ inventory_hostname }}.bck"

Platform-Independent Commands

For simple show commands across many platforms, ansible.netcommon.cli_command replaces per-vendor modules:

- name: Run show ip int br
  ansible.netcommon.cli_command:
    command: show ip int br
  register: result

More Automation Content on This Site

See Ansible network automation inventory and playbook examples, multi-vendor automation with Ansible and Jinja2 and Netmiko Python automation.

原文链接:https://docs.ansible.com/projects/ansible/latest/network/user_guide/network_best_practices_2.5.html