Skip to content

Instantly share code, notes, and snippets.

@gkspranger
Last active January 15, 2017 16:15
Show Gist options
  • Save gkspranger/772d81b3b01375637fc20ac91957b99b to your computer and use it in GitHub Desktop.
Save gkspranger/772d81b3b01375637fc20ac91957b99b to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# takes a snapshot of the provided device and writes a description
# will freeze the FS, snapshot, then unfreeze
# has the ability to "wait" until the snapshot is done if you want to make sure before you proceed to other tasks
#
device=0
desc=0
wait=0
help_msg="options -d (device path) and -c (snapshot description) are required .. -w (wait) is optional"
log () {
DATE=$(date)
echo "$DATE - $1" >&2
}
while getopts "d:c:wh" opt; do
case $opt in
d)
log "device is: $OPTARG"
device="$OPTARG"
;;
c)
log "description is: $OPTARG"
desc="$OPTARG"
;;
w)
log "wait is set to TRUE"
wait=1
;;
h)
log "$help_msg"
exit 0
;;
esac
done
if [[ "$device" == "0" ]] || [[ "$desc" == "0" ]]; then
log "$help_msg"
exit 1
fi
log "getting volume attached to $device"
vol_id=$(aws ec2 describe-instances --region {{ ansible_ec2_placement_region }} --instance-ids {{ ansible_ec2_instance_id }} | jq -r '.Reservations[0] .Instances[0] .BlockDeviceMappings[] | select(.DeviceName == "'$device'") | .Ebs .VolumeId')
log "volume id associated with $device is: $vol_id"
log "get FS path this device is mounted to"
fs_path=`cat /etc/mtab | grep "$device" | awk '{print $2}'`
log "$device is mounted to $fs_path"
log "freezing fs path: $fs_path"
/bin/sync && /sbin/fsfreeze -f $fs_path
log "taking snapshot of $vol_id"
snap_id=$(aws ec2 create-snapshot --region {{ ansible_ec2_placement_region }} --volume-id $vol_id --description "$desc" | jq -r '.SnapshotId')
log "done taking snapshot of $vol_id .. new snapshot id is: $snap_id"
log "unfreezing fs path: $fs_path"
/sbin/fsfreeze -u $fs_path
dp=`echo "$device" | sed 's/\/dev\//_/g'`
fp=`echo "$fs_path" | sed 's/\//_/g'`
name="`hostname`${dp}${fp}"
log "creating Name tag of '$name' for new snapshot $snap_id for pretty pretty"
aws ec2 create-tags --region {{ ansible_ec2_placement_region }} --resources $snap_id --tags Key=Name,Value="$name"
if [[ $wait -gt 0 ]]; then
IS_READY=0
while [ $IS_READY -eq 0 ]; do
NEW_SNAP_STATE=$(aws ec2 describe-snapshots --region {{ ansible_ec2_placement_region }} --snapshot-ids $snap_id | jq -r '.Snapshots[0] .State')
NEW_SNAP_PROGRESS=$(aws ec2 describe-snapshots --region {{ ansible_ec2_placement_region }} --snapshot-ids $snap_id | jq -r '.Snapshots[0] .Progress')
NOW=$(date)
if [ $NEW_SNAP_STATE == 'completed' ]; then
IS_READY=1
echo "$NOW - new snapshot is 100% ready and is in a 'completed' state"
else
echo "$NOW - new snapshot is NOT ready .. state is: $NEW_SNAP_STATE, progress is: $NEW_SNAP_PROGRESS"
sleep 20
fi
done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment