Ansible Cisco Network Automation 101: Playbook Examples - 夜莺博客

Ansible Cisco Network Automation 101: Playbook Examples

Ansible is the easiest entry point into network automation: playbooks are written in YAML, no agent runs on the device, and the same structure works for Cisco, Juniper and other platforms. This tutorial walks through installing Ansible, building the directory structure (ansible.cfg, inventory, group_vars), running show commands with ios_command, making configuration changes with ios_config, and understanding idempotency and desired state.

Ansible Cisco network automation playbook example

Installing Ansible

python3 -m venv venv
source venv/bin/activate
pip install ansible

Directory Structure

ansible-network-101
.
├── ansible.cfg
├── inventory
│   ├── group_vars
│   │   └── switches.yml
│   ├── host_vars
│   └── hostfile.ini
└── playbook.yml

ansible.cfg and Inventory

# ansible.cfg
[defaults]
host_key_checking = False
inventory = inventory/hostfile.ini

# inventory/hostfile.ini
[switches]
switch_01 ansible_host=10.10.1.50

Group Vars for Network Devices

# inventory/group_vars/switches.yml
---
ansible_connection: ansible.netcommon.network_cli
ansible_network_os: cisco.ios.ios
ansible_become: yes
ansible_become_method: enable
ansible_user: admin
ansible_password: cisco123
ansible_become_password: cisco123

network_cli tells Ansible to treat the host as a network device; ansible_become_method: enable enters Cisco privilege mode before executing tasks. Avoid storing plain-text passwords in production - use Ansible Vault.

Running Show Commands

---
- name: "Ansible 101"
  hosts: switches
  gather_facts: no

  tasks:
    - name: Show Version
      cisco.ios.ios_command:
        commands: show version
      register: output

    - name: Print output
      debug:
        msg: "{{ output.stdout_lines }}"

Run with ansible-playbook playbook.yml.

Making a Configuration Change

---
- name: "Create VLANs"
  hosts: switches
  gather_facts: no

  tasks:
    - name: VLAN Config
      cisco.ios.ios_config:
        lines:
          - vlan 30
          - name server_vlan
          - vlan 31
          - name user_vlan

Idempotency and Desired State

Ansible is declarative: you define the desired state (for example, two VLANs) and Ansible ensures the switch matches it. Run the playbook a second time and it reports changed=0 because the configuration already matches - this makes automation safe to re-run and keeps the network consistent.

Interface Configuration

    - name: Port Configuration
      cisco.ios.ios_l2_interfaces:
        config:
          - name: Te1/0/1
            mode: access
            access:
              vlan: 30

Related articles: Ansible network facts and config backup examples, Netmiko Python automation for network engineers, and Cisco Catalyst port security with sticky MAC.

原文链接:https://www.packetswitch.co.uk/ansible-network-automation-101