Skip to content

Instantly share code, notes, and snippets.

@vladbabii
Created March 26, 2024 12:19
Show Gist options
  • Save vladbabii/2544487fed9707816bfd9693db229261 to your computer and use it in GitHub Desktop.
Save vladbabii/2544487fed9707816bfd9693db229261 to your computer and use it in GitHub Desktop.
migrate proxmox containers from current host to a remote. doing stop, backup, rsync then start. also sets 'migrated' tag and disables onboot start on source
#!/bin/bash
# Read the ID from the first argument
id="$1"
MODE="stop"
STORAGE_LOCAL="backups3"
STORAGE_LOCAL_PATH="/storage3/pve-backup"
REMOTE_HOST="outbound"
REMOTE_PATH="/var/lib/vz/dump"
REMOTE_RESTORE_STORAGE="fast-pve"
# Get the current year and day
today=$(date +%Y_%m_%d)
echo "YMD: $today"
# Stop the Proxmox container with the specified ID
pct stop "$id"
pct set $id --onboot 0
backup=$(ls $STORAGE_LOCAL_PATH/dump/ | grep "$id" | grep "$today" | grep -v -e ".log" | grep -v -e ".notes" | sort -r | head -n 1)
if [ -z "$backup" ]; then
echo "Creating a backup..."
vzdump "$id" --compress zstd --storage $STORAGE_LOCAL --mode $MODE --notes-template '{{guestname}}'
backup=$(ls $STORAGE_LOCAL_PATH/dump/ | grep "$id" | grep "$today" | grep -v -e ".log" | grep -v -e ".notes" | sort -r | head -n 1)
fi
if [ -z "$backup" ]; then
echo "Error: Backup failed/not found"
exit 1
fi
bname=$(echo "$backup" | cut -d'.' -f1)
echo "Using backup: $bname"
tags=$(pct config $id | grep "tags: ")
echo ""
echo "----"
echo "$tags"
if [[ $tags == *"migrated"* ]]; then
echo "Tags contain 'migrated'"
else
echo "Tags do not contain 'migrated'"
existing=$(pct config $id | grep "tags: " | cut -d' ' -f2-)
echo "[$existing]"
if [ -z "$existing" ]; then
existing="migrated"
else
existing="$existing;migrated"
fi
pct set $id --tags "$existing"
fi
# # # Rsync the backup to the second server
echo "----"
echo "Copying files..."
rsync -avz $STORAGE_LOCAL_PATH/dump/$bname* $REMOTE_HOST:$REMOTE_PATH
# # # Run a command on the second server to restore the backup
echo "----"
echo "Restoring backup..."
ssh $REMOTE_HOST "pct restore $id $REMOTE_PATH/$backup --storage $REMOTE_RESTORE_STORAGE --onboot 1"
echo "----"
echo "Starting ..."
ssh $REMOTE_HOST "pct start $id"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment