Skip to content
Guides & References

Back up a device with no CLI over a REST API

An SIE recipe that backs up a Cisco Meraki organisation through its Dashboard API with standard-library Python, keeping the API key in rConfig.

Script Integration EngineUpdated
On this page

Back up a device with no CLI over a REST API

Cloud-managed and API-first platforms have no CLI to log in to. Their configuration lives behind a REST API, often spread over several endpoints. This recipe collects a Cisco Meraki organisation’s networks, devices, VLANs and firewall rules through the Dashboard API, and prints them as one sorted JSON document for rConfig to store. The pattern carries over to any API that needs more than one call.


When to use it

  • The platform has no usable CLI, only an API.
  • Getting the full configuration takes several calls, for example a list of networks and then the settings for each one.

If one request returns the whole configuration, use API Collections instead. It handles authentication and scheduling without a script.


Where the API key goes

The key is stored on the rConfig device record, not in the script or an environment variable:

Device field What to enter
Username The Meraki organisation ID
Password A Dashboard API key with read-only access to that organisation
IP address Not used by this script. rConfig requires a value, so enter one your team will recognise.

That keeps the key with rConfig’s other device credentials, lets you rotate it from the device page, and gives each organisation its own device. Environment variables are a poor fit: scheduled runs start from rConfig’s background workers, which don’t read your shell’s profile.


The template

sie-meraki-template.yml
main:
name: "SIE - Meraki API backup"
desc: "Backs up a Meraki organisation over the Dashboard API"
connect:
timeout: 300 # One call per network per endpoint adds up in a large org
idletimeout: 60
idleTimeout: 60
protocol: script
# exit_codes is deliberately left out: any non-zero exit fails the run.
failure_criteria:
error_patterns:
- "ERROR:"
success_patterns:
- "SIE-OK: meraki"

The command

/usr/bin/python3 {script_path}meraki-api-backup.py {device_username} {device_password}

The script

Save it as meraki-api-backup.py in the scripts folder. It uses only the Python standard library, so there is nothing to install.

meraki-api-backup.py
#!/usr/bin/env python3
"""Back up a Cisco Meraki organisation over the Dashboard API.
Usage:
meraki-api-backup.py <organisation_id> <api_key>
The configuration goes to stdout as sorted JSON and becomes the stored backup.
Progress, errors and the success marker go to stderr. Exit code 0 on success,
1 on any failure. Standard library only.
"""
import json
import sys
import time
import urllib.error
import urllib.request
BASE = "https://api.meraki.com/api/v1"
TIMEOUT = 30
MAX_RETRIES = 5
class NotAvailable(Exception):
"""The endpoint does not apply to this network (for example VLANs with no appliance)."""
def note(message):
print(message, file=sys.stderr)
def fail(message):
print(f"ERROR: {message}", file=sys.stderr)
sys.exit(1)
def get(path, key):
"""GET a Dashboard API path, waiting and retrying when the API rate-limits us."""
request = urllib.request.Request(
BASE + path,
headers={
"Authorization": f"Bearer {key}",
"Accept": "application/json",
"User-Agent": "rconfig-sie-recipe/1.0",
},
)
for attempt in range(1, MAX_RETRIES + 1):
try:
with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as e:
if e.code == 429 and attempt < MAX_RETRIES:
wait = int(e.headers.get("Retry-After", "2"))
note(f"rate limited on {path}, waiting {wait}s (attempt {attempt})")
time.sleep(wait)
continue
if e.code in (400, 404):
raise NotAvailable(path)
fail(f"HTTP {e.code} for {path}")
except urllib.error.URLError as e:
fail(f"cannot reach the Dashboard API for {path}: {e.reason}")
except json.JSONDecodeError:
fail(f"the response for {path} was not valid JSON")
fail(f"still rate limited on {path} after {MAX_RETRIES} attempts")
def optional(path, key, label):
"""GET an endpoint that may not apply to every network."""
try:
return get(path, key)
except NotAvailable:
note(f"skipped {label} on {path}, not available on this network")
return None
def main():
if len(sys.argv) < 3:
fail("usage: meraki-api-backup.py <organisation_id> <api_key>")
org, key = sys.argv[1], sys.argv[2]
note(f"reading organisation {org}")
try:
networks = get(f"/organizations/{org}/networks", key)
except NotAvailable:
fail(f"organisation {org} was not found, or the key cannot see it")
if not isinstance(networks, list) or not networks:
fail("no networks were returned, refusing to store an empty backup")
backup = {"organizationId": org, "networks": []}
for network in sorted(networks, key=lambda n: n.get("id", "")):
nid = network["id"]
note(f"reading network {network.get('name', nid)}")
devices = optional(f"/networks/{nid}/devices", key, "devices") or []
backup["networks"].append({
"network": network,
"devices": sorted(devices, key=lambda d: d.get("serial", "")),
"vlans": optional(f"/networks/{nid}/appliance/vlans", key, "VLANs"),
"firewallL3": optional(
f"/networks/{nid}/appliance/firewall/l3FirewallRules", key, "L3 firewall rules"
),
})
json.dump(backup, sys.stdout, indent=2, sort_keys=True)
sys.stdout.write("\n")
note(f"SIE-OK: meraki {len(backup['networks'])} network(s) from organisation {org}")
return 0
if __name__ == "__main__":
sys.exit(main())

What gets stored

Sorted JSON, one value per line. rConfig trims the indentation, which leaves valid JSON that diffs line by line:

{
"networks": [
{
"devices": [
{
"lanIp": "192.0.2.40",
"model": "MX68",
"name": "branch-01-mx",
"serial": "Q2XX-XXXX-0001"
}
],

Why the script sorts everything

The API doesn’t promise to return keys, networks or devices in the same order every time. If the order changes, so does the stored text, and the run shows up as a change with nothing changed. sort_keys=True fixes the key order. Sorting networks by ID and devices by serial fixes the list order. Firewall rules are deliberately not sorted, because their order is part of the configuration.


Adapting it

  • More settings. Add endpoints to the dictionary built for each network, using optional() for anything that doesn’t apply to every network type.
  • A different platform. Keep get(), optional() and the sorting, and change the base URL, the authentication header and the endpoints.
  • Large organisations. Some list endpoints return results in pages. If yours has more networks than one response returns, follow the pages as in the API with many pages recipe.
  • Easier diffs. For one line per setting rather than nested JSON, flatten the output as in the cleaning output recipe.

Type to search.