Prerequisites
- Ansible and the cisco.ios collection
- The ansible-pylibssh SSH library (or paramiko)
- An SSH account on the devices
01The inventory
ansible_network_os and ansible_connection tell Ansible it is talking to Cisco IOS, over SSH, in command-line mode. become with the enable method switches to privileged mode, needed to read the configuration if the account isn’t level 15.
The password isn’t written in clear text: it goes into a file encrypted with ansible-vault.
[switches]
sw-access-01 ansible_host=192.168.5.11
sw-access-02 ansible_host=192.168.5.12
[switches:vars]
ansible_network_os=cisco.ios.ios
ansible_connection=ansible.netcommon.network_cli
ansible_user=ansible
ansible_become=true
ansible_become_method=enable02The playbook
backup: true saves the running configuration; backup_options picks the file name and folder. A fixed name per device lets Git carry the history.
- name: Configuration backup
hosts: switches
gather_facts: false
tasks:
- name: Back up the running-config
cisco.ios.ios_config:
backup: true
backup_options:
filename: "{{ inventory_hostname }}.cfg"
dir_path: ./backups03Spot what wasn’t saved
Comparing the startup configuration with the running configuration reveals changes made but never saved, the ones that would vanish at the next reboot. The result is only displayed with the --diff option.
- name: startup-config versus running-config
cisco.ios.ios_config:
diff_against: startup
diff_ignore_lines:
- ntp clock .*04Version and schedule
A cron job runs everything every night. In a crontab, the % character must be escaped.
ansible-playbook -i inventory.ini backup.yml --ask-vault-pass
git add backups && git commit -m "Backup $(date +%F)"
# crontab: every night at 2 am (vault password read from a protected file)
0 2 * * * cd /opt/net-backup && ansible-playbook -i inventory.ini backup.yml --vault-password-file ~/.vault && git add backups && git commit -qm "Backup $(date +\%F)"Key takeaways
- ansible_network_os + network_cli: Ansible speaks IOS; become/enable for privileged mode.
- backup: true, one file per device, history in Git.
- diff_against: startup reveals forgotten “write memory”.
- Secrets in ansible-vault, never in clear text.
Example addresses.