Skip to content
Back to Blog
Automation

Ansible for Network Automation: MikroTik & Cisco

Automating network device configuration with Ansible: real playbooks for MikroTik RouterOS and Cisco IOS environments.

May 2025
14 min read

Ansible for Network Automation

Ansible connects to network devices over SSH (or API) and applies configuration idempotently — the same playbook run twice produces the same result.

Installation

BASH
pip install ansible ansible-pylibssh
ansible-galaxy collection install community.routeros cisco.ios

Inventory File

INI
# inventory/hosts.yml
all:
  children:
    mikrotik:
      hosts:
        router1:
          ansible_host: 192.168.1.1
          ansible_user: admin
          ansible_connection: ansible.netcommon.network_cli
          ansible_network_os: community.routeros.routeros
    cisco:
      hosts:
        sw1:
          ansible_host: 192.168.1.10
          ansible_user: cisco
          ansible_connection: ansible.netcommon.network_cli
          ansible_network_os: cisco.ios.ios

MikroTik Playbook: Backup Configs

YAML
# backup-configs.yml
- name: Backup MikroTik Configurations
  hosts: mikrotik
  gather_facts: false
  tasks:
    - name: Export configuration
      community.routeros.command:
        commands:
          - /export file=backup-{{ inventory_hostname }}
      register: result

    - name: Download backup file
      community.routeros.fetch:
        src: "/backup-{{ inventory_hostname }}.rsc"
        dest: "./backups/{{ inventory_hostname }}-{{ ansible_date_time.date }}.rsc"

Cisco IOS Playbook: VLAN Provisioning

YAML
- name: Provision VLANs on Cisco switches
  hosts: cisco
  gather_facts: false
  vars:
    vlans:
      - id: 10
        name: CORP
      - id: 20
        name: GUEST
      - id: 30
        name: SERVERS
  tasks:
    - name: Create VLANs
      cisco.ios.ios_vlans:
        config:
          - vlan_id: "{{ item.id }}"
            name: "{{ item.name }}"
            state: active
        state: merged
      loop: "{{ vlans }}"

    - name: Save running config
      cisco.ios.ios_command:
        commands: write memory

Bulk Interface Description Update

YAML
- name: Update interface descriptions
  hosts: mikrotik
  gather_facts: false
  tasks:
    - name: Set interface comments
      community.routeros.command:
        commands:
          - /interface set [find name=ether1] comment="Uplink-ISP1"
          - /interface set [find name=ether2] comment="Core-Switch-Trunk"

Scheduling with Cron

BASH
# Run backup every night at 2am
0 2 * * * ansible-playbook -i inventory/hosts.yml backup-configs.yml >> /var/log/ansible-backup.log 2>&1