Using dictionary and json with deserialize in RouterOS

Hello everyone. I’m trying to use a list of dictionaries, then use plug-in “to_json” to easy configuration. Using key/value, will produce less code and save some time, in my case.

The goal is:

  • Get some data from inventory as dict, list or a combination of them;
  • Pipe to “to_json” plugin
  • Deserialize it inside RouterOS
  • Put the result after the RouterOS command

Below there is a simple example playbook:

---
- name: Test
  hosts: test
  gather_facts: false
  vars:
    ntp_servers:
      address:
        - 192.168.1.2
        - 192.168.1.3
  tasks:
    - name: Add NTP servers
      community.routeros.command:
        commands:
          - /system/ntp/client/servers/add [:deserialize from=json value="{{ ntp_servers | to_json }}" ]

The problem is that deserialize demands double quotes in value= parameter, and community.routeros.command is escaping it ’ \" ’ , pointing it as an error:

changed: [test-host] => {
    "changed": true,
    "invocation": {
        "module_args": {
            "commands": [
                "/system/ntp/client/servers/add [:deserialize from=json value=\"{\"address\": [\"192.168.1.2\", \"192.168.1.3\"]}\" ]"
            ],
            "interval": 1,
            "match": "all",
            "retries": 10,
            "wait_for": null
        }
    },
    "stdout": [
        "expected end of command (line 1 column 32)"
    ],
    "stdout_lines": [
        [
            "expected end of command (line 1 column 32)"
        ]
    ]
}

Later I will use something like below to ensure idempotent and avoid put a command that potentially cause misconfigurations.

when: (ntp_config | map('to_nice_json') | list | difference(ntp_servers_registered | map('to_nice_json') | list)) | length != 0

Any suggestions?

Update:

Tried to execute the command directly on CLI:

> :put [:deserialize from=json value="[{\"address\":\"192.168.1.2\"}]"]
address=192.168.1.2
> /system/ntp/client/servers/set :put [:deserialize from=json value="[{\"address\":\"192.168.1.2\"}]"]
syntax error (line 1 column 32)

The problem is, the command set demands at least one of the following:

>  /system/ntp/client/servers/set
address     auth-key     comment     disabled     iburst     max-poll     min-poll     numbers

and I’m trying to use deserialize directly without using a loop like:

community.routeros.command:
   /system/ntp/client/servers/set {{item.key}}={{item.value}}
loop: "{{ ntp_config | map('dict2items') | flatten }}"

Didn’t try above code. Later will test and post results.