How to model ISP datacenter peering in NetBox for automated BGP provisioning

How to model ISP datacenter peering in NetBox for automated BGP provisioning

ISP datacenters tend to outgrow “default” NetBox assumptions quickly: multi-tenant services, many concurrent peering contexts, repeated patterns across fabrics, and a need to generate config safely and idempotently. This tutorial shows how to model datacenter peering in netbox so it becomes a reliable source of truth for automated BGP provisioning.

The goal is not just documentation—it’s making NetBox operationally correct for automation: unambiguous objects, strict validation, and clean translation into config.


Design goals: what you must represent (and why common NetBox defaults fail at ISP scale)

What you must represent

At minimum, the NetBox model needs to express:

  • Tenants / customers / internal orgs
  • Who “owns” a peering relationship or service VRF.
  • Who pays, who gets contacted, and which policies apply.

  • Circuits and cross-connects

  • Transport delivery (carrier circuit, meet-me room handoff, ODF/patch).
  • Diversity (A/B feeds) and fate-sharing metadata.

  • Peering sessions

  • eBGP to peers (public IX, private interconnect, paid transit, PNIs).
  • Per-session attributes: local/remote AS, IPs, password, policy, timers, max-prefix, BFD, communities.

  • Routing context

  • VRFs (including “global” if you treat it as a VRF for modeling consistency).
  • Addressing ownership (loopbacks, SVIs, subinterfaces, p2p links).

  • Topology context

  • IGP adjacency (fabric routing: OSPF/IS-IS, iBGP underlay/EVPN, etc.) is not the same thing as peering.
  • Peering fabrics (IXLAN, PNI VLANs, shared peering switches) are often L2 constructs with L3 on top.

Why “default NetBox usage” fails at ISP scale

Common early mistakes:

  • Modeling BGP sessions as cables or interfaces only
    That loses intent: “this is a BGP session with policy X” vs “this port is connected.”

  • Treating every external peer as a Device
    You usually do not own it; you need a stable representation of the counterparty independent of hardware.

  • Overusing Circuits for everything
    Circuits are great for provider-delivered transport, but not for internal patching or “virtual” constructs like IX LAN sessions.

  • No separation between transport and routing
    A cross-connect is not a BGP session. A VLAN is not a policy. A link is not a neighbor.

The fix is to model physical connectivity and logical peering as distinct layers, tied together via references.


NetBox schema: custom fields, relationship objects, cable vs circuit modeling, and templates

This section describes a practical schema that maps cleanly to automation.

1) Choose the “ownership” primitives

Use these built-in objects consistently:

  • Tenant: the business owner of a peering relationship (could be “Backbone”, “Content Peering”, or an actual customer).
  • VRF: routing context where the session lives (global table can be represented by a VRF like GLOBAL if desired).
  • ASN: use NetBox’s BGP/ASN support if available in your version; otherwise model ASN on a peer object via custom fields.

2) Model transport correctly: Circuit vs Cable

A good split:

Use Circuits for:
- Carrier-provided links (wavelength, EPL, IP transit handoff if delivered as a circuit)
- Anything with circuit IDs, providers, install dates, LOAs

Use Cables for:
- In-datacenter patching (ToR ↔ patch panel, patch panel ↔ MMR)
- Direct cross-connects within your managed space

Pattern that works well
- Circuit termination → patch panel interface (front/rear ports if you model them)
- Cable patching to the router port
- Keep the router interface authoritative for the L3 address and VRF

This lets you answer:
- “Which provider is this service on?” (Circuit)
- “What is physically connected to this port?” (Cable)
- “Which VRF and IP is used for BGP?” (Interface/IPAM)

3) Model the peer as a first-class object (without forcing it to be a Device)

At ISP scale, you’ll want a reusable “peer” record:

Options:
- If you run NetBox Peering Manager plugin: use it (purpose-built for BGP peers and sessions).
- If you stay core-only: create a lightweight peer representation using:
- Contact / Tenant (for ownership)
- Custom object via plugin (ideal but requires dev)
- Or a pragmatic approach: use a Device with role external-peer and minimal fields (less ideal, but works if you need per-site tracking and contacts)

4) Use relationships for “session intent”

NetBox core doesn’t have a perfect native “BGP Session” object in all versions. For automation, you need a canonical place to store session attributes.

Practical approaches:

  • Preferred: Peering Manager plugin sessions (BGP Session objects with per-session settings).
  • Core-only: store sessions as a dedicated Config Context (structured data) attached to:
  • the local router device, or
  • the VRF, or
  • the interface

In practice, Config Context is often the least invasive and easiest to automate against.

5) Custom fields you will likely need

Whether stored on interfaces, VRFs, or config contexts, these fields are commonly required:

On VRF
- vrf_role: global, transit, peering, customer
- rd and rt_import/rt_export (if L3VPN)
- routing_policy_bundle (name of policy set to apply)

On Interface (L3 edge interface)
- edge_role: ixp, pni, transit, customer, backbone
- l2_service: VLAN ID or service tag (if subinterfaces/SVIs)
- peer_group: logical group name for BGP templating

On “Session intent” (Config Context / plugin object)
- local_as, remote_as
- local_ip, remote_ip (or references to NetBox IP objects)
- password (use NetBox Secrets if available; avoid plaintext)
- afi_safi: ipv4, ipv6, ipv4+ipv6
- import_policy, export_policy
- max_prefix, max_prefix_teardown
- bfd, ttl_security, gtsm_hops
- enabled flag

6) Sample YAML template for peering sessions (Config Context)

This is a practical “session intent” structure you can attach as a Config Context to the router (or VRF). It is YAML (not JSON), so it’s human-reviewable.

yaml
bgp:
  local_as: 65001
  vrfs:
    - name: GLOBAL
      router_id: 192.0.2.1
      peer_groups:
        - name: IXP-AMS-IPv4
          afi: ipv4
          import_policy: PL-IN-IXP
          export_policy: PL-OUT-IXP
          bfd: true
          ttl_security_hops: 1
          max_prefix: 200000
      neighbors:
        - description: "AS15169 Google AMS-IX v4"
          peer_group: IXP-AMS-IPv4
          remote_as: 15169
          local_ip: 198.51.100.10
          remote_ip: 198.51.100.20
          password_secret: "netbox/peering/amsix/google"
          enabled: true
        - description: "AS32934 Meta AMS-IX v4"
          peer_group: IXP-AMS-IPv4
          remote_as: 32934
          local_ip: 198.51.100.10
          remote_ip: 198.51.100.30
          enabled: false

7) Sample YAML template for VRFs

VRFs are often better modeled natively (NetBox VRF objects + RDs/RTs) but automation typically benefits from a rendered “desired-state” view:

yaml
vrfs:
  - name: GLOBAL
    role: global
  - name: CUST-ACME
    role: customer
    rd: "65001:1001"
    rt_import: ["65001:1001"]
    rt_export: ["65001:1001"]
    routing_policy_bundle: "CUST-ACME-POLICIES"

Automating the handoff: webhook + Ansible/SDK examples

A robust approach is:

  1. NetBox is the source of truth
  2. On change, webhook notifies your automation runner
  3. Runner fetches current state via NetBox API
  4. Render vendor config snippets (or structured config) from templates
  5. Apply idempotently and validate

Webhook trigger strategy

Trigger on updates to:
- Device
- Interface
- IP Address
- VRF
- Circuit termination (if your session depends on transport state)
- Config Context (if storing session intent there)

Ensure your webhook payload includes object ID + event type. Treat webhooks as signals, not as complete data; always re-query NetBox.

Python (pynetbox) example: fetch BGP intent from config context

Below is a minimal pattern for reading a device’s merged config context and extracting bgp intent.

python
import pynetbox

NB_URL = "https://netbox.example.net"
NB_TOKEN = "REDACTED"

nb = pynetbox.api(NB_URL, token=NB_TOKEN)

def get_device_bgp_intent(device_name: str) -> dict:
    dev = nb.dcim.devices.get(name=device_name)
    if not dev:
        raise ValueError(f"Device {device_name} not found")

    # NetBox exposes "config_context" as merged data for the device
    ctx = dev.config_context or {}
    bgp = ctx.get("bgp", {})
    return bgp

def neighbors_for_vrf(bgp: dict, vrf_name: str):
    for vrf in bgp.get("vrfs", []):
        if vrf.get("name") == vrf_name:
            return vrf.get("neighbors", [])
    return []

if __name__ == "__main__":
    bgp = get_device_bgp_intent("edge01-dc1")
    for n in neighbors_for_vrf(bgp, "GLOBAL"):
        if not n.get("enabled", True):
            continue
        print(f"neighbor {n['remote_ip']} remote-as {n['remote_as']}")

Ansible pattern: idempotency notes

For idempotent provisioning, prefer:
- vendor modules that push structured config (e.g., EOS eos_config, Junos junos_config, NX-OS modules)
- or generate “set-style”/structured snippets and use replace/merge semantics

Idempotency tips:
- Render neighbors in a stable order (sort by remote_ip).
- Include explicit removals when sessions are disabled/deleted (a “garbage collection” step).
- Use device-side “candidate config” mechanisms where available (Junos, EOS with sessions) and commit/abort.

A typical flow:
- Pull NetBox intent → render template → push candidate → run pre-check commands → commit.


Validation and safety: pre-checks, staging, synthetic traffic

Automation without safety rails will eventually push a wrong neighbor, wrong AS, or overlapping IP and cause an outage. Build validation into the pipeline.

Automated pre-checks (fail fast)

