Randomly Expressed

About

Welcome to my blog “randomly expressed”. I created this website to publish helpful tips. It’s mainly technology driven, but I will blog about other topics. I am a Unix sysadmin that is always looking to learn new things. My goal is to be able to share knowledge that others may find useful. xkcd.com

Continue Reading »

Contact

Connect With US

Connect with us on the following social networking sites.

Most Popular Posts.

Add Some Content to This Area

You should either deactivate this panel on the Theme Settings page, or add some content via the Widgets page in your WordPress dashboard.

Deleting AWS Storage Gateway Snapshots

By on July 1, 2017 in Technology with No Comments

If you have a nightly snapshot schedule for your volumes that are attached on an AWS storage gateway or ec2 instances you will start to incur higher charges as the number of snapshots increase over time. Instead of deleting them manually you can use the following bash script to automatically delete snapshots when they reach a specific number.
Prerequisites:

  • AWS CLI
  • Bash
  • Purge Snapshot bash script

    #!/bin/bash
    ## version 1.1
    ###Set the number of snapshots you would like to keep in the snapshot_count variable.
    snapshot_count="42"
    profile="ops-or"
    region="us-west-2"
    owner="12345678"
    # Get array of snapshot IDs sorted by age (oldest to newest)
    snapshots=($(/usr/local/bin/aws --profile $profile --region $region ec2 describe-snapshots --owner-ids $owner --filters Name=description,Values=*-snapshot --query 'Snapshots[*].[StartTime,SnapshotId]' --output text | sort -n | awk '{print $2}'))
    # Get number of snapshots
    count=${#snapshots[@]}
    
    if [[ "$count" -lt "$snapshot_count" ]]; then
      echo "We already have less than $snapshot_count snapshots"
      exit 0
    else
      # Drop the last (newest) $snapshot_count IDs from the array
      num="$((count - snapshot_count))"
      snapshots=(${snapshots[@]:0:$num})
      # Loop through the remaining snapshots and delete
      for snapshot in ${snapshots[@]}; do
        /usr/local/bin/aws ec2 delete-snapshot --snapshot-id $snapshot --profile $profile --region $region
      done
    fi
    

    Facebook Comments

    Tagged With: , ,

    Post a Comment

    Your email address will not be published. Required fields are marked *

    Top