This repository contains a script to back up the Netbox PostgreSQL database and media files. The script performs the following tasks:
- Backs up the Netbox PostgreSQL database.
- Archives the Netbox media files.
- Deletes backups older than 7 days, except for the first of the month backups.
- Ensure you have
pg_dumpinstalled. - Ensure you have the necessary permissions to create directories and files in
/opt/backups/netbox. - Ensure the
PGPASSWORDenvironment variable is set with the PostgreSQL password. - (optional) Install cron to automate the backup process.
-
Clone the Repository
Clone this repository to your local machine:
git clone git@github.com:lancamat1/netbox-backup-script.git cd netbox-backup-script -
Make the Script Executable
Run the following command to make the script executable:
chmod +x backup_script.sh
-
Run the Backup Script
Set the
PGPASSWORDenvironment variable and run the script:PGPASSWORD=your_postgres_password ./backup_script.sh
-
Verify the Backups
Check the
/opt/backups/netboxdirectory to ensure the backups are created.
To automate the backup process, you can add a cron job. For example, to run the backup script every day at 2 AM:
-
Open the crontab editor:
crontab -e
-
Add the following line to schedule the backup:
0 2 * * * PGPASSWORD=your_postgres_password /path/to/your/repository/backup_script.sh
Replace
your_postgres_passwordwith the actual PostgreSQL password and/path/to/your/repositorywith the path to the cloned repository.
-
Stop the Netbox service:
sudo systemctl stop netbox
-
Drop the existing Netbox database:
sudo -u postgres psql -c "DROP DATABASE IF EXISTS netbox;" -
Create a new Netbox database:
sudo -u postgres psql -c "CREATE DATABASE netbox WITH OWNER netbox;" -
Restore the database from the backup:
gunzip -c /opt/backups/netbox/netbox_2024-08-14.psql.gz | sudo -u postgres psql netbox -
Start the Netbox service:
sudo systemctl start netbox