Install NetBox on CentOS / Red Hat Enterprise Linux 8 - CentLinux

Latest

Thursday, 18 November 2021

Install NetBox on CentOS / Red Hat Enterprise Linux 8

Install NetBox on CentOS / Red Hat Enterprise Linux 8

Netbox is an IP address management (IPAM) and data center infrastructure management (DCIM) tool to empower network automation. In this article, you will learn how to install NetBox on CentOS / RHEL 8 or similar Linux distros.

 

Table of Contents:

install-netbox-on-centos-rhel-8

What is NetBox? :

NetBox is an infrastructure resource modeling (IRM) application designed to empower network automation. Initially conceived by the network engineering team at DigitalOcean. NetBox was developed specifically to address the needs of network and infrastructure engineers. NetBox is made available as open source under the Apache 2 license. It encompasses the following aspects of network management:

  • IP address management (IPAM) - IP networks and addresses, VRFs, and VLANs
  • Equipment racks - Organized by group and site
  • Devices - Types of devices and where they are installed
  • Connections - Network, console, and power connections among devices
  • Virtualization - Virtual machines and clusters
  • Data circuits - Long-haul communications circuits and providers

NetBox is built on the Django Python framework and utilizes a PostgreSQL database. It runs as a WSGI service behind your choice of HTTP server.

Recommended Reading: Red Hat RHCSA 8 Cert Guide: EX200 (Certification Guide) 2nd Edition by Sander van Vugt

 

Environment Specification:

We are using a minimal RHEL 8 installation with following specifications.

  • CPU - 3.4 Ghz (2 cores)
  • Memory - 2 GB
  • Storage - 40 GB
  • Operating System - Red Hat Enterprise Linux 8.5
  • Hostname – netbox-01.centlinux.com
  • IP Address - 192.168.116.243 /24

 

Upgrade your Linux Operating System:

It is a best practice to update your existing software packages, before installing a new software on your Linux operating system.

Connect with netbox-01.centlinux.com as root user by using a ssh client.

Build cache for your enabled yum repositories.

# dnf makecache
Updating Subscription Management repositories.
Red Hat Enterprise Linux 8 for x86_64 - BaseOS  2.6 kB/s | 4.1 kB     00:01
Red Hat Enterprise Linux 8 for x86_64 - BaseOS  205 kB/s |  40 MB     03:21
Red Hat CodeReady Linux Builder for RHEL 8 x86_ 3.7 kB/s | 4.5 kB     00:01
Red Hat CodeReady Linux Builder for RHEL 8 x86_ 304 kB/s | 6.2 MB     00:20
Red Hat Enterprise Linux 8 for x86_64 - AppStre 2.7 kB/s | 4.5 kB     00:01
Red Hat Enterprise Linux 8 for x86_64 - AppStre 187 kB/s |  37 MB     03:23
Last metadata expiration check: 0:00:09 ago on Sat 13 Nov 2021 10:17:01 AM EST.
Metadata cache created.

Execute dnf command at Linux bash prompt to update existing software packages in your Linux operating system.

# dnf update -y

If the above command updates your Linux Kernel, then reboot your operating system before moving forward.

# reboot

Verify the Linux Kernel and operating system versions.

# uname -r
4.18.0-348.el8.x86_64

# cat /etc/os-release
NAME="Red Hat Enterprise Linux"
VERSION="8.5 (Ootpa)"
ID="rhel"
ID_LIKE="fedora"
VERSION_ID="8.5"
PLATFORM_ID="platform:el8"
PRETTY_NAME="Red Hat Enterprise Linux 8.5 (Ootpa)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:redhat:enterprise_linux:8::baseos"
HOME_URL="https://www.redhat.com/"
DOCUMENTATION_URL="https://access.redhat.com/documentation/red_hat_enterprise_linux/8/"
BUG_REPORT_URL="https://bugzilla.redhat.com/"

REDHAT_BUGZILLA_PRODUCT="Red Hat Enterprise Linux 8"
REDHAT_BUGZILLA_PRODUCT_VERSION=8.5
REDHAT_SUPPORT_PRODUCT="Red Hat Enterprise Linux"
REDHAT_SUPPORT_PRODUCT_VERSION="8.5"

 

