Created
December 31, 2015 03:37
-
-
Save dossy/e6108183c442d56be088 to your computer and use it in GitHub Desktop.
Create snapshots of current EC2 instance's volumes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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