### Serve Documentation Locally Source: https://github.com/netbox-community/netbox/blob/main/docs/development/release-checklist.md Start the documentation server to review installation guides and perform manual checks. This command is used to catch errors or omissions in the documentation before a release. ```bash zensical serve ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/netbox-community/netbox/blob/main/AGENTS.md Starts a local web server to preview the NetBox documentation. Requires MkDocs to be installed. ```bash mkdocs serve ``` -------------------------------- ### NetBox Development Setup Source: https://github.com/netbox-community/netbox/blob/main/AGENTS.md Initializes a Python virtual environment, installs dependencies, copies configuration, and applies initial migrations. ```bash python -m venv ~/.venv/netbox source ~/.venv/netbox/bin/activate pip install -r requirements.txt # Copy and configure cp netbox/netbox/configuration.example.py netbox/netbox/configuration.py # Edit configuration.py: set DATABASE, REDIS, SECRET_KEY, ALLOWED_HOSTS cd netbox/ python manage.py migrate python manage.py runserver ``` -------------------------------- ### Example API Request with v2 Token Source: https://github.com/netbox-community/netbox/blob/main/docs/integrations/rest-api.md This example demonstrates a typical GET request to the sites API endpoint using a v2 authentication token. ```bash $ curl -H "Authorization: Bearer nbt_4F9DAouzURLb.zjebxBPzICiPbWz0Wtx0fTL7bCKXKGTYhNzkgC2S" \ -H "Accept: application/json; indent=4" \ https://netbox/api/dcim/sites/ { "count": 10, "next": null, "previous": null, "results": [...] } ``` -------------------------------- ### Cursor Pagination Example Source: https://github.com/netbox-community/netbox/blob/main/docs/integrations/graphql-api.md Illustrates cursor-based pagination for retrieving device lists. The `start` parameter uses the primary key of the last seen record to fetch subsequent records efficiently. ```APIDOC ## Cursor Pagination ### Description Utilize cursor-based pagination by specifying a `start` value (primary key of the last record) and a `limit` to fetch records sequentially. ### Query ```graphql query { device_list(pagination: {start: 0, limit: 20}) { id } } ``` ### Query ```graphql query { device_list(pagination: {start: 124, limit: 20}) { id } } ``` ``` -------------------------------- ### Install Git Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/3-netbox.md Installs the Git version control system if it is not already present on the system. ```bash sudo apt install -y git ``` -------------------------------- ### Offset Pagination Example Source: https://github.com/netbox-community/netbox/blob/main/docs/integrations/graphql-api.md Demonstrates how to use offset-based pagination to retrieve a list of devices. The `offset` parameter specifies the starting point, and `limit` controls the number of records returned. ```APIDOC ## Offset Pagination ### Description Use offset-based pagination to retrieve data by specifying an `offset` from the beginning of the dataset and a `limit` for the number of records. ### Query ```graphql query { device_list(pagination: {offset: 0, limit: 20}) { id } } ``` ### Query ```graphql query { device_list(pagination: {offset: 20, limit: 20}) { id } } ``` ``` -------------------------------- ### Router Example Source: https://github.com/netbox-community/netbox/blob/main/docs/plugins/development/rest-api.md Example of registering a plugin's viewset with a router in api/urls.py. ```APIDOC ## Router Example ### Description Example of registering a plugin's viewset with a router in `api/urls.py`. ### Code ```python # api/urls.py from netbox.api.routers import NetBoxRouter from .views import MyModelViewSet router = NetBoxRouter() router.register('my-model', MyModelViewSet) urlpatterns = router.urls ``` This will make the plugin's view accessible at `/api/plugins/my-plugin/my-model/`. ``` -------------------------------- ### Retrieve an IP Address Source: https://github.com/netbox-community/netbox/blob/main/docs/integrations/rest-api.md This example demonstrates how to retrieve information about a specific IP address using a GET request and format the output with `jq`. ```APIDOC ## GET /api/ipam/ip-addresses/{id}/ ### Description Retrieves details for a specific IP address. ### Method GET ### Endpoint /api/ipam/ip-addresses/{id}/ ### Parameters #### Path Parameters - **id** (integer) - Required - The unique ID of the IP address to retrieve. ### Request Example ```bash curl -s http://netbox/api/ipam/ip-addresses/2954/ | jq '.' ``` ### Response #### Success Response (200) - **id** (integer) - Unique identifier for the IP address. - **url** (string) - The API URL for the IP address. - **family** (object) - IP address family (IPv4 or IPv6). - **address** (string) - The IP address with its subnet mask. - **vrf** (object or null) - The VRF assigned to the IP address. - **tenant** (object or null) - The tenant assigned to the IP address. - **status** (object) - The operational status of the IP address. - **role** (object or null) - The role assigned to the IP address. - **assigned_object_type** (string) - The type of object this IP is assigned to. - **assigned_object_id** (integer) - The ID of the object this IP is assigned to. - **assigned_object** (object) - Details of the object this IP is assigned to. - **nat_inside** (object or null) - The NAT inside IP address. - **nat_outside** (object or null) - The NAT outside IP address. - **dns_name** (string) - The DNS name associated with the IP address. - **description** (string) - A description for the IP address. - **tags** (array) - A list of tags associated with the IP address. - **custom_fields** (object) - Custom fields for the IP address. - **created** (string) - The date the IP address was created. - **last_updated** (string) - The date the IP address was last updated. #### Response Example ```json { "id": 2954, "url": "http://netbox/api/ipam/ip-addresses/2954/", "family": { "value": 4, "label": "IPv4" }, "address": "192.168.0.42/26", "vrf": null, "tenant": null, "status": { "value": "active", "label": "Active" }, "role": null, "assigned_object_type": "dcim.interface", "assigned_object_id": 114771, "assigned_object": { "id": 114771, "url": "http://netbox/api/dcim/interfaces/114771/", "device": { "id": 2230, "url": "http://netbox/api/dcim/devices/2230/", "name": "router1", "display_name": "router1" }, "name": "et-0/1/2", "cable": null, "connection_status": null }, "nat_inside": null, "nat_outside": null, "dns_name": "", "description": "Example IP address", "tags": [], "custom_fields": {}, "created": "2020-08-04", "last_updated": "2020-08-04T14:12:39.666885Z" } ``` ``` -------------------------------- ### Enable and Start NetBox Services Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/4b-uwsgi.md Enable and start the NetBox WSGI and worker services to initiate at boot time. ```bash sudo systemctl enable --now netbox netbox-rq ``` -------------------------------- ### Install Plugin Package Source: https://github.com/netbox-community/netbox/blob/main/netbox/templates/core/inc/plugin_installation.html Install the plugin package using pip within the NetBox virtual environment. ```bash source /opt/netbox/venv/bin/activate pip install {{ plugin.slug }} ``` -------------------------------- ### Authentication Header Examples Source: https://github.com/netbox-community/netbox/blob/main/docs/integrations/rest-api.md Examples of how to format the Authorization header for v2 and legacy v1 API tokens. ```APIDOC ## Authenticating to the API An authentication token is included with a request in its `Authorization` header. The format of the header value depends on the version of token in use. v2 tokens use the following form, concatenating the token's prefix (`nbt_`) and key with its plaintext value, separated by a period: ``` Authorization: Bearer nbt_. ``` Legacy v1 tokens use the prefix `Token` rather than `Bearer`, and include only the token plaintext. (v1 tokens do not have a key.) ``` Authorization: Token ``` ``` -------------------------------- ### Install Pre-Commit Hooks and Ruff Source: https://github.com/netbox-community/netbox/blob/main/docs/development/getting-started.md Install the necessary tools for pre-commit hooks, including the Ruff linter. This should be done before committing any changes to ensure code quality. ```bash python -m pip install ruff pre-commit pre-commit install ``` -------------------------------- ### Install pyuwsgi Package Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/4b-uwsgi.md Activate the Python virtual environment and install the pyuwsgi package using pip. ```bash source /opt/netbox/venv/bin/activate pip3 install pyuwsgi ``` -------------------------------- ### Gunicorn Service Status Example Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/4a-gunicorn.md Example output from 'systemctl status netbox.service' showing the Gunicorn WSGI service running. ```text ● netbox.service - NetBox WSGI Service Loaded: loaded (/etc/systemd/system/netbox.service; enabled; preset: enabled) Active: active (running) since Mon 2026-01-26 11:00:00 CST; 7s ago Docs: https://docs.netbox.dev/ Main PID: 7283 (gunicorn) Tasks: 6 (limit: 4545) Memory: 556.1M (peak: 556.3M) CPU: 3.387s CGroup: /system.slice/netbox.service ├─7283 /opt/netbox/venv/bin/python3 /opt/netbox/venv/bin/gunicorn --pid /var/tmp/netbox.pid --pythonpath /opt/netbox/netbox> ├─7285 /opt/netbox/venv/bin/python3 /opt/netbox/venv/bin/gunicorn --pid /var/tmp/netbox.pid --pythonpath /opt/netbox/netbox> ├─7286 /opt/netbox/venv/bin/python3 /opt/netbox/venv/bin/gunicorn --pid /var/tmp/netbox.pid --pythonpath /opt/netbox/netbox> ├─7287 /opt/netbox/venv/bin/python3 /opt/netbox/venv/bin/gunicorn --pid /var/tmp/netbox.pid --pythonpath /opt/netbox/netbox> ├─7288 /opt/netbox/venv/bin/python3 /opt/netbox/venv/bin/gunicorn --pid /var/tmp/netbox.pid --pythonpath /opt/netbox/netbox> └─7289 /opt/netbox/venv/bin/python3 /opt/netbox/venv/bin/gunicorn --pid /var/tmp/netbox.pid --pythonpath /opt/netbox/netbox> Jan 26 11:00:00 netbox systemd[1]: Started netbox.service - NetBox WSGI Service. ... ``` -------------------------------- ### Install Plugin Manually (Python Executable) Source: https://github.com/netbox-community/netbox/blob/main/docs/plugins/installation.md Install a plugin by invoking `pip` through NetBox's virtual environment's Python executable. This avoids the need to activate the virtual environment directly. ```bash sudo /opt/netbox/venv/bin/python3 -m pip install ``` -------------------------------- ### Create NetBox Installation Directory Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/3-netbox.md Creates the base directory for NetBox installation if it does not already exist. ```bash sudo mkdir -p /opt/netbox/ cd /opt/netbox/ ``` -------------------------------- ### Install Apache for NetBox Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/5-http-server.md Installs Apache on Ubuntu 24.04. This is the first step in setting up Apache as the HTTP server for NetBox. ```bash sudo apt install -y apache2 ``` -------------------------------- ### Example Plugin Template Extension Source: https://github.com/netbox-community/netbox/blob/main/docs/plugins/development/views.md Demonstrates how to create a plugin template extension to inject custom content into a specific view. This example adds animal count information to the site view. ```python from netbox.plugins import PluginTemplateExtension from .models import Animal class SiteAnimalCount(PluginTemplateExtension): models = ['dcim.site'] def right_page(self): return self.render('netbox_animal_sounds/inc/animal_count.html', extra_context={ 'animal_count': Animal.objects.count(), }) template_extensions = [SiteAnimalCount] ``` -------------------------------- ### Basic Circuit Query Example Source: https://github.com/netbox-community/netbox/blob/main/docs/integrations/graphql-api.md This example demonstrates how to query for circuit IDs and provider names of active circuits using the GraphQL API. ```APIDOC ## Querying Circuits ### Description Fetches a list of circuits, filtered by status, and returns their IDs and provider names. ### Method POST ### Endpoint /graphql/ ### Parameters #### Request Body - **query** (string) - Required - The GraphQL query string. ### Request Example ```json { "query": "query { circuit_list(filters:{status: STATUS_ACTIVE}) {cid provider {name}}}" } ``` ### Response #### Success Response (200) - **data** (object) - Contains the query results. - **circuits** (array) - A list of circuit objects. - **cid** (string) - The circuit ID. - **provider** (object) - Information about the provider. - **name** (string) - The provider's name. #### Response Example ```json { "data": { "circuits": [ { "cid": "1002840283", "provider": { "name": "CenturyLink" } }, { "cid": "1002840457", "provider": { "name": "CenturyLink" } } ] } } ``` ``` -------------------------------- ### Enable and Start NetBox Services Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/4a-gunicorn.md Enable and start the NetBox WSGI and background worker services to initiate at boot time. Verify the WSGI service status. ```bash sudo systemctl enable --now netbox netbox-rq systemctl status netbox.service ``` -------------------------------- ### Check NetBox Installation Method Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/upgrading.md Determine if NetBox was installed from a release package or a git repository by checking the existence and type of /opt/netbox and /opt/netbox/.git. ```bash ls -ld /opt/netbox /opt/netbox/.git ``` -------------------------------- ### Cursor-Based Pagination with `start` Parameter Source: https://github.com/netbox-community/netbox/blob/main/docs/release-notes/version-4.6.md All list endpoints now support cursor-based pagination using the `start` query parameter. ```APIDOC ## Cursor-Based Pagination with `start` Parameter ### Description Introduces cursor-based pagination for all list endpoints, allowing clients to fetch data in a paginated manner using a `start` parameter. ### Method GET ### Endpoint All list endpoints (e.g., `/api/dcim/devices/`) ### Parameters #### Query Parameters - **start** (string) - Optional - The cursor value to start pagination from. ``` -------------------------------- ### Example Dashboard Widget with Configuration Source: https://github.com/netbox-community/netbox/blob/main/docs/plugins/development/dashboard-widgets.md This example demonstrates a `ReminderWidget` with a configurable content field using `forms.CharField` and `forms.Textarea`. The widget's content is rendered from its configuration. ```python from django import forms from extras.dashboard.utils import register_widget from extras.dashboard.widgets import DashboardWidget, WidgetConfigForm @register_widget class ReminderWidget(DashboardWidget): default_title = 'Reminder' description = 'Add a virtual sticky note' class ConfigForm(WidgetConfigForm): content = forms.CharField( widget=forms.Textarea() ) def render(self, request): return self.config.get('content') ``` -------------------------------- ### Install nginx for NetBox Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/5-http-server.md Installs nginx on Ubuntu 24.04. This is the first step in setting up nginx as the HTTP server for NetBox. ```bash sudo apt install -y nginx ``` -------------------------------- ### Install Plugin Manually (Root Shell) Source: https://github.com/netbox-community/netbox/blob/main/docs/plugins/installation.md Manually install a plugin using `pip` within the NetBox virtual environment. This method requires switching to a root shell. ```bash sudo -i # source /opt/netbox/venv/bin/activate (venv) # pip install ``` -------------------------------- ### Example Custom Link URL Source: https://github.com/netbox-community/netbox/blob/main/docs/customization/custom-links.md This example demonstrates how to construct a URL for a custom link using Jinja templating to include data from the NetBox object being viewed. ```html View NMS ``` -------------------------------- ### Start NetBox Development Server Source: https://github.com/netbox-community/netbox/blob/main/docs/development/getting-started.md Start the Django development server to run NetBox locally. This server auto-updates in response to code changes and is essential for development. ```bash $ ./manage.py runserver ``` -------------------------------- ### API Status Endpoint Example Source: https://github.com/netbox-community/netbox/blob/main/netbox/templates/users/panels/token_example.html This example demonstrates how to make a GET request to the API status endpoint using a bearer token for authentication. ```APIDOC ## GET /api/status/ ### Description Retrieves the status of the Netbox API. ### Method GET ### Endpoint /api/status/ ### Request Headers - **Authorization** (string) - Required - Bearer token for authentication. Format: `Bearer ` - **Content-Type** (string) - Required - `application/json` - **Accept** (string) - Optional - `application/json; indent=4` ### Request Example ```bash curl -X GET \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -H "Accept: application/json; indent=4" \ http://localhost:8000/api/status/ ``` ### Response #### Success Response (200) - **version** (string) - The version of Netbox. - **ready** (boolean) - Indicates if the API is ready. #### Response Example ```json { "version": "3.7.0", "ready": true } ``` ``` -------------------------------- ### Copy NetBox Configuration File Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/3-netbox.md Copies the example configuration file to 'configuration.py' in the NetBox configuration directory, preparing it for local customization. ```bash cd /opt/netbox/netbox/netbox/ sudo cp configuration_example.py configuration.py ``` -------------------------------- ### Run Development Server Source: https://github.com/netbox-community/netbox/blob/main/AGENTS.md Starts the NetBox development server. Ensure you are in the 'netbox/' directory with your virtual environment activated. ```bash python manage.py runserver ``` -------------------------------- ### Example: New Branch Provisioning Script Source: https://github.com/netbox-community/netbox/blob/main/docs/customization/custom-scripts.md A Python script to provision a new branch site, including creating the site and access switches. It prompts the user for site name, switch count, and switch model via a web form. ```python from django.utils.text import slugify from dcim.choices import DeviceStatusChoices, SiteStatusChoices from dcim.models import Device, DeviceRole, DeviceType, Manufacturer, Site from extras.scripts import * class NewBranchScript(Script): class Meta(Script.Meta): name = "New Branch" description = "Provision a new branch site" field_order = ['site_name', 'switch_count', 'switch_model'] site_name = StringVar( description="Name of the new site" ) switch_count = IntegerVar( description="Number of access switches to create" ) manufacturer = ObjectVar( model=Manufacturer, required=False ) switch_model = ObjectVar( description="Access switch model", model=DeviceType, query_params={ 'manufacturer_id': '$manufacturer' } ) def run(self, data, commit): # Create the new site site = Site( name=data['site_name'], slug=slugify(data['site_name']), status=SiteStatusChoices.STATUS_PLANNED ) site.full_clean() site.save() self.log_success(f"Created new site: {site}") # Create access switches switch_role = DeviceRole.objects.get(name='Access Switch') for i in range(1, data['switch_count'] + 1): switch = Device( device_type=data['switch_model'], name=f'{site.slug}-switch{i}', site=site, status=DeviceStatusChoices.STATUS_PLANNED, role=switch_role ) switch.full_clean() switch.save() self.log_success(f"Created new switch: {switch}") # Generate a CSV table of new devices output = [ 'name,make,model' ] for switch in Device.objects.filter(site=site): attrs = [ switch.name, switch.device_type.manufacturer.name, switch.device_type.model ] output.append(','.join(attrs)) return '\n'.join(output) ``` -------------------------------- ### Example Active Directory Configuration Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/6-ldap.md A comprehensive example configuration for integrating NetBox with Active Directory. This includes server URI, connection options, service account credentials, certificate handling, user and group search parameters, attribute mapping, and group-based permissions. ```python import ldap from django_auth_ldap.config import LDAPSearch, NestedGroupOfNamesType # Server URI AUTH_LDAP_SERVER_URI = "ldaps://ad.example.com:3269" # The following may be needed if you are binding to Active Directory. AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_REFERRALS: 0 } # Set the DN and password for the NetBox service account. AUTH_LDAP_BIND_DN = "CN=NETBOXSA,OU=Service Accounts,DC=example,DC=com" AUTH_LDAP_BIND_PASSWORD = "demo" # Include this setting if you want to ignore certificate errors. This might be needed to accept a self-signed cert. # Note that this is a NetBox-specific setting which sets: # ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) LDAP_IGNORE_CERT_ERRORS = False # Include this setting if you want to validate the LDAP server certificates against a CA certificate directory on your server # Note that this is a NetBox-specific setting which sets: # ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, LDAP_CA_CERT_DIR) LDAP_CA_CERT_DIR = '/etc/ssl/certs' # Include this setting if you want to validate the LDAP server certificates against your own CA. # Note that this is a NetBox-specific setting which sets: # ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, LDAP_CA_CERT_FILE) LDAP_CA_CERT_FILE = '/path/to/example-CA.crt' # This search matches users with the sAMAccountName equal to the provided username. This is required if the user's # username is not in their DN (Active Directory). AUTH_LDAP_USER_SEARCH = LDAPSearch( "ou=Users,dc=example,dc=com", ldap.SCOPE_SUBTREE, "( |(userPrincipalName=%(user)s)(sAMAccountName=%(user)s))" ) # If a user's DN is producible from their username, we don't need to search. AUTH_LDAP_USER_DN_TEMPLATE = None # You can map user attributes to Django attributes as so. AUTH_LDAP_USER_ATTR_MAP = { "username": "sAMAccountName", "email": "mail", "first_name": "givenName", "last_name": "sn", } AUTH_LDAP_USER_QUERY_FIELD = "username" # This search ought to return all groups to which the user belongs. django_auth_ldap uses this to determine group # hierarchy. AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "dc=example,dc=com", ldap.SCOPE_SUBTREE, "(objectClass=group)" ) AUTH_LDAP_GROUP_TYPE = NestedGroupOfNamesType() # Define a group required to login. AUTH_LDAP_REQUIRE_GROUP = "CN=NETBOX_USERS,DC=example,DC=com" # Mirror LDAP group assignments. AUTH_LDAP_MIRROR_GROUPS = True # Define special user types using groups. Exercise great caution when assigning superuser status. AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "cn=active,ou=groups,dc=example,dc=com", "is_superuser": "cn=superuser,ou=groups,dc=example,dc=com" } # For more granular permissions, we can map LDAP groups to Django groups. AUTH_LDAP_FIND_GROUP_PERMS = True ``` -------------------------------- ### Retrieving Multiple Objects Example Source: https://github.com/netbox-community/netbox/blob/main/docs/integrations/rest-api.md To retrieve a list of objects, make a GET request to the model's list endpoint. The objects are returned within the 'results' parameter of the JSON response. ```APIDOC ## GET /api/ipam/ip-addresses/ ### Description Retrieves a list of IP addresses. ### Method GET ### Endpoint /api/ipam/ip-addresses/ ### Request Example ```no-highlight curl -s -X GET http://netbox/api/ipam/ip-addresses/ | jq '.' ``` ### Response #### Success Response (200) - **count** (integer) - The total number of IP addresses. - **next** (string) - URL for the next page of results. - **previous** (null) - URL for the previous page of results. - **results** (array) - A list of IP address objects. ### Response Example ```json { "count": 42031, "next": "http://netbox/api/ipam/ip-addresses/?limit=50&offset=50", "previous": null, "results": [ { "id": 5618, "address": "192.0.2.1/24", ... }, { "id": 5619, "address": "192.0.2.2/24", ... }, { "id": 5620, "address": "192.0.2.3/24", ... }, ... ] } ``` ``` -------------------------------- ### Cursor-Based Pagination Example Source: https://github.com/netbox-community/netbox/blob/main/docs/integrations/rest-api.md For large datasets, cursor-based pagination offers an alternative to offset-based pagination. It uses the 'start' query parameter (minimum primary key) and 'limit' to efficiently filter results. ```APIDOC ## GET /api/[app]/[model]/ ### Description Retrieves a paginated list of objects using cursor-based pagination. ### Method GET ### Endpoint /api/[app]/[model]/ ### Query Parameters - **start** (integer) - Optional - The minimum primary key value to start retrieving objects from. - **limit** (integer) - Optional - The number of objects to return per page. Defaults to `PAGINATE_COUNT`. ### Response #### Success Response (200) - **count** (null) - Always null in cursor mode. - **next** (string) - A hyperlink to the next page of results (if applicable). - **previous** (null) - Always null in cursor mode. - **results** (array) - The list of objects on the current page. ### Response Example ```json { "count": null, "next": "http://netbox/api/dcim/devices/?start=356&limit=100", "previous": null, "results": [ { "id": 109, "name": "dist-router07", ... }, ... { "id": 356, "name": "acc-switch492", ... } ] } ``` ``` -------------------------------- ### Customize Default Permissions for All Users Source: https://github.com/netbox-community/netbox/blob/main/docs/configuration/security.md Define object permissions automatically applied to any authenticated user. Overriding this setting replaces the default mapping, so ensure default permissions are reproduced if they need to be retained. The example shows how to grant all users the ability to create a device role starting with 'temp'. ```python DEFAULT_PERMISSIONS = { 'dcim.add_devicerole': ( {'name__startswith': 'temp'}, ) } ``` -------------------------------- ### Install NetBox System Packages Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/3-netbox.md Installs essential system packages required for NetBox and its dependencies. Ensure Python 3.12 or later is installed. ```bash sudo apt install -y python3 python3-pip python3-venv python3-dev \ build-essential libxml2-dev libxslt1-dev libffi-dev libpq-dev \ libssl-dev zlib1g-dev ``` -------------------------------- ### Running the Upgrade Script Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/upgrading.md Execute the upgrade script to rebuild the virtual environment, install dependencies, apply database migrations, and collect static files. ```bash sudo ./upgrade.sh ``` -------------------------------- ### Generate Nagios Host Configuration from Devices Source: https://github.com/netbox-community/netbox/blob/main/docs/customization/export-templates.md This example demonstrates generating a Nagios host configuration from a list of devices. It checks for the existence of status and primary IP before defining a host. ```jinja2 {% for device in queryset %}{% if device.status and device.primary_ip %}define host{ use generic-switch host_name {{ device.name }} address {{ device.primary_ip.address.ip }} } {% endif %}{% endfor %} ``` -------------------------------- ### Install PostgreSQL Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/1-postgresql.md Installs PostgreSQL on Debian/Ubuntu systems. Ensure you have PostgreSQL 14 or later. ```bash sudo apt update sudo apt install -y postgresql ``` -------------------------------- ### Forbidden Response Example Source: https://github.com/netbox-community/netbox/blob/main/docs/integrations/rest-api.md Example of a 403 Forbidden response when authentication is required but not provided. ```APIDOC ## Forbidden Response Example When a token is required but not present in a request, the API will return a 403 (Forbidden) response: ```bash $ curl https://netbox/api/dcim/sites/ { "detail": "Authentication credentials were not provided." } ``` ``` -------------------------------- ### Build Static Documentation Source: https://github.com/netbox-community/netbox/blob/main/AGENTS.md Generates a static HTML site for the NetBox documentation. This is used for deployment. ```bash mkdocs build ``` -------------------------------- ### Model Viewset Example Source: https://github.com/netbox-community/netbox/blob/main/docs/plugins/development/rest-api.md Example of creating a custom viewset for a plugin model using NetBoxModelViewSet. ```APIDOC ## Model Viewset Example ### Description Example of creating a custom viewset for a plugin model using `NetBoxModelViewSet`. ### Code ```python # api/views.py from netbox.api.viewsets import NetBoxModelViewSet from my_plugin.models import MyModel from .serializers import MyModelSerializer class MyModelViewSet(NetBoxModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer ``` ``` -------------------------------- ### Configure SSO Authentication Backend (Google OAuth2 Example) Source: https://github.com/netbox-community/netbox/blob/main/docs/administration/authentication/overview.md Enable Single Sign-On (SSO) by specifying the path to a python-social-auth backend, such as 'social_core.backends.google.GoogleOAuth2'. Additional configuration may be required via SOCIAL_AUTH_ prefixed settings. ```python REMOTE_AUTH_BACKEND = 'social_core.backends.google.GoogleOAuth2' ``` -------------------------------- ### Model Serializer Example Source: https://github.com/netbox-community/netbox/blob/main/docs/plugins/development/rest-api.md Example of creating a custom serializer for a plugin model using NetBoxModelSerializer. ```APIDOC ## Model Serializer Example ### Description Example of creating a custom serializer for a plugin model using `NetBoxModelSerializer`. ### Code ```python # api/serializers.py from rest_framework import serializers from netbox.api.serializers import NetBoxModelSerializer from my_plugin.models import MyModel class MyModelSerializer(NetBoxModelSerializer): foo = SiteSerializer(nested=True, allow_null=True) class Meta: model = MyModel fields = ('id', 'foo', 'bar', 'baz') brief_fields = ('id', 'url', 'display', 'bar') ``` ``` -------------------------------- ### Install django-auth-ldap Package Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/6-ldap.md Installs the django-auth-ldap package within the NetBox virtual environment using pip. ```bash source /opt/netbox/venv/bin/activate pip3 install django-auth-ldap ``` -------------------------------- ### Install System Packages for LDAP Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/6-ldap.md Installs the required system packages for LDAP integration on Debian/Ubuntu systems. ```bash sudo apt install -y libldap2-dev libsasl2-dev libssl-dev ``` -------------------------------- ### Configure Default PostgreSQL Database Source: https://github.com/netbox-community/netbox/blob/main/docs/configuration/required-parameters.md This example shows the required parameters for the 'default' PostgreSQL database connection in NetBox. ```python DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'netbox', 'USER': 'netbox', 'PASSWORD': 'J5brHrAXFLQSif0K', 'HOST': 'localhost', 'PORT': '', 'CONN_MAX_AGE': 300, } } ``` -------------------------------- ### Install Redis Server Source: https://github.com/netbox-community/netbox/blob/main/docs/installation/2-redis.md Installs the Redis server package on Debian-based systems. Ensure your version is at least v6.0. ```bash sudo apt install -y redis-server ``` -------------------------------- ### Example API Request Source: https://github.com/netbox-community/netbox/blob/main/docs/integrations/rest-api.md An example of a REST API request to retrieve site data using a v2 token. ```APIDOC ## Example API Request Below is an example REST API request utilizing a v2 token. ```bash $ curl -H "Authorization: Bearer nbt_4F9DAouzURLb.zjebxBPzICiPbWz0Wtx0fTL7bCKXKGTYhNzkgC2S" \ -H "Accept: application/json; indent=4" \ https://netbox/api/dcim/sites/ { "count": 10, "next": null, "previous": null, "results": [...] } ``` ``` -------------------------------- ### GraphQL Response Example Source: https://github.com/netbox-community/netbox/blob/main/docs/integrations/graphql-api.md Example JSON response for a GraphQL query, showing nested data for circuits and their providers. ```json { "data": { "circuits": [ { "cid": "1002840283", "provider": { "name": "CenturyLink" } }, { "cid": "1002840457", "provider": { "name": "CenturyLink" } } ] } } ``` -------------------------------- ### List and Filter Interfaces Source: https://github.com/netbox-community/netbox/blob/main/docs/integrations/rest-api.md This example shows how to retrieve a list of interfaces, filtered by device ID and ordered by creation date. ```APIDOC ## GET /api/dcim/interfaces/ ### Description Retrieves a list of interfaces, with options for filtering and ordering. ### Method GET ### Endpoint /api/dcim/interfaces/ ### Parameters #### Query Parameters - **device_id** (integer) - Optional - Filters interfaces belonging to a specific device. - **ordering** (string) - Optional - Specifies the order of results. Use a hyphen prefix for reverse order (e.g., `-created`). ### Request Example ```bash GET /api/dcim/interfaces/?device_id=123 GET /api/dcim/interfaces/?device_id=123&ordering=-created ``` ### Response #### Success Response (200) - A list of interface objects, each containing details like ID, name, device, etc. #### Response Example (Response structure would be a JSON array of interface objects, similar to the detail view but for multiple interfaces.) ``` -------------------------------- ### Basic Context Data Example Source: https://github.com/netbox-community/netbox/blob/main/docs/features/context-data.md This JSON represents a simple configuration context, defining a list of syslog servers. This data can be applied to devices based on their assigned region or other criteria. ```json { "syslog-servers": [ "192.168.43.107", "192.168.48.112" ] } ``` -------------------------------- ### Jinja2 Configuration Template Example Source: https://github.com/netbox-community/netbox/blob/main/docs/features/configuration-rendering.md An example Jinja2 template for rendering a simple network switch configuration file. It extends a base template and includes logic for host name, domain, time zone, NTP servers, and interfaces. ```jinja2 {% extends 'base.j2' %} {% block content %} system { host-name {{ device.name }}; domain-name example.com; time-zone UTC; authentication-order [ password radius ]; ntp { {% for server in ntp_servers %} server {{ server }}; {% endfor %} } } {% for interface in device.interfaces.all() %} {% include 'common/interface.j2' %} {% endfor %} {% endblock %} ```