Install PostgreSQL on Linux Server:

NetBox supports PostgreSQL 9.6 or higher. It currently does not support MySQL and other relational databases.

PostgreSQL 10 is available in standard yum repositories. Therefore, you can easily install it by using dnf command.

# dnf install -y postgresql-server

Initialized the PostgreSQL database server by executing following command at Linux bash prompt.

# postgresql-setup --initdb
 * Initializing database in '/var/lib/pgsql/data'
 * Initialized, logs are in /var/lib/pgsql/initdb_postgresql.log

PostgreSQL by default uses host-based authentication. But you need to enable credential-based authentication for NetBox software.

Edit pg_hba.conf file by using vim text editor.

# vi /var/lib/pgsql/data/pg_hba.conf

Locate following lines in this file.

host    all             all             127.0.0.1/32            ident
host    all             all             ::1/128                 ident

and change the ident with md5 to enable credential-based authentication.

host    all             all             127.0.0.1/32            md5
host    all             all             ::1/128                 md5

Enable and start PostgreSQL database service.

# systemctl enable --now postgresql.service
Created symlink /etc/systemd/system/multi-user.target.wants/postgresql.service → /usr/lib/systemd/system/postgresql.service.

Connect to psql prompt.

# sudo -u postgres psql
psql (10.17)
Type "help" for help.
postgres=#

Create a database and an user for NetBox application.

postgres=# CREATE DATABASE netbox;
CREATE DATABASE
postgres=# CREATE USER netbox WITH PASSWORD '123';
CREATE ROLE
postgres=# GRANT ALL PRIVILEGES ON DATABASE netbox TO netbox;
GRANT
postgres=# \q

Test the database connectivity by executing following command.

# sudo -u postgres psql --username netbox --password --host 127.0.0.1 netbox
Password for user netbox:
psql (10.17)
Type "help" for help.

netbox=> \q

PostgreSQL database server has been installed and configured successfully.

 

Install Redis on Linux Server:

Redis is an in-memory key-value store, and NetBox uses it for caching and queuing.

Redis software is available in standard yum repositories. Therefore, install it by executing following Linux command.

# dnf install -y redis

Enable and start Redis service as follows.

# systemctl enable --now redis.service
Created symlink /etc/systemd/system/multi-user.target.wants/redis.service → /usr/lib/systemd/system/redis.service.

Execute following command at Linux bash prompt to verify the status of Redis service.

# redis-cli ping
PONG

 

Install Python 3.7 on CentOS / RHEL 8:

NetBox required Python 3.7 or later.

The default yum repositories of CentOS / RHEL 8 do not provide Python 3.7. However, you can install it by downloading the zip archive from Python official website.

But, you should install the prerequisite software packages on your Linux server before installing Python 3.7.

# dnf install -y gcc make openssl-devel bzip2-devel libffi-devel wget git libxml2-devel libxslt-devel libpq-devel redhat-rpm-config

By using wget command download Python 3.7 to your Linux server.

# wget https://www.python.org/ftp/python/3.7.9/Python-3.7.9.tgz
--2021-11-14 12:18:33--  https://www.python.org/ftp/python/3.7.9/Python-3.7.9.tgz
Resolving www.python.org (www.python.org)... 199.232.44.223, 2a04:4e42:48::223
Connecting to www.python.org (www.python.org)|199.232.44.223|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 23277790 (22M) [application/octet-stream]
Saving to: ‘Python-3.7.9.tgz’

Python-3.7.9.tgz    100%[===================>]  22.20M  52.4KB/s    in 12m 37s

2021-11-14 12:31:24 (30.0 KB/s) - ‘Python-3.7.9.tgz’ saved [23277790/23277790]

Extract downloaded Tarball by using following Linux command.

# tar xzf Python-3.7.9.tgz

Configure and install Python 3.7 into your Linux server.

# cd Python-3.7.9
# ./configure --enable-optimizations
# make altinstall

