Sync rConfig devices from your own source of truth
When your device list lives somewhere else (a CMDB, an IPAM, a spreadsheet the network team maintains), rConfig’s inventory drifts from it unless something keeps them in step. This recipe reads your source, compares it with rConfig, then creates the devices that are missing, updates the ones whose address or model changed, and disables the ones that have gone. It runs as a dry run until you tell it otherwise.
Check Device Sync first
rConfig already syncs devices from NetBox, Nautobot, Infrahub, Zabbix, LibreNMS, Observium, OpenNMS, PRTG, AKiPS, Checkmk, Statseeker and SolarWinds, with no code. See the Device Sync overview. Use this recipe only for a source Device Sync doesn’t cover.
rConfig docsDevice Sync V2 OverviewOverview of the V2 Device Sync engine in rConfig V8.2.0: a unified, schema-driven pipeline for syncing device inventory from eight upstream platforms.Read the Device Sync docs
How it works
- Read the devices from your source (here, a CSV file exported from the CMDB).
- Read every device in rConfig, page by page, through v2
GET /devices. - Match them by device name.
- Create devices in the source but not in rConfig, through v1
POST /devices. - Update devices whose IP address or model differs, through v1
PUT /devices/{id}. - Disable devices this sync created that are no longer in the source, through v2
POST /devices/{id}/disable. It never deletes, so the config history is kept.
The sync only ever disables devices carrying its own tag. Devices added by hand or by Device Sync are never touched.
What you need
- A token owned by a service account, with
devices.readanddevices.write. See tokens and least privilege. - A tag in rConfig that marks devices this sync owns, such as
cmdb-sync. Note its ID. - The IDs of the vendor, category, template, credential set and role new devices should get. You can read them from the rConfig UI or from v1
GET /vendors,/categories,/templates. - Python 3 with
requests(pip install requests).
The source CSV has one row per device:
device_name,device_ip,device_modeledge-rtr-01,192.0.2.1,ISR4331core-sw-01,192.0.2.10,C9500-24Y4Cbranch-fw-07,198.51.100.7,FortiGate-60FThe script
Save it as rconfig_device_sync.py. The settings at the top are the parts to change.
#!/usr/bin/env python3"""Sync rConfig devices from a CSV source of truth.
Usage: RCONFIG_URL=https://rconfig.example.com RCONFIG_TOKEN=... \ python3 rconfig_device_sync.py cmdb-export.csv # dry run python3 rconfig_device_sync.py cmdb-export.csv --apply # make the changes
Creates missing devices, updates changed IPs and models, and disables devicesthis sync owns that have left the source. Never deletes."""
import csvimport osimport sys
import requests
# ---- Settings to adapt --------------------------------------------------------SYNC_TAG_ID = 7 # tag that marks devices this sync ownsNEW_DEVICE_DEFAULTS = { # applied to every device the sync creates or updates "device_vendor": 1, "device_category_id": 2, "device_template": 1, "device_cred_id": 3, # a credential set, so no passwords pass through this script "device_main_prompt": "#", "device_enable_prompt": "", "roles": [1],}# ------------------------------------------------------------------------------
BASE = os.environ.get("RCONFIG_URL", "").rstrip("/")TOKEN = os.environ.get("RCONFIG_TOKEN", "")TIMEOUT = 30
def api(method, path, **kwargs): response = requests.request( method, f"{BASE}/api/{path}", headers={"apitoken": TOKEN, "Accept": "application/json"}, timeout=TIMEOUT, **kwargs, ) if response.status_code == 422: raise SystemExit(f"validation failed on {method} {path}: {response.text}") response.raise_for_status() return response.json()
def rconfig_devices(): """Every device the token can see, keyed by name. Follows every page.""" devices, page = {}, 1 while True: body = api("GET", "v2/devices", params={ "per_page": 100, "page": page, "with_credentials": "false", }) for device in body["data"]: devices[device["device_name"]] = device if body["next_page_url"] is None: return devices page += 1
def source_devices(path): with open(path, newline="") as handle: rows = list(csv.DictReader(handle)) names = [row["device_name"].strip() for row in rows] if len(names) != len(set(names)): raise SystemExit("the source has duplicate device names; fix it before syncing") return {row["device_name"].strip(): row for row in rows}
def payload(row): return { **NEW_DEVICE_DEFAULTS, "device_name": row["device_name"].strip(), "device_ip": row["device_ip"].strip(), "device_model": row["device_model"].strip(), "device_tags": [SYNC_TAG_ID], }
def owned_by_sync(device): return any(tag.get("id") == SYNC_TAG_ID for tag in device.get("tag", []))
def main(): if not BASE or not TOKEN: raise SystemExit("set RCONFIG_URL and RCONFIG_TOKEN") if len(sys.argv) < 2: raise SystemExit("usage: rconfig_device_sync.py <source.csv> [--apply]") apply = "--apply" in sys.argv[2:]
wanted = source_devices(sys.argv[1]) current = rconfig_devices() plan = []
for name, row in sorted(wanted.items()): device = current.get(name) if device is None: plan.append(("create", name, None, payload(row))) elif (device["device_ip"], device["device_model"]) != (row["device_ip"].strip(), row["device_model"].strip()): plan.append(("update", name, device["id"], payload(row)))
for name, device in sorted(current.items()): if name not in wanted and owned_by_sync(device) and device.get("status") != 100: plan.append(("disable", name, device["id"], None))
for action, name, device_id, _ in plan: print(f"{'APPLY' if apply else 'DRY RUN'}: {action} {name}")
if not apply: print(f"{len(plan)} change(s) planned. Run again with --apply to make them.") return 0
for action, name, device_id, body in plan: if action == "create": api("POST", "v1/devices", json=body) elif action == "update": api("PUT", f"v1/devices/{device_id}", json=body) else: api("POST", f"v2/devices/{device_id}/disable") print(f"{len(plan)} change(s) applied.") return 0
if __name__ == "__main__": sys.exit(main())What it prints
DRY RUN: create branch-fw-07DRY RUN: update core-sw-01DRY RUN: disable lab-sw-033 change(s) planned. Run again with --apply to make them.Things the API expects
- Device names must be unique, at least 5 characters, and contain no spaces. Rows that break this are refused with
422, which stops the run. - Create and update need the full device.
PUT /devices/{id}validates the same required fields as a create, which is why the script sendsNEW_DEVICE_DEFAULTSon updates too. - The category must have commands, or the device is refused.
- Role 1 is always added. The API adds it to every new device whatever you send, so administrators can always see devices created this way.
- New devices start with status 2 (not yet checked). They’re backed up at the next scheduled task that covers them.
Adapting it
- A different source. Replace
source_devices()with a call to your CMDB’s API. Keep the duplicate-name check. - More fields to keep in step. Add them to the comparison in
main()and topayload(). - Re-enabling devices that come back. Add a case for owned, disabled devices that are in the source again, calling v2
POST /devices/{id}/enable. - Run it on a schedule from cron or your automation platform. Keep the dry-run output: it’s a record of what the sync wanted to change.