Last active
June 23, 2024 16:35
-
-
Save schnapster/7ef936e45fb934030566227521e78a15 to your computer and use it in GitHub Desktop.
Backup Grafana sqlite db to Backblaze
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# Prerequisites: | |
# sudo apt install pipx curl jq tar sqlite3 | |
# sudo pipx install b2 | |
# | |
# pass 4 args: | |
# - instance (meta information), example: <machine name> | |
# - b2 bucket name (target of the upload), example: grafana-backups | |
# - path to backblaze credentials file that sets B2_ACCOUNT_ID and B2_APP_KEY | |
# | |
# Full example: ./grafana_b2_backup.sh "$(hostname)" grafana-backups .b2_creds | |
set -e | |
echo $(date) | |
# Verify we are root | |
if [ "$EUID" -ne 0 ]; then | |
echo "Please run as root" | |
exit 1 | |
fi | |
# Read arguments | |
INSTANCE=$1 | |
BUCKET=$2 | |
source $3 | |
echo "Backing up grafana ${INSTANCE} to bucket ${BUCKET}" | |
DB_FILE="/var/lib/grafana/grafana.db" | |
if [ ! -f "${DB_FILE}" ]; then | |
echo "Database ${DB_FILE} does not exist!" | |
exit 1 | |
fi | |
TMP_DIR="/tmp" | |
FILE_NAME="grafana_${INSTANCE}_$(date +%Y-%m-%d).db.bak" | |
TMP_FILE=${TMP_DIR}/${FILE_NAME} | |
B2_INFO="--info app=grafana --info instance=${INSTANCE}" | |
mkdir -p ${TMP_DIR} | |
# cleanup any old backups | |
if [ -f "${TMP_FILE}" ]; then | |
rm -f "${TMP_FILE}" | |
fi | |
# get it | |
sqlite3 ${DB_FILE} ".backup '${TMP_FILE}'" | |
# Calculate sha1 sum | |
SHA1=$(sha1sum ${TMP_FILE} | sed -En "s/^([0-9a-f]{40}).*/\1/p") | |
echo "sha1sum is ${SHA1}" | |
# log in to backblaze | |
b2 account authorize ${B2_ACCOUNT_ID} ${B2_APP_KEY} | |
echo "Logged into b2" | |
# Upload to backblaze | |
b2 file upload --sha1 ${SHA1} \ | |
${B2_INFO} \ | |
--quiet \ | |
${BUCKET} \ | |
${TMP_FILE} \ | |
${FILE_NAME} | |
echo "Uploaded to b2" | |
#log out of backblaze | |
b2 account clear | |
echo "Logged out of b2" | |
# Clean up tar file | |
if [ -f "${TMP_FILE}" ]; then | |
rm -f "${TMP_FILE}" | |
fi | |
echo "Cleaned up and done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment