Automating snapshot creation and cleanup is an essential task for server management, ensuring data safety and efficient resource usage. The following Bash script accomplishes this by creating snapshots of a server hosted on Hetzner Cloud and deleting snapshots older than two days. This guide explains the script step by step.
Prerequisites
Before running the script, ensure you have:
- A Hetzner Cloud account with API access.
- jq installed on your Debian 12 server (
sudo apt install jq). - curl installed on your Debian 12 server (
sudo apt install curl).
The Script
Save the following script as hetzner_backup.sh:
How the Script Works
- Configuration: Replace
YOURSERVERIDandYOUR API TOKENwith your Hetzner Cloud server ID and API token respectively. These credentials allow the script to interact with the Hetzner Cloud API. - Logging: The script logs its actions to
/var/log/hetzner_backup.log. Ensure this file is writable by the user running the script. - Snapshot Creation:
- The
create_snapshotfunction creates a snapshot with the current date as the description. - It uses the
curlcommand to send a POST request to the Hetzner API, creating a snapshot of the specified server. - Responses are checked for errors, and the outcome is logged.
- Old Snapshot Deletion:
- The
delete_old_snapshotsfunction retrieves a list of snapshots older than two days usingcurlandjqfor JSON processing. - For each outdated snapshot, a DELETE request is sent to the Hetzner API to remove it.
- The script logs the success or failure of each deletion attempt.
Running the Script
- Make the Script Executable: Set execute permissions for the script:
chmod +x hetzner_backup.sh
- Schedule the Script: Use
cronto schedule the script for periodic execution. For example, to run the script daily at midnight:
crontab -e
Add the following line:
0 0 * * * /path/to/hetzner_backup.sh
Conclusion
This script automates the process of creating and cleaning up snapshots on a Hetzner Cloud server. By scheduling it with cron, you can ensure regular backups and manage disk space efficiently by removing old snapshots. This approach enhances your server management and data safety practices, If you need to see what's your server ID, click here.
Was this worth your time?



