|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +# Variables |
| 4 | +DIR_TO_BACKUP="<dir-path>" |
| 5 | +BUCKET_NAME="<bucket-name>" |
| 6 | +DATE=$(date +%Y_%m_%d_%H_%M) |
| 7 | +ZIP_NAME="$(basename "$DIR_TO_BACKUP")-backup-$DATE.zip" |
| 8 | +HOME_DIR="/home/$(whoami)" |
| 9 | +ZIP_PATH="$HOME_DIR/$ZIP_NAME" |
| 10 | +TEMP_BACKUP_DIR="$HOME_DIR/monitoring-backup-tmp-$DATE" |
| 11 | +LOG_FILE="$HOME_DIR/container-backups.log" |
| 12 | + |
| 13 | +# Start logging |
| 14 | +echo "############### Backup Started at $(date) ###############" | tee -a "$LOG_FILE" |
| 15 | + |
| 16 | +# Create temporary backup copy |
| 17 | +echo "Copying files from $DIR_TO_BACKUP to $TEMP_BACKUP_DIR..." | tee -a "$LOG_FILE" |
| 18 | +mkdir -p "$TEMP_BACKUP_DIR" |
| 19 | +rsync -avh "$DIR_TO_BACKUP/" "$TEMP_BACKUP_DIR/" | tee -a "$LOG_FILE" |
| 20 | + |
| 21 | +if [ $? -ne 0 ]; then |
| 22 | + echo "Rsync failed! Exiting." | tee -a "$LOG_FILE" |
| 23 | + rm -rf "$TEMP_BACKUP_DIR" |
| 24 | + exit 1 |
| 25 | +fi |
| 26 | + |
| 27 | +# Zip the copied files |
| 28 | +echo "Creating zip file: $ZIP_NAME..." | tee -a "$LOG_FILE" |
| 29 | +zip -rq "$ZIP_PATH" "$TEMP_BACKUP_DIR" |
| 30 | + |
| 31 | +if [ $? -eq 0 ]; then |
| 32 | + echo "Zip file created successfully: $ZIP_PATH" | tee -a "$LOG_FILE" |
| 33 | + FILE_SIZE=$(stat --printf="%s" "$ZIP_PATH") |
| 34 | + FILE_SIZE_MB=$(echo "scale=2; $FILE_SIZE / 1048576" | bc) |
| 35 | + echo "Backup size is: $FILE_SIZE_MB MB" | tee -a "$LOG_FILE" |
| 36 | +else |
| 37 | + echo "Failed to create zip file. Exiting." | tee -a "$LOG_FILE" |
| 38 | + rm -rf "$TEMP_BACKUP_DIR" |
| 39 | + exit 1 |
| 40 | +fi |
| 41 | + |
| 42 | +# Cleanup temp copied files |
| 43 | +echo "Cleaning up temporary backup directory..." | tee -a "$LOG_FILE" |
| 44 | +rm -rf "$TEMP_BACKUP_DIR" |
| 45 | + |
| 46 | +# Upload the zip file to S3 |
| 47 | +echo "Uploading $ZIP_NAME to S3 bucket $BUCKET_NAME..." | tee -a "$LOG_FILE" |
| 48 | +aws s3 cp "$ZIP_PATH" "s3://$BUCKET_NAME/" --quiet |
| 49 | + |
| 50 | +if [ $? -eq 0 ]; then |
| 51 | + echo "Upload completed. Deleting local zip file..." | tee -a "$LOG_FILE" |
| 52 | + rm -f "$ZIP_PATH" |
| 53 | +else |
| 54 | + echo "Upload failed. Keeping the zip file for debugging." | tee -a "$LOG_FILE" |
| 55 | +fi |
| 56 | + |
| 57 | +# Final log entries |
| 58 | +echo "############### End of Logging Session on $(date) ###############" | tee -a "$LOG_FILE" |
| 59 | +echo "_____________________________________________________________" | tee -a "$LOG_FILE" |
| 60 | + |
| 61 | +# Upload the log file to S3 |
| 62 | +aws s3 cp "$LOG_FILE" "s3://$BUCKET_NAME/logs/container-backups-$DATE.log" |
0 commit comments