Create a soft link for python3.7 executable as follows.

# ln -s /usr/local/bin/python3.7 /usr/local/bin/python3

Verify the installation by checking the version of Python.

# python3 -V
Python 3.7.9

Before moving forward, update pip (Python Package Management Tool) to the latest release.

# pip3.7 install --upgrade pip

Collecting pip
  Downloading pip-21.3.1-py3-none-any.whl (1.7 MB)
     |████████████████████████████████| 1.7 MB 99 kB/s
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 20.1.1
    Uninstalling pip-20.1.1:
      Successfully uninstalled pip-20.1.1
Successfully installed pip-21.3.1

Create the base directory for NetBox installation.

# mkdir -p /opt/netbox/

By using git command, clone the master branch of NetBox GitHub repository. This branch always holds the current stable release.

# cd /opt/netbox/
# git clone -b master --depth 1 https://github.com/netbox-community/netbox.git .
Cloning into '.'...
remote: Enumerating objects: 1044, done.
remote: Counting objects: 100% (1044/1044), done.
remote: Compressing objects: 100% (962/962), done.
remote: Total 1044 (delta 180), reused 386 (delta 58), pack-reused 0
Receiving objects: 100% (1044/1044), 4.28 MiB | 263.00 KiB/s, done.
Resolving deltas: 100% (180/180), done.

Create a system user to own NetBox software and processes. Later in this tutorial, you will configure the WSGI and HTTP services to run under this account.

You should also assign the ownership of media directory to this user. This ensures that NetBox will be able to save uploaded files therein.

# groupadd --system netbox
# adduser --system -g netbox netbox
# chown --recursive netbox /opt/netbox/netbox/media/

Create NetBox configuration file from template.

# cd /opt/netbox/netbox/netbox/
# cp configuration.example.py configuration.py

Edit Netbox configuration file by using vim text editor.

# vi configuration.py

Locate and set following four directives in this file.

ALLOWED_HOSTS = ['*']

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

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 second database
        'SSL': False,
    }
}

SECRET_KEY = '^Juy^bAT2bmFRYVnJHVg0&YkkFyM=-PODj*4zZM@th2@C)_$Jv'

You can execute following command at Linux Bash prompt to generate a SECRET_KEY for your NetBox server.

# python3.7 ../generate_secret_key.py
^Juy^bAT2bmFRYVnJHVg0&YkkFyM=-PODj*4zZM@th2@C)_$Jv

Once NetBox has been configured, you are ready to proceed with the actual installation.

Execute upgrade.sh script to install NetBox on Linux server.

# /opt/netbox/upgrade.sh
...
WARNING: No existing virtual environment was detected. A new one has
been created. Update your systemd service files to reflect the new
Python and gunicorn executables. (If this is a new installation,
this warning can be ignored.)

netbox.service ExecStart:
  /opt/netbox/venv/bin/gunicorn

netbox-rq.service ExecStart:
  /opt/netbox/venv/bin/python

After modifying these files, reload the systemctl daemon:
  > systemctl daemon-reload
--------------------------------------------------------------------
Upgrade complete! Don't forget to restart the NetBox services:
  > sudo systemctl restart netbox netbox-rq

Netbox does not have a predefined user account. Therefore, you have to create a superuser (administrative account) to be able to login to NetBox.

Create a Python virtual environment and then execute the following commands to create a superuser for NetBox software.

# source /opt/netbox/venv/bin/activate
(venv) # cd /opt/netbox/netbox
(venv) # python3 manage.py createsuperuser
Username (leave blank to use 'root'):
Email address: root@netbox-01.centlinux.com
Password:
Password (again):
Superuser created successfully.

NetBox provides a housekeeping script that clears out old sessions and expired change records. You can run this command manually, but it is recommended to configure it as a cron job.

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

Allow the required service port in Linux firewall. We are not making it permanent, because NetBox will be configured to access via HTTP web server.

# firewall-cmd --add-port=8000/tcp
success

Start the NetBox service by executing following command at Linux bash prompt.

# python3 manage.py runserver 0.0.0.0:8000 --insecure
Performing system checks...

