Skip to content

Instantly share code, notes, and snippets.

@shaiesto
Created December 12, 2016 13:58
Show Gist options
  • Save shaiesto/8829a5fdb0725e33ee094a7f9c74f696 to your computer and use it in GitHub Desktop.
Save shaiesto/8829a5fdb0725e33ee094a7f9c74f696 to your computer and use it in GitHub Desktop.
Take snapshots of aws instance based on the name tag.
#!/usr/bin/env sh
### aj@22seven.com
### script to snapshot aws instances based in instance name.
# Great big construct to remind me how it all works.
# Also happens to be a multiline self-documenting comment.
THIS=$(basename "$0" .sh)
DOCZ=$(cat <<-docz
AWS Instance snapshotter.\n\n
Usage: $THIS [-n | --name] {INSTANCE NAME}\n\n
-n --name The name of the instance to snapshot. Should be unique.\n
-h --help This text.\n\n
docz
)
if test "$#" -eq "0"; then
printf "%b\n" "No options provided."
echo $DOCZ; exit 1;
fi
function SNAPSHOT() {
#Find and snapshot drives.
printf "%b\n" "Quering aws for $INSTANCENAME details..."
INSTANCEID=$(aws ec2 describe-instances --query "Reservations[].Instances[].[InstanceId, Tags[?Key=='Name'] | [0].Value]" --output text | awk "/$INSTANCENAME/ {print \$1}");
printf "%b\n" "$INSTANCENAME InstanceId: $INSTANCEID"
VOLUMES=$(aws ec2 describe-instances --instance-ids $INSTANCEID --query "Reservations[].Instances[].BlockDeviceMappings[].Ebs[].VolumeId" --output text);
printf "%b\n" "Starting snapshot/s of $VOLUMES..."
for VOLUME in $VOLUMES; do
SNAPSHOT=$(aws ec2 create-snapshot --output text --volume-id "$VOLUME" --description "$INSTANCEID" | awk '{print $4}');
printf "%b\n" "Snapshot ID: $SNAPSHOT"
done
}
while (($#)); do
case $1 in
-n | --name) INSTANCENAME=$2 && (SNAPSHOT) ;;
-h | --help) echo $DOCZ; exit 0;;
*) echo $DOCZ; exit 1;;
esac
shift 2
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment