Ansible Network Examples: Facts, Backups and cli_command - 夜莺博客

Ansible Network Examples: Facts, Backups and cli_command

Automating network devices with Ansible starts with a few well-understood patterns: inventory groups with connection variables, facts collection, configuration backups, and platform-independent modules that work across vendors. This guide is based on the official Ansible network examples and walks through a facts-and-backup playbook that runs against Arista EOS, Cisco IOS and VyOS, then shows how to simplify multi-vendor playbooks with cli_command and cli_config. It is the fastest way to move from ad-hoc CLI work to repeatable automation.

Inventory Groups and Variables

Use [group:vars] sections to set connection variables per platform, and Ansible Vault to encrypt passwords. A minimal inventory for network devices groups switches by platform so playbooks can target each type.

Example 1: Collect Facts and Create Backups

- name: "Demonstrate connecting to switches"
  hosts: switches
  gather_facts: no
  tasks:
    - 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: Display some facts
      debug:
        msg: "The hostname is {{ ansible_net_hostname }} and the OS is {{ ansible_net_version }}"
    - name: Backup switch (eos)
      arista.eos.eos_config:
        backup: yes
      register: backup_eos_location
      when: ansible_network_os == 'arista.eos.eos'

Facts modules populate ansible_net_* variables such as hostname, version, model and serial number; the config backup creates timestamped files you can store in version control.

Example 2: Platform-Independent Modules

With two or more platforms, replace platform-specific modules with ansible.netcommon.cli_command and ansible.netcommon.cli_config:

- hosts: network
  gather_facts: false
  connection: ansible.netcommon.network_cli
  tasks:
    - name: Run cli_command on Arista
      ansible.netcommon.cli_command:
        command: show ip int br
      register: result
      when: ansible_network_os == 'arista.eos.eos'
    - name: Run cli_command on Cisco IOS
      ansible.netcommon.cli_command:
        command: show ip int br
      register: result
      when: ansible_network_os == 'cisco.ios.ios'

Using groups and group_vars by platform, this can be further simplified to a single task with a {{ show_interfaces }} variable per platform group.

Best Practices

Always run ansible-playbook --syntax-check before execution, use --check --diff for dry runs on config modules, store credentials in Vault, and keep playbooks idempotent by checking state before applying changes.

More automation content: Ansible network automation 101, Cisco IOS Ansible playbook getting started, and SONiC troubleshooting.

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