Created
June 1, 2016 19:21
-
-
Save rnagle/74e9ca390b752470ea42d028c43dcaee to your computer and use it in GitHub Desktop.
Create EC2 Snapshots
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 | |
source /home/newsapps/secrets/all_secrets.sh; | |
export AWS_ACCESS_KEY_ID=$SNAPSHOTS_AWS_ACCESS_KEY_ID; | |
export AWS_SECRET_ACCESS_KEY=$SNAPSHOTS_AWS_SECRET_ACCESS_KEY; | |
export PATH=$PATH:/usr/local/bin; | |
export NUMBER_OF_SNAPSHOTS_TO_KEEP=3; | |
export DATE_STR=`date +%y.%m.%d.%I`; | |
export INSTANCE_ID=`ec2metadata --instance-id`; | |
# Get the ID of the volume mounted as the root device on this instance | |
export VOLUME_ID=`/usr/local/bin/aws ec2 describe-volumes --filters Name=attachment.instance-id,Values=$INSTANCE_ID Name=attachment.device,Values=/dev/sda1 --query 'Volumes[*].{ID:VolumeId}' | grep ID | awk '{print $2}' | tr -d '"'` | |
date; | |
echo "Initiating EBS volume snapshot of volume $VOLUME_ID attached to instance ID $INSTANCE_ID..."; | |
/usr/local/bin/aws ec2 create-snapshot --volume-id $VOLUME_ID --description $VOLUME_ID; | |
echo "Done."; | |
echo "Deleting old snapshots..."; | |
# Get any snapshots older than the last $NUMBER_OF_SNAPSHOTS_TO_KEEP | |
# TODO: this should pull the snapshot start date and use that to determine which snapshots should be deleted. | |
for SNAPSHOT_ID in `/usr/local/bin/aws ec2 describe-snapshots --filters Name=volume-id,Values=$VOLUME_ID --query 'Snapshots[*].{ID:SnapshotId}' | grep ID | head -n -$NUMBER_OF_SNAPSHOTS_TO_KEEP | awk '{print $2}' | tr -d '"'` ; do | |
echo "Deleting snapshot $SNAPSHOT_ID..."; | |
/usr/local/bin/aws ec2 delete-snapshot --snapshot-id $SNAPSHOT_ID; | |
done; | |
echo "Done."; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment