NetBox
1.installing Netbox

NetBox Installation Guide for Ubuntu 23.10

This guide provides step-by-step instructions for installing NetBox, an open-source IP address management (IPAM) and data center infrastructure management (DCIM) tool.

Prerequisites

Before starting the installation process, ensure that you have the following prerequisites:

  • Python 3.8 or later
  • PostgreSQL 12 or later
  • Redis 4.0 or later

Installation Steps:

1. Postgress install:

sudo apt update
sudo apt install -y postgresql
  • PostgreSQL Installation Verification:
psql -V

Database Creation:

sudo -u postgres psql
CREATE DATABASE netbox;
CREATE USER netbox WITH PASSWORD 'YOUR_PASSWORD';
ALTER DATABASE netbox OWNER TO netbox;
  • The next two commands are necessary for PostgreSQL 15 and later:
\connect netbox;
GRANT CREATE ON SCHEMA public TO netbox;
Note:
Use a strong password
Do not use the password from the example. Choose a strong, random password to ensure secure database authentication for your NetBox installation.

Exit the PostgreSQL shell

\q

Verification of Service Status

  • Replace 'localhost' with your database server if using a remote database
psql -U netbox -h localhost -W
$ psql --username netbox --password --host localhost netbox
Password for user netbox: 
psql (12.5 (Ubuntu 12.5-0ubuntu0.20.04.1))
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
Type "help" for help.
  • If successful, you will enter a netbox prompt. Type \conninfo to confirm your connection, or type \q to exit.
netbox=> \conninfo
You are connected to database "netbox" as user "netbox" on host "localhost" (address "127.0.0.1") at port "5432".
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
netbox=> \q

2. Redis install:

Redis is an in-memory key-value store used by NetBox for caching and queuing. This section covers the installation and configuration of a local Redis instance. If you already have a Redis service, skip to the next section.

sudo apt install -y redis-server
  • Before proceeding, confirm that your installed version of Redis is at least v4.0:
redis-server -v
  • Use the redis-cli utility to ensure the Redis service is functional:
redis-cli ping
  • If successful, you should receive a PONG response from the server.

Installing and configuring NetBox:

  • This section of the documentation discusses installing and configuring the NetBox application itself.

  • Install System Packages:

  • We will begin by installing all system packages required by NetBox and its dependencies.

  • Python3.8 and above required:

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
Note: It is advisable to install NetBox in a directory named after its version number. For instance, if installing NetBox v3.0.0, it would be placed in /opt/netbox-3.0.0. Additionally, create a symlink from /opt/netbox/ to point to this specific version. You can verify this configuration using the command
  • We will install NetBox using the Gitub repository as this allows to easily upgrade by re-pulling the master branch.

  • We will create a base directory for the NetBox installation. We will be using /opt/netbox:

sudo mkdir -p /opt/netbox/
cd /opt/netbox/
  • Install Git:
sudo apt install -y git
  • next we will clone the master branch of the NetBox GitHub repository into the current directory. (This branch always holds the current stable release.)
sudo git clone -b master --depth 1 https://github.com/netbox-community/netbox.git .
  • Installation via git also allows you to easily try out different versions of NetBox. To check out a specific NetBox release (opens in a new tab), use the git checkout command with the desired release tag. For example, git checkout v3.0.8.
 

Creating a the Netbox System User

  • To set up NetBox, create a system user account named netbox. Configure the WSGI and HTTP services to operate under this account. Additionally, assign ownership of the media directory to this user to ensure NetBox can successfully save uploaded files.
sudo adduser --system --group netbox
sudo chown --recursive netbox /opt/netbox/netbox/media/
sudo chown --recursive netbox /opt/netbox/netbox/reports/
sudo chown --recursive netbox /opt/netbox/netbox/scripts/

Netbox Configuration

  • We will now Navigate to the NetBox configuration directory and duplicate the configuration_example.py file, naming the copy configuration.py. This file will store all your local configuration parameters.
cd /opt/netbox/netbox/netbox/
sudo cp configuration_example.py configuration.py

Configure NetBox in configuration.py

Open configuration.py using your preferred text editor to initiate the NetBox configuration. Among the numerous configuration parameters, the following four are essential for new installations:

ALLOWED_HOSTS

This is a list of valid hostnames and IP addresses for accessing the server. Specify at least one name or IP address for HTTP host header validation.

ALLOWED_HOSTS = ['netbox.example.com', '192.0.2.123']

