Compare commits

...

5 Commits
2.0.1 ... main

5 changed files with 364 additions and 18 deletions

View File

@ -1,3 +1,80 @@
# Home-Assistant-Backup-Script
# Home Assistant Backup Automation Scripts
These scripts automate the backup process for **Home Assistant** servers, enabling you to create, transfer, and manage backups. The backups are securely transferred from the Home Assistant server to your local machine, with options for cleaning up old backups based on configurable retention periods.
## Overview
### Features:
- **Backup Creation**: Automates the process of creating backups on your Home Assistant server.
- **Backup Transfer**: Transfers the generated backups to a local machine for safekeeping.
- **Old Backup Cleanup**: Automatically cleans up old backups on both the Home Assistant server and local machine after a specified retention period.
- **Notification Support** (Optional): Configure **ntfy** or **Discord** notifications to alert you about the backup status (available in the first script version).
### Two Versions of the Script:
1. **Version 1: Simple Backup with Cleanup**
A simpler version that creates a backup, copies it to your local machine, and performs a basic cleanup of old backups locally. No notification system is included in this version.
2. **Version 2: Full Backup and Cleanup with Notifications**
This version includes backup creation, local and remote cleanup of old backups, and optional notifications via **ntfy** and **Discord**. It also checks for available disk space before cleaning up old backups.
## Requirements
Both scripts require the following to function correctly:
- **Bash shell** (on your local machine and Home Assistant server)
- **SSH** access to the Home Assistant server
- **`scp`** and **`ssh`** tools
- **Home Assistant** installed on the server with the `ha` CLI tool
- **Optional**: Access to a notification service (for Version 2)
## Configuration
Before running either script, you need to set up a few configuration parameters. These include SSH credentials, backup destination paths, and notification settings.
- **HA_SSH_KEY**: Path to your private SSH key for accessing the Home Assistant server.
- **HA_SSH_USER**: The SSH username (default is `root`).
- **HA_SSH_HOST**: The IP address or hostname of your Home Assistant server.
- **BACKUP_DEST**: Path to the directory where backups will be saved locally.
- **Retention Settings**: You can configure how long old backups are kept before they are deleted (default is 30 days for local and remote backups).
- **Optional**: Set up **ntfy** or **Discord** notifications to receive alerts when backups are created or when errors occur.
## How to Use
### Step 1: Configure the Script
Open the script file in a text editor and set the following variables:
- **SSH credentials** (`HA_SSH_KEY`, `HA_SSH_USER`, `HA_SSH_HOST`)
- **Backup destination path** (`BACKUP_DEST`)
- **Notification settings** (optional)
### Step 2: Make the Script Executable
After configuring the script, make it executable by running:
```
chmod +x home_assistant_backup.sh
```
## Disclaimer
**The software is provided "as-is" without any warranties or guarantees of any kind.**
By using this script, you acknowledge and agree that:
- **No Warranty**: The script is provided without any warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability, fitness for a particular purpose, or non-infringement. The entire risk arising out of the use or performance of the script remains with you.
- **Data Loss**: The author cannot be held responsible for any data loss, damage to your system, or any other kind of loss resulting from the use of this script. You are solely responsible for backing up your data and ensuring the integrity of your systems before using the script.
- **Use at Your Own Risk**: You are using this script at your own risk. The author shall not be liable for any damages, including but not limited to direct, indirect, incidental, special, consequential, or punitive damages, arising out of the use of or inability to use the script.
- **No Support**: The script is provided "as-is" with no formal support or maintenance. The author does not provide any guarantees of continued functionality, updates, or support.
- **Modifications and Redistribution**: If you modify or redistribute the script, you do so at your own risk. You are solely responsible for ensuring that any modifications or redistributed versions do not cause harm or violate any laws.
By using or modifying this script, you agree to indemnify and hold harmless the author from any and all claims, damages, liabilities, and expenses arising from your use or modification of the script.
---
Use of this script is subject to the terms above. If you do not agree with this disclaimer, you should not use the script.
A script that when ran, creates a backup of Home Assistant using the "ha backup new" command over SSH, then pulls the .tar file from the HA system on to the system that the script is running on

70
V1/README.md Normal file
View File

