Ansible with MikroTik RouterOS: Quick Start

1. Install the collection on the Ansible control node:

ansible-galaxy collection install community.routeros ansible.netcommon
pip install paramiko

2. Inventory (inventory.ini):

[mikrotik]
rt01 ansible_host=192.0.2.1
rt02 ansible_host=192.0.2.4

[mikrotik:vars]
ansible_connection=ansible.netcommon.network_cli
ansible_network_os=community.routeros.routeros
ansible_user=ansible+cet1024w
ansible_ssh_private_key_file=~/.ssh/id_ed25519

The +cet1024w suffix on the user name disables colors and sets a wide terminal, which avoids parsing problems. Create the ansible user on the router and import its public key (/user ssh-keys import).

3. Playbook to back up the config (backup.yml):

- name: Backup MikroTik configuration
  hosts: mikrotik
  gather_facts: false
  tasks:
    - name: Export configuration
      community.routeros.command:
        commands: /export
      register: export

    - name: Save it on the control node
      ansible.builtin.copy:
        content: "{{ export.stdout[0] }}"
        dest: "backups/{{ inventory_hostname }}.rsc"
      delegate_to: localhost
mkdir -p backups
ansible-playbook -i inventory.ini backup.yml

4. Run any command, for example add a read-only user:

    - name: Add read-only user
      community.routeros.command:
        commands: /user add name=monitor group=read password=ChangeMe

For idempotent configuration (only change what differs) look at the community.routeros.api_modify module, which uses the RouterOS API.

Docs: community.routeros collection.

Written by Daniel Ruiz Peláez, Systems & Infrastructure Engineer (Linux, VMware, Proxmox, Active Directory, networking and security). These are notes from real problems I have solved.

← Back to all posts