System check identified no issues (0 silenced).
November 14, 2021 - 18:40:39
Django version 3.2.9, using settings 'netbox.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.

Open URL http://netbox-01.centlinux.com:8000 in a web browser.

01-install-netbox-dashboard-centos-rocky-rhel-linux-8

 

Create Systemd Service for NetBox :

NetBox runs as a WSGI application behind an HTTP server. For this purpose, you can use gunicorn (which is installed with NetBox).

NetBox shipped with a default configuration file for gunicorn. Copy it into NetBox base directory.

# cp /opt/netbox/contrib/gunicorn.py /opt/netbox/unicorn.py

NetBox also provides Systemd service units. Copy them into Systemd configuration directory.

# cp -v /opt/netbox/contrib/*.service /etc/systemd/system/
'/opt/netbox/contrib/netbox-rq.service' -> '/etc/systemd/system/netbox-rq.service'
'/opt/netbox/contrib/netbox.service' -> '/etc/systemd/system/netbox.service'

Enable and start NetBox services.

# systemctl enable --now netbox netbox-rq
Created symlink /etc/systemd/system/multi-user.target.wants/netbox.service → /etc/systemd/system/netbox.service.
Created symlink /etc/systemd/system/multi-user.target.wants/netbox-rq.service → /etc/systemd/system/netbox-rq.service.

We will configure NetBox on HTTPS protocol. Therefore, you may need a SSL certificate for NetBox application.

Create a self-signed SSL certificate or generate a CSR (Certificate Signing Request) and get it signed by the CA (You have to configure a Certificate Authority (CA) for your Network).

You can generate a self-signed SSL certificate by executing following Linux commands.

# mkdir /etc/ssl/private
# openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
> -keyout /etc/ssl/private/netbox.key \
> -out /etc/ssl/certs/netbox.crt
Generating a RSA private key
...........+++++
.......................................................................+++++
writing new private key to '/etc/ssl/private/netbox.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:PK
State or Province Name (full name) []:Sindh
Locality Name (eg, city) [Default City]:Karachi
Organization Name (eg, company) [Default Company Ltd]:CentLinux
Organizational Unit Name (eg, section) []:IT Lab
Common Name (eg, your name or your server's hostname) []:netbox-01.centlinux.com
Email Address []:root@netbox-01.centlinux.com

 

Install Nginx Web Server on CentOS / RHEL 8:

We are configuring NetBox as a WSGI service, therefore you need a web server to provide HTTP access to NetBox application.

You can either use Apache or Nginx for this purpose. But we are using Nginx in this tutorial.

Install Nginx web server by using dnf command.

# dnf install -y nginx

Edit Nginx configuration file by using vim text editor.

# vi /etc/nginx/nginx.conf

Disable default server block and add following lines therein.

server {
    listen [::]:443 ssl ipv6only=off;

    # CHANGE THIS TO YOUR SERVER'S NAME
    server_name netbox.example.com;

    ssl_certificate /etc/ssl/certs/netbox.crt;
    ssl_certificate_key /etc/ssl/private/netbox.key;

    client_max_body_size 25m;

    location /static/ {
        alias /opt/netbox/netbox/static/;
    }

    location / {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header X-Forwarded-Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

server {
    # Redirect HTTP traffic to HTTPS
    listen [::]:80 ipv6only=off;
    server_name _;
    return 301 https://$host$request_uri;
}

Enable and start Nginx service.

# systemctl enable --now nginx.service
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.

Allow HTTP & HTTPS services in Linux firewall.

# firewall-cmd --permanent --add-service=http,https
success
# firewall-cmd --reload
success

Adjust SELinux boolean, so your web server can communicate to NetBox service.

# setsebool -P httpd_can_network_connect 1

Open URL https://netbox-01.centlinux.com in a web browser.

01-install-netbox-dashboard-centos-rocky-rhel-linux-8

Your NetBox server has been configured successfully.

 

Conclusion:

In this article, you have learn how to install NetBox on CentOS / RHEL 8 or similar Linux distros.

No comments:

Post a Comment