backup-bot-two/backup.sh

61 lines
1.8 KiB
Bash
Executable File

#!/bin/bash
server_name="${SERVER_NAME:?SERVER_NAME not set}"
restic_password_file="${RESTIC_PASSWORD_FILE:?RESTIC_PASSWORD_FILE not set}"
restic_sftp_host="${RESTIC_SFTP_HOST:?RESTIC_SFTP_HOST not set}"
restic_repo="sftp:$restic_sftp_host:/$server_name"
backup_path="${BACKUP_DEST:?BACKUP_DEST not set}"
if [ -n "$SERVICES_OVERRIDE" ]; then
# this is fine because docker service names should never include spaces or
# glob characters
# shellcheck disable=SC2206
services=($SERVICES_OVERRIDE)
else
mapfile -t services < <(docker service ls --format '{{ .Name }}')
fi
for service in "${services[@]}"; do
echo "service: $service"
details=$(docker service inspect "$service" --format "{{ json .Spec.Labels }}")
if echo "$details" | jq -r '.["backupbot.backup"]' | grep -q 'true'; then
pre=$(echo "$details" | jq -r '.["backupbot.backup.pre-hook"]')
post=$(echo "$details" | jq -r '.["backupbot.backup.post-hook"]')
path=$(echo "$details" | jq -r '.["backupbot.backup.path"]')
if [ "$path" = "null" ]; then
echo "ERROR: missing 'path' for $service"
continue # or maybe exit?
fi
container=$(docker container ls -f "name=$service" --format '{{ .ID }}')
echo "backing up $service"
test -d "$backup_path/$service" || mkdir "$backup_path/$service"
if [ "$pre" != "null" ]; then
# run the precommand
# shellcheck disable=SC2086
docker exec "$container" sh -c "$pre"
fi
# run the backup
docker cp "$container:$path" "$backup_path/$service"
if [ "$post" != "null" ]; then
# run the postcommand
# shellcheck disable=SC2086
docker exec "$container" sh -c "$post"
fi
fi
done
restic -p "$restic_password_file" \
backup --quiet -r "$restic_repo" \
-o sftp.command="ssh $restic_sftp_host -s sftp" \
--tag coop-cloud "$backup_path"