NetBox Branching
repository·main·Indexed 41 days ago
https://github.com/netboxlabs/netbox-branchingA 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.
What's inside NetBox Branching
- 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.
What is a NetBox Branch?
mainA branch represents a divergent state of the NetBox database, isolated within a dedicated PostgreSQL schema. Changes made within a branch do not affect themainbranch (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.Understand Change Diffs in NetBox Branching
mainA 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:
- Reviewing Changes: Simplifying the review process by showing the state of an object before and after branch modifications.
- Conflict Detection: Identifying and surfacing attribute-level conflicts between a branch and the
mainbranch to prevent accidental overwrites during sync or merge operations.
Avoid unrecoverable merge failures from editing after deletion
mainA merge will fail and become unrecoverable if you attempt to update an object in a branch that has already been deleted in the
mainbranch.Example Scenario:
- A
Siteis created inmain. - A branch is created.
- The
Siteis updated in the branch. - The
Siteis deleted inmain. - Result: The merge fails because the system cannot apply an update to a non-existent object.
- A
Activate a branch for API requests using X-NetBox-Branch
mainTo perform operations on NetBox objects within the context of a specific branch, you must include the
X-NetBox-BranchHTTP 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/- The value in the header does not include the
Understand Branch Events and operational history
mainBranch Events record the lifecycle operations of a branch, such as provisioning, syncing, merging, and more. The collection of events associated with a specific branch provides its complete operational history within NetBox Branching.How model compatibility works in NetBox Branching
mainNetBox Branching uses NetBox's
ObjectChangeaudit log to replay changes.Automatic Support
Any model that inherits from
ChangeLoggingMixin(directly or via base classes likeNetBoxModel,PrimaryModel,OrganizationalModel, orNestedGroupModel) 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).
- Models without
Understand how reverting affects the change log
mainReverting 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:
- Create site A
- Change device B description from "foo" to "bar"
- Delete tenant C
Reverting that branch will trigger these inverse actions in reverse order:
- Create tenant C (with original attributes)
- Change device B description from "bar" to "foo"
- Delete site A
The global change log will ultimately contain records for all six discrete changes (the original three and the three inverse actions).
How automatic branch recovery works
mainIf 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, orReverting).When
auto_recover_stuck_branchesisTrue(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 status Reset to Provisioning Failed Syncing Ready Migrating Pending Migrations Merging Ready Reverting Merged 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
Provisioningis reset toFailedbecause its schema may be incomplete. You should delete and recreate such branches.
PLUGINS_CONFIG = { 'netbox_branching': { 'auto_recover_stuck_branches': False, } }- For Syncing or Migrating, you can opt to re-run the operation by passing
Compare Iterative and Squash merge strategies
mainNetBox provides two strategies for applying branch changes to
main. Both read from theObjectChangeaudit log, but differ in application logic.Iterative (Default)
Replays every
ObjectChangelog entry from the branch intomainin 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
mainduring 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.
- Pros: Preserves full granular audit trail in
NetBox Branching Terminology
mainUnderstanding 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.
Perform dry runs during sync or merge
mainBy 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
commitparameter (defaults totrue).