Run these checks from the NetBox data before generating config:

  • IP conflicts
  • local_ip must exist on exactly one interface on the target device (and in the correct VRF).
  • remote_ip must not exist anywhere in your IPAM as assigned to your infrastructure.
  • L2/L3 mismatch: local_ip and remote_ip should be in the same prefix (for directly connected eBGP).

  • AS number sanity

  • remote_as must not equal local_as (unless you explicitly allow same-AS scenarios).
  • remote_as should match your peer record / allowed list.

  • Overlap detection

  • Prevent allocating the same peering subnet to multiple fabrics.
  • Prevent duplicate neighbor definitions (same remote_ip in same VRF).

  • Policy presence

  • import/export policy names must be defined in your policy repo (if you manage policy-as-code).
  • enforce “no policy, no session” for external peers.

  • Max-prefix defaults

  • Ensure max-prefix is always set for eBGP, with sane thresholds.

Dry-run testing against a staging fabric

A practical staging approach:

  • Mirror the NetBox model into a staging environment (separate site/tenant or tags).
  • Push configs to lab routers or virtual NOS.
  • Validate:
  • BGP establishes (or intentionally doesn’t, if waiting on peer)
  • route-map/policy attaches correctly
  • no unexpected route leaks (check advertised/received routes)

Synthetic traffic checks

After deployment, validate forwarding, not just control plane:

  • For IX/PNI: probe known endpoints via the peer path
  • For transit: ensure default route behavior matches expected policy
  • Use:
  • ping + traceroute from VRF contexts
  • BGP looking glass validation: advertised prefixes count, received prefix count
  • flow logs / telemetry to confirm traffic shifts

Runbook & troubleshooting: failure modes, remediation, monitoring hooks

Common failure modes (and what usually causes them)

1) Stale topology in NetBox

Symptoms
- Config pushes to wrong interface/VRF
- Neighbor IP belongs to an old subnet

Causes
- Cabling changed but NetBox not updated
- Interface moved to different VRF without updating session intent

Remediation
- Make link changes require NetBox update before commit (process gate)
- Add a “last_verified” custom field/tag on edge interfaces
- Periodic reconciliation: compare LLDP neighbors to NetBox cables and alert on drift

2) Dual-injection / duplicated neighbors

Symptoms
- Same peer appears twice (two sessions in same VRF unintentionally)
- Route dampening, oscillations, or unexpected best-path changes

Causes
- Both fabric edges configured with the same peering IPs
- Copy/paste session intent reused without unique addressing

Remediation
- Enforce uniqueness: (vrf, remote_ip) must be unique per device, and ideally per site/fabric
- Add pre-check: remote_ip cannot appear in multiple devices unless explicitly marked as multihop design

3) AS-PATH / policy issues (route leak or no routes)

Symptoms
- Session up but prefixes rejected
- Unexpected transit usage or peer routes not preferred

Causes
- Wrong import/export policy applied
- Missing communities, incorrect local-pref, or next-hop handling

Remediation
- Make policy selection explicit in NetBox intent (don’t infer from interface names)
- Add post-checks: verify policy attachment and prefix counters
- Monitor advertised/received prefix deltas and alarm on sudden changes

4) Password / auth drift

Symptoms
- BGP flaps, “authentication failure” logs

Causes
- Secrets rotated on one side only
- Password stored in plaintext and inconsistently copied

Remediation
- Use a centralized secret reference (password_secret) and fetch at runtime
- Implement a rotation workflow: update secret → stage → commit → confirm

Monitoring hooks to keep the model honest

  • NetBox drift detection
  • Compare device state (LLDP, interface IPs, VRFs) to NetBox and alert
  • BGP session SLOs
  • Up/down status, flaps per hour/day
  • prefix count thresholds (min/max)
  • Change correlation
  • Tie automation runs to NetBox change IDs (store as commit comment / device annotation)
  • Alert when device config changes without a corresponding NetBox change event

Common pitfalls

  • Overloading Circuits for internal cross-connects: you lose physical patch visibility and make troubleshooting harder.
  • Modeling peers as Devices everywhere: creates noise and implies ownership; prefer a peer object or structured intent.
  • Implicit policies (deriving import/export from naming conventions): works until it doesn’t; store policy names explicitly.
  • No garbage collection: deleting a session in NetBox but leaving it on devices causes zombie neighbors and confusion.
  • No uniqueness constraints in validation: duplicates will happen at scale unless the pipeline enforces invariants.
  • Treating “BGP up” as success: always validate prefix counters and forwarding behavior.

Key takeaways

  • Model transport (cables/circuits) separately from routing intent (BGP sessions and policy).
  • At ISP scale, netbox defaults need augmentation: structured intent (Config Context or peering plugin), explicit policy references, and validation.
  • Use webhooks as triggers, but always re-query NetBox to build current desired state.
  • Make automation safe with pre-checks, staging dry-runs, and post-change synthetic traffic.
  • Keep the source of truth honest with drift detection and monitoring tied to NetBox change events.