If you are uncertain about the domain name or IP address for the NetBox installation, set the ALLOWED_HOSTS to a wildcard (asterisk) to allow all host values.

ALLOWED_HOSTS = ['*']

DATABASE

The DATABASE parameter holds the database configuration details. Define the username and password used during PostgreSQL configuration. If the service runs on a remote host, update the HOST and PORT parameters accordingly. Refer to the configuration documentation for more detail on individual parameters.

DATABASE = {
    'NAME': 'netbox',               # Database name
    'USER': 'netbox',               # PostgreSQL username
    'PASSWORD': 'J5brHrAXFLQSif0K', # PostgreSQL password
    'HOST': 'localhost',            # Database server
    'PORT': '',                     # Database port (leave blank for default)
    'CONN_MAX_AGE': 300,            # Max database connection age (seconds)
}

REDIS

Redis is an in-memory key-value store used by NetBox for caching and background task queuing. Minimal configuration is usually required; the values below should suffice for most installations. Refer to the configuration documentation for more detail on individual parameters.

Note: NetBox requires two separate Redis databases, tasks, and caching, each with a unique numeric database ID.

REDIS = {
    'tasks': {
        'HOST': 'localhost',      # Redis server
        'PORT': 6379,             # Redis port
        'PASSWORD': '',           # Redis password (optional)
        'DATABASE': 0,            # Database ID
        'SSL': False,             # Use SSL (optional)
    },
    'caching': {
        'HOST': 'localhost',
        'PORT': 6379,
        'PASSWORD': '',
        'DATABASE': 1,            # Unique ID for the second database
        'SSL': False,
    }
}

SECRET_KEY

This parameter must be assigned a randomly-generated key used as a salt for hashing and cryptographic functions. It is never directly used in the encryption of secret data. The key must be unique to the installation and is recommended to be at least 50 characters long.

Use the provided Python script, generate_secret_key.py, in the parent directory to generate a suitable key:

python3 ../generate_secret_key.py
SECRET_KEY values must match:

In the case of a highly available installation with multiple web servers, SECRET_KEY must be identical among all servers in order t maintain a persistent user session state.

  • Make sure to add the security key value that was generated by the script in the secret_KEY
  • Now we will save the file.

Optional Requirements

All Python packages needed by NetBox are listed in requirements.txt and are automatically installed. NetBox also supports optional packages, which must be specified in local_requirements.txt within the NetBox root directory.

Remote File Storage

By default, NetBox utilizes the local filesystem for storing uploaded files. To use a remote filesystem, install the django-storages library and configure the desired storage backend in configuration.py.

sudo sh -c "echo 'django-storages' >> /opt/netbox/local_requirements.txt"

Remote Data Sources

NetBox supports integration with various remote data sources via configurable backends. Each integration requires installing one or more additional libraries.

  • Amazon S3: boto3

  • Git: dulwich

  • For example, to enable the Amazon S3 backend, add boto3 to your local requirements file:

sudo sh -c "echo 'boto3' >> /opt/netbox/local_requirements.txt"
Info:

These packages were mandatory in NetBox v3.5 but are now optional.

Sentry Integration

NetBox can be configured to send error reports to Sentry for analysis. This integration requires installing the sentry-sdk Python library.

sudo sh -c "echo 'sentry-sdk' >> /opt/netbox/local_requirements.txt"
Info:

Sentry integration was previously included by default in NetBox v3.6 but is now optional.

Run the Upgrade Script

Once NetBox is configured, proceed with the installation by running the packaged upgrade script (upgrade.sh). This script performs the following actions:

  • Creates a Python virtual environment Installs all required Python packages
  • Runs database schema migrations
  • Builds local documentation (for offline use)
  • Aggregates static resource files on disk
Warning: If a Python virtual environment is active from a previous installation step, deactivate it now with the deactivate command to avoid errors on systems where sudo preserves the user's environment.
sudo /opt/netbox/upgrade.sh
Note:

Python 3.8 or later is required for NetBox v3.2 and later releases. If the default Python installation is an older version, specify the path to a supported installation using the PYTHON environment variable after the sudo command.

sudo PYTHON=/usr/bin/python3.8 /opt/netbox/upgrade.sh
Note: The script may warn about no existing virtual environment, which is normal for a new installation.

Create a Super User

NetBox doesn't come with predefined user accounts. Create a superuser (administrative account) to log into NetBox. Activate the Python virtual environment created by the upgrade script:

source /opt/netbox/venv/bin/activate
  • Then, create a superuser account using the createsuperuser Django management command:
cd /opt/netbox/netbox
python3 manage.py createsuperuser

Schedule the Housekeeping Task

NetBox includes a housekeeping management command for recurring cleanup tasks. Configure a scheduled job using the system's cron daemon or a similar utility. Use the included shell script, netbox-housekeeping.sh, in the contrib directory and link it to the daily cron task directory:

sudo ln -s /opt/netbox/contrib/netbox-housekeeping.sh /etc/cron.daily/netbox-housekeeping

Test the Application

  • Run NetBox's development server locally for testing. Ensure the Python virtual environment is active before running the server:
python3 manage.py runserver 0.0.0.0:8000 --insecure
Note:

The development server is not suitable for production use. If issues arise during testing, troubleshoot before proceeding with the installation.

Warning:

If the test service fails or you can't reach the NetBox home page, correct the installation before continuing. Use Ctrl+c to stop the development server.

Note:

By default RHEL based distros will likely block your testing attempts with firewalld. The development server port can be opened with firewall-cmd (add --permanent if you want the rule to survive server restarts):

firewall-cmd --zone=public --add-port=8000/tcp

Gunicorn

  • Similar to many Django applications, NetBox operates as a WSGI application situated behind an HTTP server. This guide demonstrates the installation and configuration of gunicorn (automatically included with NetBox) for this purpose, although other WSGI servers are also viable options and should function similarly effectively. uWSGI stands out as a well-received alternative in this context.

Configuration

NetBox comes equipped with a default gunicorn configuration file. To employ it, duplicate the file located at /opt/netbox/contrib/gunicorn.py to /opt/netbox/gunicorn.py. This copying approach is chosen to safeguard against potential loss of local modifications due to future upgrades, as we create a separate copy rather than directly referencing the original file.

sudo cp /opt/netbox/contrib/gunicorn.py /opt/netbox/gunicorn.py
  • Although the supplied configuration is generally suitable for most initial installations, you might want to customize this file to alter the bound IP address and/or port number, or to implement performance-related adjustments. Refer to the Gunicorn documentation (opens in a new tab) for a comprehensive list of available configuration parameters.

systemd Setup

  • To manage both gunicorn and NetBox's background worker process, we'll utilize systemd. Begin by duplicating the files contrib/netbox.service and contrib/netbox-rq.service to the /etc/systemd/system/ directory, and then reload the systemd daemon.

Check user & group assignment The stock service configuration files packaged with NetBox assume that the service will run with the netbox user and group names. If these differ on your installation, be sure to update the service files accordingly.

