Ansible Network Automation 101: Cisco IOS First Steps - 夜莺博客

Ansible Network Automation 101: Cisco IOS First Steps

Ansible remains the fastest on-ramp to network automation for engineers who have never written code: playbooks are YAML, modules are declarative, and there is no agent to install on the devices. This 101 guide, based on the PacketSwitch tutorial series, walks a complete first project against a Cisco Catalyst 9300 — installing Ansible in a virtualenv, building a clean directory structure, running show commands with ios_command, and making idempotent configuration changes with ios_vlans. You will also learn the two concepts that make automation safe: idempotency and desired state.

Install Ansible

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

Project Structure

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

ansible.cfg sets host_key_checking = False and points to the inventory. In hostfile.ini, group hosts under [switches]. The group name must match the group_vars/switches.yml file name so variables apply automatically:

[switches]
switch_01 ansible_host=10.10.1.50
# 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

Never store real credentials in plain text — use Ansible Vault.

First Playbook: Run 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 }}"
ansible-playbook playbook.yml

Make a Configuration Change

---
- name: "Ansible 101 - Configuration Changes"
  hosts: switches
  gather_facts: no
  tasks:
    - name: VLAN Config
      cisco.ios.ios_vlans:
        config:
          - name: server_vlan
            vlan_id: 30
          - name: user_vlan
            vlan_id: 31

Run it once → changed=1; run it again → changed=0. That is idempotency: Ansible detects the current state and only applies changes needed to reach the desired state.

Fix libssh Issues (macOS)

pip install ansible-pylibssh
# Apple Silicon: build with brew headers
CFLAGS="-I $(brew --prefix)/include -I ext -L $(brew --prefix)/lib -lssh" pip install ansible-pylibssh

Desired State Explained

Playbooks declare what the end state should be, not how to get there. Ansible translates intent into the required CLI commands, which reduces human error and keeps every switch consistent. For the deeper playbook design with roles and host_vars, continue with our Cisco IOS Ansible playbook guide; automation pairs well with MLNX-OS configuration management.

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