@ -0,0 +1,70 @@
# Home Assistant Backup Script
This script automates the process of creating and copying backups from a Home Assistant server to a local machine. It includes functionality for:
- Creating a new backup on the Home Assistant server.
- Copying the backup file to a specified local destination.
- Cleaning up old backups based on a specified retention period.
## Requirements
- Bash shell
- SSH access to your Home Assistant server
- `scp` and `ssh` tools
- Access to a Home Assistant server with the `ha` command line tool installed
## Configuration
Before using the script, you need to configure the following variables:
### Global Settings
- **HA_SSH_KEY**: Path to your SSH private key for accessing the Home Assistant server.
- **HA_SSH_USER**: The SSH username to use for connecting to the Home Assistant server (usually `root`).
- **HA_SSH_HOST**: The IP address or hostname of your Home Assistant server.
- **BACKUP_DEST**: The destination directory on your local machine where the backup file will be stored.
### Backup Retention
- The script will automatically clean up backup files on the local machine that are older than 30 days. You can adjust this retention period by modifying the `-mtime +30` argument in the `find` command to a different number of days.
## Script Flow
1. **Backup Creation**: The script connects to the Home Assistant server via SSH and creates a new backup using the `ha backup new` command. It generates a timestamped name for the backup.
2. **Backup Transfer**: The backup file is copied from the Home Assistant server to your local machine using `scp`.
3. **Local Backup Cleanup**: The script will automatically remove local backups that are older than the configured retention period (default is 30 days).
4. **Completion Message**: A success message is displayed after the backup process is complete.
## Usage
1. **Clone or Download the Script**:
- Clone the repository or download the script file.
2. **Make the Script Executable**:
```
chmod +x home_assistant_backup.sh
```
## Disclaimer
**The software is provided "as-is" without any warranties or guarantees of any kind.**
By using this script, you acknowledge and agree that:
- **No Warranty**: The script is provided without any warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability, fitness for a particular purpose, or non-infringement. The entire risk arising out of the use or performance of the script remains with you.
- **Data Loss**: The author cannot be held responsible for any data loss, damage to your system, or any other kind of loss resulting from the use of this script. You are solely responsible for backing up your data and ensuring the integrity of your systems before using the script.
- **Use at Your Own Risk**: You are using this script at your own risk. The author shall not be liable for any damages, including but not limited to direct, indirect, incidental, special, consequential, or punitive damages, arising out of the use of or inability to use the script.
- **No Support**: The script is provided "as-is" with no formal support or maintenance. The author does not provide any guarantees of continued functionality, updates, or support.
- **Modifications and Redistribution**: If you modify or redistribute the script, you do so at your own risk. You are solely responsible for ensuring that any modifications or redistributed versions do not cause harm or violate any laws.
By using or modifying this script, you agree to indemnify and hold harmless the author from any and all claims, damages, liabilities, and expenses arising from your use or modification of the script.
---
Use of this script is subject to the terms above. If you do not agree with this disclaimer, you should not use the script.

90
V2/README.md Normal file
View File

@ -0,0 +1,90 @@
# Home Assistant Backup Script
This script automates the process of creating, copying, and cleaning up backups for a Home Assistant server. It supports the ability to:
- Create a backup on the Home Assistant server.
- Copy the backup file to a local machine.
- Clean up old backups on both the local machine and Home Assistant server.
- Send notifications to `ntfy` and Discord.
## Requirements
- Bash shell
- SSH access to your Home Assistant server
- `scp` and `ssh`
- `yq` for parsing YAML (https://github.com/mikefarah/yq)
- `jq` for parsing JSON (https://github.com/jqlang/jq)
- `curl` for sending notifications
- Access to a Discord webhook URL (if using Discord notifications) (https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks)
- ntfy.sh server (if using ntfy.sh notifications) (https://ntfy.sh/)
## Configuration
Before using the script, you need to set up the following environment variables in the script:
### Global Settings
- **HA_SSH_KEY**: Path to your SSH private key for Home Assistant.
- **HA_SSH_USER**: Username for SSH login (usually `root`).
- **HA_SSH_HOST**: IP address or hostname of your Home Assistant server.
- **HA_SSH_PORT**: SSH port (default is 22).
- **BACKUP_DEST**: Destination directory for storing local backups.
- **BACKUP_FILE_LOCATION**: Location of the backups on the Home Assistant server (default is `/backup`).
- **LOCAL_BACKUP_CLEANUP**: Number of days to keep local backups (default is 90 days).
- **REMOTE_BACKUP_CLEANUP**: Number of days to keep backups on the Home Assistant server (default is 30 days).
- **NTFY_ENABLED**: Set to `true` to enable `ntfy` notifications.
- **NTFY_SERVER**: The FQDN of your `ntfy` server.
- **NTFY_TOPIC**: The topic for your `ntfy` notifications.
- **DISCORD_ENABLED**: Set to `true` to enable Discord notifications.
- **DISCORD_WEBHOOK_URL**: Your Discord webhook URL.
- **STORAGE_THRESHOLD_KB**: The disk space threshold in KB for triggering cleanup (default is 2GB).
### Notifications
- **ntfy**: Notifications are sent via HTTP POST to your `ntfy` server.
- **Discord**: Notifications are sent via a Discord webhook.
Set `NTFY_ENABLED` and `DISCORD_ENABLED` to `true` to enable notifications for respective services. Replace the relevant URLs and topics.
## Script Flow
1. **Backup Creation**: The script first creates a backup on the Home Assistant server.
2. **Disk Space Check**: It checks available disk space on the Home Assistant server. If it is less than the specified threshold, it will clean up old backups on the Home Assistant server.
3. **Backup Transfer**: The backup file is then copied from the Home Assistant server to the local backup destination.
4. **Local Cleanup**: Old backups are removed from the local machine if they exceed the specified retention period.
5. **Notification**: Notifications are sent at each major step (e.g., start of backup, successful backup, cleanup actions) via `ntfy` and Discord if enabled.
6. **Backup File Size and Script Runtime**: The script reports the backup file size and runtime after completing the backup process.
## Usage
1. **Clone or Download the Script**:
- Clone the repository or download the script file.
2. **Make the Script Executable**:
```bash
chmod +x home_assistant_backup.sh
## Disclaimer
**The software is provided "as-is" without any warranties or guarantees of any kind.**
By using this script, you acknowledge and agree that:
- **No Warranty**: The script is provided without any warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability, fitness for a particular purpose, or non-infringement. The entire risk arising out of the use or performance of the script remains with you.
- **Data Loss**: The author cannot be held responsible for any data loss, damage to your system, or any other kind of loss resulting from the use of this script. You are solely responsible for backing up your data and ensuring the integrity of your systems before using the script.
- **Use at Your Own Risk**: You are using this script at your own risk. The author shall not be liable for any damages, including but not limited to direct, indirect, incidental, special, consequential, or punitive damages, arising out of the use of or inability to use the script.
- **No Support**: The script is provided "as-is" with no formal support or maintenance. The author does not provide any guarantees of continued functionality, updates, or support.
- **Modifications and Redistribution**: If you modify or redistribute the script, you do so at your own risk. You are solely responsible for ensuring that any modifications or redistributed versions do not cause harm or violate any laws.
By using or modifying this script, you agree to indemnify and hold harmless the author from any and all claims, damages, liabilities, and expenses arising from your use or modification of the script.
---
Use of this script is subject to the terms above. If you do not agree with this disclaimer, you should not use the script.

View File

@ -1,5 +1,5 @@
#!/bin/bash
set -x
#set -x
### Global Settings ###
# Set your Home Assistant SSH credentials
@ -8,9 +8,22 @@ HA_SSH_USER="SSH_USER" # Replace with your HomeAssistant server username
HA_SSH_HOST="SSH_HOST_IP_OR_HOSTNAME" # Replace with your HomeAssistant server IP address
HA_SSH_PORT="SSH_PORT" # Replace with your HomeAssistant server port
## Storage
# Set the backup destination path
BACKUP_DEST="BACKUP_FILE_DESTINATION" # Replace with the location for the backup files
BACKUP_DEST="BACKUP_FILE_DESTINATION" # Replace with the location for the backup files
# Set the location of the Home Assistant backups (Set to default location /backup)
# If you have a custom install, using the likes of Supervised
# this location should normally be /usr/share/hassio/backup
BACKUP_FILE_LOCATION="/backup"
# Storage threshold (in KB) for triggering cleanup
STORAGE_THRESHOLD_KB=2097152 # 2GB = 2 * 1024 * 1024 KB
# Set clean up old backups (adjust the number of days to keep)
LOCAL_BACKUP_CLEANUP="90" # Set the number of days that local backup files will be kept for (Default 90 days)
REMOTE_BACKUP_CLEANUP="30" # Set the number of days that backups on the Home Assistant server will be kept for (Default 30 days)
## Notification Settings
# ntfy settings
NTFY_ENABLED=false # Set to 'true' to enable ntfy notifications
NTFY_SERVER="NTFY_SERVER_FQDN_ADDRESS" # Replace with your ntfy server address
@ -20,15 +33,101 @@ NTFY_TOPIC="NTFY_TOPIC" # Replace with your ntfy topic
DISCORD_ENABLED=false # Set to 'true' to enable Discord notifications
DISCORD_WEBHOOK_URL="DISCORD_WEBHOOK_URL" # Replace with your Discord webhook URL
# Set clean up old backups (adjust the number of days to keep)
BACKUP_FILE_CLEANUP="90" # Set the number of days that backup files will be kept for (Default 90 days)
# Set the location of the Home Assistant backups (Set to default location /backup)
# If you have a custom install, using the likes of Supervised
# this location should normally be /usr/share/hassio/backup
BACKUP_FILE_LOCATION="/backup"
### Script ###
## Sanity Check##
# Function to check if the necessary variables are set and if jq and yq are installed
sanity_check() {
# Check if jq and yq are installed
if ! command -v jq &> /dev/null; then
echo "Error: jq is not installed. Please install jq before running this script."
exit 1
fi
if ! command -v yq &> /dev/null; then
echo "Error: yq is not installed. Please install yq before running this script."
exit 1
fi
# Check for each variable
if [ -z "$HA_SSH_KEY" ] || [ "$HA_SSH_KEY" == "SSH_PRIVATE_KEY" ]; then
echo "Error: SSH_PRIVATE_KEY is not set."
exit 1
fi
if [ -z "$HA_SSH_USER" ] || [ "$HA_SSH_USER" == "SSH_USER" ]; then
echo "Error: SSH_USER is not set."
exit 1
fi
if [ -z "$HA_SSH_HOST" ] || [ "$HA_SSH_HOST" == "SSH_HOST_IP_OR_HOSTNAME" ]; then
echo "Error: SSH_HOST_IP_OR_HOSTNAME is not set."
exit 1
fi
if [ -z "$HA_SSH_PORT" ] || [ "$HA_SSH_PORT" == "SSH_PORT" ]; then
echo "Error: SSH_PORT is not set."
exit 1
fi
if [ -z "$BACKUP_DEST" ] || [ "$BACKUP_DEST" == "BACKUP_FILE_DESTINATION" ]; then
echo "Error: BACKUP_FILE_DESTINATION is not set."
exit 1
fi
if [ "$NTFY_ENABLED" == "true" ]; then
if [ -z "$NTFY_SERVER" ] || [ "$NTFY_SERVER" == "NTFY_SERVER_FQDN_ADDRESS" ]; then
echo "Error: NTFY_SERVER_FQDN_ADDRESS is not set."
exit 1
fi
if [ -z "$NTFY_TOPIC" ] || [ "$NTFY_TOPIC" == "NTFY_TOPIC" ]; then
echo "Error: NTFY_TOPIC is not set."
exit 1
fi
fi
if [ "$DISCORD_ENABLED" == "true" ]; then
if [ -z "$DISCORD_WEBHOOK_URL" ] || [ "$DISCORD_WEBHOOK_URL" == "DISCORD_WEBHOOK_URL" ]; then
echo "Error: DISCORD_WEBHOOK_URL is not set."
exit 1
fi
fi
}
# Call the function to check requirements and variables
sanity_check
# Function to remove old backups from Home Assistant server (older than $REMOTE_BACKUP_CLEANUP days)
remove_old_backups_ssh() {
echo "Removing backups older than $REMOTE_BACKUP_CLEANUP days on Home Assistant server..."
# Fetch the list of backups and parse the YAML output using yq
BACKUPS_OUTPUT=$(ssh -i "$HA_SSH_KEY" -p "$HA_SSH_PORT" "$HA_SSH_USER@$HA_SSH_HOST" "ha backups")
if ! echo "$BACKUPS_OUTPUT" | yq eval >/dev/null 2>&1; then
echo "Error: The output of 'ha backups' is not valid YAML."
return 1
fi
# Convert the YAML to JSON and extract old backups using jq
OLD_BACKUPS=$(echo "$BACKUPS_OUTPUT" | yq eval -o=json | jq --argjson days "$REMOTE_BACKUP_CLEANUP" -r '.backups[] | select((.date | sub("\\.[0-9]+\\+00:00$"; "Z") | fromdateiso8601) < (now - ($days * 86400))) | .slug')
# Remove each old backup by its slug
if [ -n "$OLD_BACKUPS" ]; then
for slug in $OLD_BACKUPS; do
echo "Removing backup with slug: $slug"
ssh -i "$HA_SSH_KEY" -p "$HA_SSH_PORT" "$HA_SSH_USER@$HA_SSH_HOST" "ha backups remove $slug"
if [ $? -eq 0 ]; then
echo "Successfully removed backup with slug: $slug"
send_ntfy_notification "Old backup removed: $slug"
send_discord_notification "Old backup removed: $slug"
else
echo "Failed to remove backup with slug: $slug"
fi
done
else
echo "No old backups found to remove."
fi
}
### Function for sending notifications ###
send_ntfy_notification() {
@ -58,6 +157,16 @@ START_TIME=$(date +%s)
send_ntfy_notification "Backup process started at $TIMESTAMP"
send_discord_notification "Backup process started at $TIMESTAMP"
# Check available disk space on Home Assistant server
AVAILABLE_SPACE=$(ssh -i "$HA_SSH_KEY" -p "$HA_SSH_PORT" "$HA_SSH_USER@$HA_SSH_HOST" "df --output=avail / | tail -n 1")
if [ "$AVAILABLE_SPACE" -lt "$STORAGE_THRESHOLD_KB" ]; then
echo "Disk space is less than 2GB on Home Assistant server. Proceeding with remote backup cleanup..."
# Remove old backups on Home Assistant server if less than 2GB available
remove_old_backups_ssh
else
echo "Sufficient disk space available on Home Assistant server. Skipping remote backup cleanup."
fi
# Create a backup on the Home Assistant server and extract the slug
BACKUP_OUTPUT=$(ssh -i "$HA_SSH_KEY" -p "$HA_SSH_PORT" "$HA_SSH_USER@$HA_SSH_HOST" "ha backup new --name=auto_backup_$TIMESTAMP")
if [ $? -ne 0 ]; then
@ -104,14 +213,13 @@ if [ $? -ne 0 ]; then
exit 1
fi
# Clean up old backups if needed (adjust the number of days to keep)
find "$BACKUP_DEST" -name '*.tar' -mtime +90 -exec rm {} \;
# Clean up old backups locally (older than $LOCAL_BACKUP_CLEANUP days)
find "$BACKUP_DEST" -name '*.tar' -mtime +$LOCAL_BACKUP_CLEANUP -exec rm {} \;
if [ $? -ne 0 ]; then
# Send notification if cleanup fails
send_ntfy_notification "Error: Failed to clean up old backups."
send_discord_notification "Error: Failed to clean up old backups."
echo "Error: Failed to clean up old backups."
send_ntfy_notification "Error: Failed to clean up old backups locally."
send_discord_notification "Error: Failed to clean up old backups locally."
echo "Error: Failed to clean up old backups locally."
exit 1
fi
@ -131,3 +239,4 @@ RUNTIME=$((END_TIME - START_TIME))
# Send notification with backup file size and script runtime
send_ntfy_notification "Backup file size: $BACKUP_FILE_SIZE bytes. Script runtime: $RUNTIME seconds."
send_discord_notification "Backup file size: $BACKUP_FILE_SIZE bytes. Script runtime: $RUNTIME seconds."