Skip to content

Instantly share code, notes, and snippets.

@dossy
Created December 31, 2015 03:37
Show Gist options
  • Save dossy/e6108183c442d56be088 to your computer and use it in GitHub Desktop.
Save dossy/e6108183c442d56be088 to your computer and use it in GitHub Desktop.
Create snapshots of current EC2 instance's volumes.
#!/bin/bash
if [ -z "$AWS_CREDENTIALS" ]; then
AWS_CREDENTIALS="$HOME/.aws/credentials"
fi
if [ ! -e "$AWS_CREDENTIALS" ]; then
echo "$AWS_CREDENTIALS missing; use 'aws configure'."
exit
fi
eval $(sed -ne 's/^\(.*\) = \(.*\)$/\U\1\E=\2/p' "$AWS_CREDENTIALS")
if [ -z "$AWS_ACCESS_KEY_ID" -o -z "$AWS_SECRET_ACCESS_KEY" ]; then
echo "AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY not set."
exit
fi
AWS_ACCESS_KEY=$AWS_ACCESS_KEY_ID
AWS_SECRET_KEY=$AWS_SECRET_ACCESS_KEY
#AWS_DEFAULT_REGION=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed -e 's/[a-z]$//')
AWS_DEFAULT_REGION=$(curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | sed -ne 's/^.*"region" : "\(.*\)",.*$/\1/p')
export AWS_DEFAULT_REGION
echo "Region: $AWS_DEFAULT_REGION"
INSTANCE=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
echo "Instance ID: $INSTANCE"
aws ec2 describe-volumes --filter Name=attachment.instance-id,Values=$INSTANCE --query "Volumes[*].{ID:VolumeId,Device:Attachments[0].Device,Name:Tags[0].Value}" --output text | while read DEV VOL NAME; do
echo "Volume: $VOL $DEV $NAME"
DESC="$(date +%Y%m%d_%H%M%S) $INSTANCE $VOL $(echo $DEV | sed -e 's#/dev/##')"
SNAP=$(aws ec2 create-snapshot --volume-id $VOL --description "$DESC" --query "SnapshotId" --output text 2>&1)
if [ "$?" != "0" ]; then
echo -e "An error occurred when running ec2-create-snapshot. The error returned is:\n$SNAP" 1>&2
exit
fi
echo "Snapshot: $SNAP $DESC"
TAG=$(aws ec2 create-tags --resources $SNAP --tags "Key=Name,Value=$NAME" --output text 2>&1)
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment