Steps to Automatically Delete Old Backups in Home Assistant
Follow these steps to set up a system that automatically deletes backups older than 7 days.
Step 1: Generate SSH Keys
Generate a new SSH key pair. Open the terminal and execute:
ssh-keygen -t rsa
When prompted for the file location, change it to:
/config/shell_command_id_rsa
Step 2: Set Up SSH Key Authentication
Append the public key to the authorized keys and test the SSH connection:
cat /config/shell_command_id_rsa.pub >> /root/.ssh/authorized_keys
cd /config
ssh -i shell_command_id_rsa root@localhost
This should open a new SSH session. Type exit
to close the session.
Step 3: Create a Directory for Shell Scripts
Create a directory to store your shell scripts:
mkdir /config/shell
Step 4: Create the Backup Removal Script
Create a shell script that deletes backups older than 7 days:
nano /config/shell/remove-old-backups.sh
Add the following content to the script:
#!/bin/bash
# Remove old backup files
# -mtime +7 corresponds to files older than 7 days
find /backup -name '*.tar' -mtime +7 -exec rm -f {} \;
Make the script executable:
chmod +x /config/shell/remove-old-backups.sh
Step 5: Edit the Home Assistant Configuration
Edit the configuration.yaml
file to add a shell command that executes your script via SSH:
shell_command:
delete_old_backups: 'ssh -i /config/shell_command_id_rsa -o StrictHostKeyChecking=no root@localhost bash /config/shell/remove-old-backups.sh'
Step 6: Create an Automation to Run the Script
Add an automation to run the shell command daily. Edit your automations.yaml
or use the UI to create a new automation:
automation:
- alias: Delete Old Backups
description: Deletes backups older than 7 days every day at 3:30 AM
trigger:
- platform: time
at: "03:30:00"
action:
- service: shell_command.delete_old_backups
Step 7: Restart Home Assistant
Restart Home Assistant to apply the changes:
ha core restart
Summary
You’ve now set up an automated system to delete backups older than 7 days using a custom shell script and Home Assistant automations.
Feel free to adapt the SSH setup to suit other types of commands if needed.