This playbook is for updating Mikrotik routers. It will update both the RouterOS version and the firmware.
The playbook executes in the following order.
- Check for RouterOS Updates
- Update RouterOS (Router will reboot if there is an update)
- Sleep 120 seconds to allow the router(s) to boot up
- Check current firmware version, and if there is an available upgrade
- Update firmware
- Reboot router to apply firmware upgrade
This playbook attempts to be smart and will not reboot a router if there is not an update available. Routers that have updates available will reboot twice. Once to apply the RouterOS version, and the second time to apply the firmware.
Prerequisites
You should already have an inventory file and the Ansible RouterOS collection installed. If not, check out the following post.
Playbook
Here is the playbook.
A quick command syntax note, RouterOS 7 and newer typically use slashes / between commands. i.e. /system/package/update/install
. Older versions of RouterOS have spaces in the command path i.e. /system package update install
Since this still works on newer versions, we use it here.
---
- name: Mikrotik RouterOS and Firmware Upgrades
hosts: routers
gather_facts: false
tasks:
# Update RouterOS version. Mikrotik update/install command automatically reboots the router
- name: Check for RouterOS updates
community.routeros.command:
commands:
- /system package update check-for-updates
register: system_update_print
- name: Update RouterOS version
community.routeros.command:
commands:
- /system package update install
when: system_update_print is not search('System is already up to date')
# Check if firmware needs an upgrade, upgrade and reboot.
- name: Sleeping for 120 seconds. Giving time for routers to reboot.
ansible.builtin.wait_for:
timeout: 120
delegate_to: localhost
- name: Check Current firmware
community.routeros.command:
commands:
- ':put [/system routerboard get current-firmware]'
register: firmware_current
- name: Check Upgrade firmware
community.routeros.command:
commands:
- ':put [/system routerboard get upgrade-firmware]'
register: firmware_upgrade
- name: Upgrade firmware
community.routeros.command:
commands:
- ':execute script="/system routerboard upgrade"'
when: firmware_current != firmware_upgrade
- name: Wait for firmware upgrade and then reboot
community.routeros.command:
commands:
- /system routerboard print
register: Reboot_Status
until: "Reboot_Status is search(\"please reboot\")"
notify:
- Reboot Mikrotik
retries: 3
delay: 15
when: firmware_current != firmware_upgrade
handlers:
- name : Reboot Mikrotik
community.routeros.command:
commands:
- ':execute script="/system reboot"'
Run the playbook with
ansible-playbook -i routers.ini mikrotik_update.yaml
Change routers.ini to your router inventory.
mikrotik_update.yaml to whatever you end up calling the playbook.