High Desert Hacker

Automating AWS Snapshots

I’ve been running my snapshots manually from the AWS console and it’s time to automate this. Here’s how to get it set up.

Install the AWS CLI

This is needed in order to use the create-snapshot command.

# Download the package to the home directory.
cd ~
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"

# unzip. Creates a directory aws under the current directory.
unzip awscliv2.zip

# Run the install program. By default, the files are all installed to /usr/local/aws-cli, and a symbolic link is created in /usr/local/bin.
sudo ./aws/install

# Verify installation
/usr/local/bin/aws --version

 

Configure the Credentials

This configures and saves your credentials for using the CLI.
You will need your AWS Access Key ID and AWS Secret Access Key. If you haven’t created these yet, go to your AWS Account menu (username in the upper right corner), and choose Security Credentials. Note that once your Secret Access Key is generated, you must note it and you cannot ever retrieve it again.

# Run the configuration program
aws configure

# Respond to the prompts. Your entries will differ here.
AWS Access Key ID [None]: (your 20 digit access key)
AWS Secret Access Key [None]: (your 40 digit secret key)
Default region name [None]: us-west-1
Default output format [None]: json

 

Create the Snapshot Script

I keep all my programs and scripts in /dockerdata/programs, for convenience.

sudo nano /dockerdata/programs/aws_snapshot.sh

My script:

# =================================================================================
#!/bin/bash
# /dockerdata/programs/aws_snapshot.sh
# AWS snapshot of this volume.
# To Run:   /bin/bash /dockerdata/programs/aws_snapshot.sh
# Returns: 0 Ok, 1 if error
# =================================================================================
CMD="aws ec2 create-snapshot"
VOLUME_ID="vol-11111111111111111"
# date params: %Y-%m-%d %H:%M:%S  Note that this is local tz.
# Note that --description parameter chokes on whitespace.
SNAPSHOT_DESCRIPTION="MyVolume_Snapshot_$(date +'%Y-%m-%d_%H:%M')"

$CMD  --volume-id $VOLUME_ID  --description \"$SNAPSHOT_DESCRIPTION\" --output=text
exit $?

 

Test It

/bin/bash /dockerdata/programs/aws_snapshot.sh

Go the the AWS Console, choose Snapshots, and confirm your snapshot is created.

Set it up on a cron

sudo crontab -e

Enter your schedule, in my case, I run it monthly.

# AWS Snapshot - 1st of Month.
0 18  1  *  *  /dockerdata/programs/aws_snapshot.sh