NetBox Branching

repository·main·Indexed 41 days ago

https://github.com/netboxlabs/netbox-branching

A plugin for NetBox version 1.2.1 that enables database branching, allowing users to create isolated snapshots of the NetBox database for offline changes and reviews before merging them back into the main source of truth.

Tokens
15.5K
Snippets
37
Records
72
Agent score
97%

What's inside NetBox Branching

  1. What is NetBox Branching?

    main
    NetBox Branching is a plugin that introduces a version-control-like paradigm to NetBox. It allows users to create isolated copies (branches) of the NetBox data model. Changes made within a branch are independent and do not affect the 'Main' state or other branches until they are explicitly merged. This enables staging changes in isolated environments without impacting the production source of truth.
  2. What is a NetBox Branch?

    main
    A branch represents a divergent state of the NetBox database, isolated within a dedicated PostgreSQL schema. Changes made within a branch do not affect the main branch (or any other branch) until the branch is explicitly merged. This isolation allows for testing configuration changes or data updates in a safe environment before applying them to the production state.
  3. Understand Change Diffs in NetBox Branching

    main

    A Change Diff summarizes the net effect of all changes made to a specific NetBox object within a branch. Instead of showing every individual incremental change, it collapses successive modifications into a single comparison. This model is used for two primary purposes:

    1. Reviewing Changes: Simplifying the review process by showing the state of an object before and after branch modifications.
    2. Conflict Detection: Identifying and surfacing attribute-level conflicts between a branch and the main branch to prevent accidental overwrites during sync or merge operations.
  4. Avoid unrecoverable merge failures from editing after deletion

    main

    A merge will fail and become unrecoverable if you attempt to update an object in a branch that has already been deleted in the main branch.

    Example Scenario:

    1. A Site is created in main.
    2. A branch is created.
    3. The Site is updated in the branch.
    4. The Site is deleted in main.
    5. Result: The merge fails because the system cannot apply an update to a non-existent object.
  5. Activate a branch for API requests using X-NetBox-Branch

    main

    To perform operations on NetBox objects within the context of a specific branch, you must include the X-NetBox-Branch HTTP header in every request. This header must contain the branch's schema ID (a pseudorandom eight-character alphanumeric identifier).

    Important Notes:

    • The value in the header does not include the branch_ prefix used in the underlying database.
    • The header is only required when making changes to NetBox objects (like sites, prefixes, etc.) within a branch context. It is not required when managing the branches themselves.
    • To 'deactivate' a branch for subsequent requests, simply omit the header.
    # Example: Retrieve all site objects within a specific branch context
    curl -X POST \
    -H "Authorization: Token $TOKEN" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json; indent=4" \
    -H "X-NetBox-Branch: td5smq0f" \
    http://netbox:8000/api/dcim/sites/
  6. How model compatibility works in NetBox Branching

    main

    NetBox Branching uses NetBox's ObjectChange audit log to replay changes.

    Automatic Support

    Any model that inherits from ChangeLoggingMixin (directly or via base classes like NetBoxModel, PrimaryModel, OrganizationalModel, or NestedGroupModel) is automatically branchable. No extra code is needed.

    Unsupported Models

    • Models without ChangeLoggingMixin: These are excluded from branching. Changes made to them inside a branch are not isolated and affect the main schema immediately.
    • Multi-table inheritance: Models using Django's multi-table inheritance are incompatible. Each model in a branch must map to a single, self-contained table.

    Best Practices for Model Selection

    Branching is intended for network inventory or topology (e.g., devices, sites, prefixes). It is generally not appropriate for system-level or administrative state (e.g., user accounts, API tokens, permissions, or plugin configuration).

  7. Understand how reverting affects the change log

    main

    Reverting a branch is an additive process in terms of auditing; it does not erase history.

    When you revert a merged branch, NetBox does not delete the original merge records from the global change log. Instead, it creates new change records that represent the inverse of the original actions.

    Example Behavior: If a branch merge performed these actions:

    1. Create site A
    2. Change device B description from "foo" to "bar"
    3. Delete tenant C

    Reverting that branch will trigger these inverse actions in reverse order:

    1. Create tenant C (with original attributes)
    2. Change device B description from "bar" to "foo"
    3. Delete site A

    The global change log will ultimately contain records for all six discrete changes (the original three and the three inverse actions).

  8. How automatic branch recovery works

    main

    If a branch worker is killed abruptly (e.g., OOM kill, kill -9), the branch may be stuck in a transitional status (Provisioning, Syncing, Migrating, Merging, or Reverting).

    When auto_recover_stuck_branches is True (default), an hourly background job resets these orphaned statuses to a safe state. It does not re-run the interrupted operation to avoid infinite crash loops.

    Status Reset Mapping:

    Interrupted statusReset to
    ProvisioningFailed
    SyncingReady
    MigratingPending Migrations
    MergingReady
    RevertingMerged

    Manual Recovery: Users can manually recover branches via the Recover button in the UI or the /api/plugins/branching/branches/<id>/recover/ REST API endpoint.

    • For Syncing or Migrating, you can opt to re-run the operation by passing {"retry": true} to the REST API or checking the Sync the branch / Apply the outstanding migrations checkbox on the Recover page.
    • Warning: A branch interrupted during Provisioning is reset to Failed because its schema may be incomplete. You should delete and recreate such branches.
    PLUGINS_CONFIG = {
        'netbox_branching': {
            'auto_recover_stuck_branches': False,
        }
    }
  9. Compare Iterative and Squash merge strategies

    main

    NetBox provides two strategies for applying branch changes to main. Both read from the ObjectChange audit log, but differ in application logic.

    Iterative (Default)

    Replays every ObjectChange log entry from the branch into main in chronological order, one at a time.

    • Pros: Preserves full granular audit trail in main (original user and timestamp attribution).
    • Cons: Can fail if intermediate states violate constraints or if objects were modified/deleted in main during the branch lifecycle.

    Squash

    Collapses all changes made to each individual object in the branch into a single operation (the net effect) before applying it to main.

    • Pros: Sidesteps intermediate state errors; handles foreign key dependencies automatically (deletes before creates); useful for recovering from duplicate object conflicts.
    • Cons: main's changelog only shows the final state, attributed to the user who performed the merge, losing the granular history of the branch.
  10. NetBox Branching Terminology

    main

    Understanding the core concepts of the branching model:

    • Main: The primary NetBox state. Changes made outside of a specific branch context occur here.
    • Change: The creation, modification, or deletion of an object.
    • Branch: An independent copy of the NetBox data model that diverges from Main at a specific point in time.
    • Provisioning: The automatic process of creating a dedicated PostgreSQL schema for a new branch.
    • Synchronization: The process of pulling changes from Main into a specific branch to keep it up to date. Branches must be synchronized individually.
    • Migration: The process of applying database migrations to a branch schema, required after NetBox upgrades.
    • Merge: Incorporating changes from a branch back into Main.
    • Revert: Undoing a merge by replaying the changes in reverse order (available if the branch hasn't been archived or deleted).
    • Archive: Deprovisioning a branch's PostgreSQL schema while retaining its metadata. Archived branches cannot be reverted.
  11. Perform dry runs during sync or merge

    main

    By default, the NetBox web UI performs a "dry run" when synchronizing or merging. It replicates changes to check for errors and then aborts, returning the branch to its original state.

    To apply changes permanently via the UI, check the Commit changes checkbox before submitting the form.

    When using the REST API, control this behavior with the commit parameter (defaults to true).