sudo cp -v /opt/netbox/contrib/*.service /etc/systemd/system/
sudo systemctl daemon-reload
  • Then, start the netbox and netbox-rq services and enable them to initiate at boot time:
sudo systemctl start netbox netbox-rq
sudo systemctl enable netbox netbox-rq
  • We should see the following output:
 netbox.service - NetBox WSGI Service
     Loaded: loaded (/etc/systemd/system/netbox.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2021-08-30 04:02:36 UTC; 14h ago
       Docs: https://docs.netbox.dev/
   Main PID: 1140492 (gunicorn)
      Tasks: 19 (limit: 4683)
     Memory: 666.2M
     CGroup: /system.slice/netbox.service
             ├─1140492 /opt/netbox/venv/bin/python3 /opt/netbox/venv/bin/gunicorn --pid /va>
             ├─1140513 /opt/netbox/venv/bin/python3 /opt/netbox/venv/bin/gunicorn --pid /va>
             ├─1140514 /opt/netbox/venv/bin/python3 /opt/netbox/venv/bin/gunicorn --pid /va>
...
Note:

If the NetBox service fails to start, issue the command journalctl -eu netbox to check for log messages that may indicate the problem.

  • After confirming that the WSGI workers are operational, proceed to configure the HTTP server.

HTTP Server Setup

Configuration

NetBox ships with a default configuration file for gunicorn. To use it, copy /opt/netbox/contrib/gunicorn.py to /opt/netbox/gunicorn.py. (We make a copy of this file rather than pointing to it directly to ensure that any local changes to it do not get overwritten by a future upgrade.)

Customization

While the provided configuration should suffice for most initial installations, you may wish to edit this file to change the bound IP address and/or port number, or to make performance-related adjustments. See the Gunicorn documentation for the available configuration parameters.

systemd Setup

We'll use systemd to control both gunicorn and NetBox's background worker process. First, copy contrib/netbox.service and contrib/netbox-rq.service to the /etc/systemd/system/ directory and reload the systemd daemon.

WSGI Workers

Once you've verified that the WSGI workers are up and running, move on to HTTP server setup.

HTTP Server Configuration

This documentation provides example configurations for both nginx and Apache, though any HTTP server which supports WSGI should be compatible.

Info:

For the sake of brevity, only Ubuntu 20.04 instructions are provided here. These tasks are not unique to NetBox and should carry over to other distributions with minimal changes. Please consult your distribution's documentation for assistance if needed.

Obtain an SSL Certificate

To enable HTTPS access to NetBox, you'll need a valid SSL certificate. You can purchase one from a trusted commercial provider, obtain one for free from Let's Encrypt, or generate your own (although self-signed certificates are generally untrusted). Both the public certificate and private key files need to be installed on your NetBox server in a location that is readable by the netbox user.

The command below can be used to generate a self-signed certificate for testing purposes, however it is strongly recommended to use a certificate from a trusted authority in production. Two files will be created: the public certificate (netbox.crt) and the private key (netbox.key). The certificate is published to the world, whereas the private key must be kept secret at all times.

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /etc/ssl/private/netbox.key \
-out /etc/ssl/certs/netbox.crt
  • The above command will prompt you for additional details of the certificate; all of these are optional.

HTTP Server Installation (nginx)

  • We will first install nginx:
sudo apt install -y nginx

Nginx Configuration

  • Once nginx is installed, copy the nginx configuration file provided by NetBox to /etc/nginx/sites-available/netbox. Ensure to replace netbox.example.com with the domain name or IP address of your installation. (This should match the value configured for ALLOWED_HOSTS in configuration.py.)
sudo cp /opt/netbox/contrib/nginx.conf /etc/nginx/sites-available/netbox
  • delete the default configuration in /etc/nginx/sites-enabled/ and create a symlink in the sites-enabled directory to the configuration file you just created.
sudo rm /etc/nginx/sites-enabled/default
sudo ln -s /etc/nginx/sites-available/netbox /etc/nginx/sites-enabled/netbox
  • Now we can restart the nginx server
sudo systemctl restart nginx

Confirm Connectivity

At this point, you should be able to connect to the HTTPS service at the server name or IP address you provided.

Info

Please keep in mind that the configurations provided here are bare minimums required to get NetBox up and running. You may want to make adjustments to better suit your production environment.

Warning

Certain components of NetBox (such as the display of rack elevation diagrams) rely on the use of embedded objects. Ensure that your HTTP server configuration does not override the X-Frame-Options response header set by NetBox.

Troubleshooting

If you are unable to connect to the HTTP server, check that:

  • Nginx/Apache is running and configured to listen on the correct port.
  • Access is not being blocked by a firewall somewhere along the path. (Try connecting locally from the server itself.)

If you are able to connect but receive a 502 (bad gateway) error, check the following:

  • The WSGI worker processes (gunicorn) are running (systemctl status netbox should show a status of "active (running)")
  • Nginx/Apache is configured to connect to the port on which gunicorn is listening (default is 8001).
  • SELinux is not preventing the reverse proxy connection. You may need to allow HTTP network connections with the command setsebool -P httpd_can_network_connect 1.

LDAP Configuration

  • This guide explains how to implement LDAP authentication using an external server. User authentication will fall back to built-in Django users in the event of a failure.

Install Requirements

Install System Packages

Ubuntu:

sudo apt install -y libldap2-dev libsasl2-dev libssl-dev

CentOS:

sudo yum install -y openldap-devel python3-devel

Install django-auth-ldap

Activate the Python virtual environment and install the django-auth-ldap package using pip:

source /opt/netbox/venv/bin/activate
pip3 install django-auth-ldap
  • Once installed, add the package to local_requirements.txt to ensure it is re-installed during future rebuilds of the virtual environment:
sudo sh -c "echo 'django-auth-ldap' >> /opt/netbox/local_requirements.txt"
  • Next, we will generate a file in the directory where configuration.py resides (usually /opt/netbox/netbox/netbox/) and name it ldap_config.py. Specify all the necessary parameters outlined below within the ldap_config.py file. Comprehensive documentation for all django-auth-ldap configuration options is provided in the project's official documentation (opens in a new tab).

General Server Configuration

info:

  • When using Active Directory you may need to specify a port on AUTH_LDAP_SERVER_URI to authenticate users from all domains in the forest. Use 3269 for secure, or 3268 for non-secure access to the GC (Global Catalog).
import ldap
 
# Server URI
AUTH_LDAP_SERVER_URI = "ldaps://ad.example.com"
 
# 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 = True
 
# 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'
  • STARTTLS can be configured by setting AUTH_LDAP_START_TLS = True and using the ldap:// URI scheme.

User Authentication

Note:

  • When using Windows Server 2012+, AUTH_LDAP_USER_DN_TEMPLATE should be set to None.
from django_auth_ldap.config import LDAPSearch
 
# 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,
                                    "(sAMAccountName=%(user)s)")
 
# If a user's DN is producible from their username, we don't need to search.
AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,ou=users,dc=example,dc=com"
 
# You can map user attributes to Django attributes as so.
AUTH_LDAP_USER_ATTR_MAP = {
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail"
}

User Groups for Permissions

info:

from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
 
# 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 = GroupOfNamesType()
 
# 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_staff": "cn=staff,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
 
# Cache groups for one hour to reduce LDAP traffic
AUTH_LDAP_CACHE_TIMEOUT = 3600

is_active: All users must be associated with at least this group to activate authentication. Without this association, users won't be able to log in.

is_staff: Users linked to this group gain access to administrative tools; this is akin to marking the "staff status" checkbox for a manually created user. However, it doesn't confer any specific permissions.

is_superuser: Users assigned to this group attain superuser status, entitling them to all permissions by default.

Note: Authentication will fail if the groups (the distinguished names) do not exist in the LDAP directory.

Authenticating with Active Directory

  • Authenticating with Active Directory can pose challenges due to various login formats. Integrating it for authentication is facilitated by accommodating different login scenarios. This solution enables users to log in using either their full User Principal Name (UPN) or their username alone. The DN is filtered based on either the sAMAccountName or the userPrincipalName. The subsequent configuration options permit users to enter their usernames in the format username or username@domain.tld.

  • As previously mentioned, these configuration options are specified in the ldap_config.py file. Initially, adjust the AUTH_LDAP_USER_SEARCH option to align with the following:

AUTH_LDAP_USER_SEARCH = LDAPSearch(
    "ou=Users,dc=example,dc=com",
    ldap.SCOPE_SUBTREE,
    "(|(userPrincipalName=%(user)s)(sAMAccountName=%(user)s))"
)
  • Furthermore, set AUTH_LDAP_USER_DN_TEMPLATE to None, as detailed in the preceding sections. Subsequently, update AUTH_LDAP_USER_ATTR_MAP to align with the following:
AUTH_LDAP_USER_ATTR_MAP = {
    "username": "sAMAccountName",
    "email": "mail",
    "first_name": "givenName",
    "last_name": "sn",
}
  • Lastly, an additional configuration option, AUTH_LDAP_USER_QUERY_FIELD, needs to be included in your LDAP configuration file. Incorporate the following into your LDAP configuration:
AUTH_LDAP_USER_QUERY_FIELD = "username"
  • With these configuration options, your users will be able to log in either with or without the UPN suffix.

Example configuration

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_staff": "cn=staff,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
 
# Cache groups for one hour to reduce LDAP traffic
AUTH_LDAP_CACHE_TIMEOUT = 3600
AUTH_LDAP_ALWAYS_UPDATE_USER = True

Info: This configuration is offered as a template and may require modifications to align with your specific environment.

#### Troubleshooting LDAP
 
- To restart the NetBox service and apply changes made to ldap_config.py, use the following command:
 
```bash
sudo systemctl restart netbox

If there are syntax errors, the NetBox process won't start, and errors will be logged to /var/log/messages.

For troubleshooting LDAP user/group queries, add or merge the following logging configuration to configuration.py:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'netbox_auth_log': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': '/opt/netbox/local/logs/django-ldap-debug.log',
            'maxBytes': 1024 * 500,
            'backupCount': 5,
        },
    },
    'loggers': {
        'django_auth_ldap': {
            'handlers': ['netbox_auth_log'],
            'level': 'DEBUG',
        },
    },
}

Ensure that the specified file and path in the filename attribute exist, and the file is writable and executable by the application service account. Restart the netbox service and attempt to log into the site to trigger log entries to this file.