Overview
Most homelabs and small-business networks track addresses in a spreadsheet, a wiki page, or somebody's head. That works until two hosts collide on the same IP, a VLAN gets reused, or you need to answer "what is on this subnet?" during an incident. NetBox fixes this by acting as a source of truth: IP address management (IPAM) plus data-center infrastructure management (DCIM) behind a REST and GraphQL API.
In this project you will:
- Run NetBox with the community
netbox-dockerstack (PostgreSQL, Redis, worker, web). - Model sites, VLANs, prefixes, devices and IP addresses.
- Bulk-load an existing inventory from a YAML file with
pynetbox. - Generate an Ansible inventory and Prometheus scrape targets directly from NetBox.
- Add a nightly job that flags drift between what NetBox says and what is actually alive.
The result is one place that answers "what exists, where, and what address does it own", and that other tools read from instead of keeping their own copies.
Architecture and Design
+-------------------------------+
Browser/API | NetBox (web + worker) |
------------->| Django, REST + GraphQL |
+---------+---------------+-----+
| |
PostgreSQL Redis
(data) (cache, queue)
pynetbox loader ---> NetBox API <--- inventory/targets exporters
(YAML -> objects) (Ansible, Prometheus file_sd)
^
drift check: ping sweep vs NetBox IPs
Design decisions:
- NetBox owns intent. Scripts write to NetBox only through the loader, and everything else reads.
- One prefix per VLAN, named consistently so exporters can group by role.
- Tokens are scoped. A write token for the loader, a read-only token for exporters.
- Stay behind a reverse proxy on the LAN. NetBox holds your full network map, so do not expose it to the internet.
Example addressing plan used throughout (documentation-style ranges, replace with yours):
| VLAN | Name | Prefix | Role |
|---|---|---|---|
| 10 | mgmt | 10.20.10.0/24 | Management |
| 20 | servers | 10.20.20.0/24 | Servers |
| 30 | iot | 10.20.30.0/24 | IoT |
| 40 | guest | 10.20.40.0/24 | Guest |
Step-by-Step Build
1. Deploy NetBox
You need a Linux host with Docker and the Compose plugin, 4 GB of RAM and a few GB of disk.
git clone -b release https://github.com/netbox-community/netbox-docker.git
cd netbox-docker
cp docker-compose.override.yml.example docker-compose.override.ymlEdit docker-compose.override.yml to publish the web port on the LAN interface only and to set the bootstrap admin. Generate the secrets first:
openssl rand -base64 48 # use for SECRET_KEY (50+ chars)
openssl rand -base64 48 # use for API_TOKEN_PEPPER_1Put the values in env/netbox.env (not in version control):
SECRET_KEY=<generated value>
API_TOKEN_PEPPER_1=<generated value>
SUPERUSER_NAME=admin
SUPERUSER_EMAIL=admin@example.com
SUPERUSER_PASSWORD=<long random password>
SUPERUSER_API_TOKEN=Two gotchas from recent releases: NetBox 4.5 and later issue v2 API tokens (prefixed nbt_), which require API_TOKEN_PEPPER_1 to be set, and the legacy SUPERUSER_API_TOKEN variable should be left empty. You will create a real token in the UI instead.
A minimal override that binds to a single address:
services:
netbox:
ports:
- "10.20.10.5:8000:8080"Start it and wait for the health check (the first migration takes a few minutes):
docker compose pull
docker compose up -d
docker compose ps
docker compose logs -f netbox | grep -m1 -i "Listening"Browse to http://10.20.10.5:8000, log in as admin, then go to your profile and open API Tokens. Create a v2 token with write access for the loader and a second, read-only token for exporters. The secret is shown once, so store it in a password manager.
2. Model the Network Manually (Once)
Before automating, click through the model so you understand the relationships:
- Organization > Sites: create
home-lab. - IPAM > VLANs: create the four VLANs from the table above.
- IPAM > Prefixes: create each /24, assign the matching VLAN and site, and set status to Active.
- DCIM > Manufacturers, Device Types, Device Roles: add what you own, for example a firewall, a managed switch and a hypervisor.
Key relationships: a device has interfaces; an interface carries IP addresses; a prefix contains addresses and maps to a VLAN. Marking one IP as the device's primary IPv4 is what exporters key off.
3. Bulk-Load an Existing Inventory with pynetbox
Describe your network in YAML. Keep it in a private repository, because it is sensitive.
# inventory.yml
site: home-lab
vlans:
- {vid: 10, name: mgmt}
- {vid: 20, name: servers}
- {vid: 30, name: iot}
prefixes:
- {prefix: 10.20.10.0/24, vlan: 10, description: Management}
- {prefix: 10.20.20.0/24, vlan: 20, description: Servers}
- {prefix: 10.20.30.0/24, vlan: 30, description: IoT}
devices:
- {name: fw01, role: firewall, type: generic-fw, ip: 10.20.10.1/24, iface: lan}
- {name: sw01, role: switch, type: generic-switch, ip: 10.20.10.2/24, iface: mgmt0}
- {name: hv01, role: hypervisor, type: generic-server, ip: 10.20.20.10/24, iface: eno1}
- {name: nas01, role: nas, type: generic-server, ip: 10.20.20.20/24, iface: eno1}Install the client and write an idempotent loader. Every call is "get or create", so you can re-run it safely.
python3 -m venv .venv && . .venv/bin/activate
pip install pynetbox pyyaml
export NETBOX_URL=http://10.20.10.5:8000
export NETBOX_TOKEN=<write token>#!/usr/bin/env python3
"""load_inventory.py - idempotently load inventory.yml into NetBox."""
import os
import sys
import pynetbox
import yaml
nb = pynetbox.api(os.environ["NETBOX_URL"], token=os.environ["NETBOX_TOKEN"])
# NetBox may sit behind a private CA; set REQUESTS_CA_BUNDLE rather than disabling verification.
def slug(s):
return s.lower().replace(" ", "-")
def get_or_create(endpoint, lookup, create=None):
obj = endpoint.get(**lookup)
if obj:
return obj
return endpoint.create({**lookup, **(create or {})})
with open(sys.argv[1]) as fh:
data = yaml.safe_load(fh)
site = get_or_create(nb.dcim.sites, {"slug": slug(data["site"])}, {"name": data["site"], "status": "active"})
vlans = {}
for v in data.get("vlans", []):
vlans[v["vid"]] = get_or_create(nb.ipam.vlans, {"vid": v["vid"], "site_id": site.id},
{"name": v["name"], "status": "active"})
for p in data.get("prefixes", []):
get_or_create(nb.ipam.prefixes, {"prefix": p["prefix"]},
{"vlan": vlans[p["vlan"]].id, "scope_type": "dcim.site", "scope_id": site.id,
"description": p.get("description", ""), "status": "active"})
mfr = get_or_create(nb.dcim.manufacturers, {"slug": "generic"}, {"name": "Generic"})
for d in data.get("devices", []):
role = get_or_create(nb.dcim.device_roles, {"slug": slug(d["role"])}, {"name": d["role"], "color": "3b82f6"})
dtype = get_or_create(nb.dcim.device_types, {"slug": slug(d["type"])},
{"model": d["type"], "manufacturer": mfr.id})
dev = get_or_create(nb.dcim.devices, {"name": d["name"], "site_id": site.id},
{"role": role.id, "device_type": dtype.id, "status": "active"})
iface = get_or_create(nb.dcim.interfaces, {"device_id": dev.id, "name": d["iface"]}, {"type": "1000base-t"})
ip = get_or_create(nb.ipam.ip_addresses, {"address": d["ip"]},
{"status": "active", "assigned_object_type": "dcim.interface",
"assigned_object_id": iface.id})
if not dev.primary_ip4:
dev.primary_ip4 = ip.id
dev.save()
print(f"ok {d['name']} {d['ip']}")Run it with python load_inventory.py inventory.yml. Field names such as scope_type for prefixes and role for devices changed across NetBox major versions (older releases used site and device_role). If the API returns a 400, read the message and compare with the interactive API browser at /api/, which always reflects your installed version.
4. Export an Ansible Inventory
NetBox has an official inventory plugin in the netbox.netbox collection.
ansible-galaxy collection install netbox.netbox# netbox_inventory.yml (filename must end in nb_inventory.yml or netbox_inventory.yml)
plugin: netbox.netbox.nb_inventory
api_endpoint: http://10.20.10.5:8000
validate_certs: true
config_context: false
group_by:
- device_roles
- sites
query_filters:
- status: active
compose:
ansible_host: primary_ip4.address | ansible.utils.ipaddr('address')Pass the read-only token through the environment (NETBOX_TOKEN) and test:
export NETBOX_TOKEN=<read-only token>
ansible-inventory -i netbox_inventory.yml --graph
ansible -i netbox_inventory.yml device_roles_hypervisor -m pingIf the graph shows your role groups and the ping reaches the hypervisors, NetBox is now driving automation. The compose line needs the ansible.utils collection and the netaddr Python package.
5. Export Prometheus Targets
Prometheus file_sd reads a JSON file, so a small exporter script is enough:
#!/usr/bin/env python3
"""nb_targets.py - write Prometheus file_sd targets from NetBox."""
import json
import os
import pynetbox
nb = pynetbox.api(os.environ["NETBOX_URL"], token=os.environ["NETBOX_TOKEN"])
groups = {}
for dev in nb.dcim.devices.filter(status="active", has_primary_ip=True):
ip = str(dev.primary_ip4.address).split("/")[0]
key = (str(dev.role.slug), str(dev.site.slug))
groups.setdefault(key, []).append(f"{ip}:9100")
out = [{"targets": t, "labels": {"role": r, "site": s}} for (r, s), t in groups.items()]
tmp = "/etc/prometheus/targets/netbox.json.tmp"
with open(tmp, "w") as fh:
json.dump(out, fh, indent=2)
os.replace(tmp, "/etc/prometheus/targets/netbox.json")Reference it in prometheus.yml:
scrape_configs:
- job_name: node
file_sd_configs:
- files: ["/etc/prometheus/targets/netbox.json"]
refresh_interval: 5mThe atomic os.replace avoids Prometheus reading a half-written file.
6. Add a Drift Check
A source of truth is only useful if it is accurate. This script compares live hosts with NetBox and reports both directions.
#!/usr/bin/env bash
# drift_check.sh - alive-but-undocumented and documented-but-dead
set -euo pipefail
PREFIX=10.20.20.0/24
nmap -sn -n "$PREFIX" -oG - | awk '/Up$/ {print $2}' | sort > /tmp/alive.txt
curl -fsS -H "Authorization: Bearer $NETBOX_TOKEN" \
"$NETBOX_URL/api/ipam/ip-addresses/?parent=$PREFIX&limit=1000" \
| python3 -c 'import sys,json;[print(r["address"].split("/")[0]) for r in json.load(sys.stdin)["results"]]' \
| sort > /tmp/documented.txt
echo "== Alive but NOT in NetBox =="; comm -23 /tmp/alive.txt /tmp/documented.txt
echo "== In NetBox but NOT alive =="; comm -13 /tmp/alive.txt /tmp/documented.txtTriage each line: either document the host or retire the stale record.
Testing
- API smoke test:
curl -s -H "Authorization: Bearer $NETBOX_TOKEN" $NETBOX_URL/api/status/should return the NetBox version and healthy workers. - Idempotency: run
load_inventory.pytwice and confirm the second run creates nothing (object counts under IPAM do not change). - Collision detection: try creating a duplicate IP in the UI. If your policy requires uniqueness, set the ENFORCE_GLOBAL_UNIQUE setting so NetBox rejects it.
- Exporters: confirm
ansible-inventory --graphand the Prometheus Status > Targets page match NetBox device counts. - Token scope: verify the read-only token gets a 403 on a POST request.
- Restore test: take a database dump (below), restore it into a scratch stack, and confirm the objects reappear.
Deployment
- Reverse proxy and TLS: put NetBox behind your existing proxy with an internal CA certificate. Set
ALLOWED_HOSTSin the NetBox environment to the real hostname. - Authentication: for more than one user, connect SSO via OIDC or LDAP and disable local accounts other than a break-glass admin.
- Backups: the PostgreSQL database holds everything. Schedule a nightly dump and keep copies off the host:
docker compose exec -T postgres pg_dump -U netbox netbox | gzip > netbox-$(date +%F).sql.gzMedia files (device images, attachments) live in the netbox-media-files volume, so include it as well.
- Upgrades: pull the new
releasebranch, read the NetBox release notes for breaking API changes, back up first, thendocker compose pull && docker compose up -d. Test your loader and exporters after every major version. - Scheduling: run the exporter every 5 minutes and the drift check nightly with systemd timers or cron on a management host.
- Change tracking: NetBox keeps a changelog of every edit. Review it periodically, and treat unexpected changes as a signal.
Extensions and Next Steps
- Webhooks and event rules: trigger an Ansible job or CI pipeline when a device status changes to "Planned" or "Decommissioning".
- Custom fields and tags: record owner, patch panel port, warranty date or data classification, then filter exporters on them.
- DNS from IPAM: generate forward and reverse zones for your resolver from NetBox IP records, which prevents a second copy of the truth.
- DHCP reservations: render static leases from NetBox for your DHCP server.
- Config validation: use the
diffsyncornetbox-diodeecosystem to reconcile discovered state with intent automatically. - Custom scripts and reports: NetBox can run Python reports in-app, such as a check that every active device has a primary IP.
- Security workflows: join the inventory with vulnerability scan results so findings map to an owner and a VLAN, and so rogue devices on the IoT VLAN stand out.
Once the inventory is trusted, every other project in your lab, from monitoring to patching to firewall rules, gets simpler because it can ask NetBox instead of guessing.