Skip to content

Instantly share code, notes, and snippets.

@rnagle
Created June 1, 2016 19:21
Show Gist options
  • Save rnagle/74e9ca390b752470ea42d028c43dcaee to your computer and use it in GitHub Desktop.
Save rnagle/74e9ca390b752470ea42d028c43dcaee to your computer and use it in GitHub Desktop.

Revisions

  1. rnagle created this gist Jun 1, 2016.
    24 changes: 24 additions & 0 deletions create-ec2-snapshot.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    #!/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.";