forked from CaseyLabs/aws-ec2-ebs-automatic-snapshot-bash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathebs-snapshot.sh
executable file
·144 lines (117 loc) · 6.23 KB
/
ebs-snapshot.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/bin/bash
export PATH=$PATH:/usr/local/bin/:/usr/bin
# Safety feature: exit script if error is returned, or if variables not set.
# Exit if a pipeline results in an error.
set -ue
set -o pipefail
## Automatic EBS Volume Snapshot Creation & Clean-Up Script
#
# Written by Casey Labs Inc. (https://www.caseylabs.com)
# Contact us for all your Amazon Web Services Consulting needs!
# Script Github repo: https://github.com/CaseyLabs/aws-ec2-ebs-automatic-snapshot-bash
#
# Additonal credits: Log function by Alan Franzoni; Pre-req check by Colin Johnson
#
# PURPOSE: This Bash script can be used to take automatic snapshots of your Linux EC2 instance. Script process:
# - Determine the instance ID of the EC2 server on which the script runs
# - Gather a list of all volume IDs attached to that instance
# - Take a snapshot of each attached volume
# - The script will then delete all associated snapshots taken by the script that are older than 7 days
#
# DISCLAIMER: This script deletes snapshots (though only the ones that it creates).
# Make sure that you understand how the script works. No responsibility accepted in event of accidental data loss.
#
# ENV VARS:
# AWS_CONFIG_FILE - The location of your AWS config file.
# RETAIN_FOREVER - (Optional) If set to any value, old backups won't be deleted. Overrides all other retention settings.
# RETENTION_DAYS - (Optional) Number of days to retain backups. Default is 7.
# RETAIN_DAY_OF_WEEK - (Optional) An integer indicating a day of the week for which you would like to
# retain backups indefinitely. 1 is Monday, 2 is Tuesday, etc.
## Variable Declartions ##
# Get Instance Details
instance_id=$(wget -q -O- http://169.254.169.254/latest/meta-data/instance-id)
region=$(wget -q -O- http://169.254.169.254/latest/meta-data/placement/availability-zone | sed -e 's/\([1-9]\).$/\1/g')
# Set Logging Options
logfile="/var/log/ebs-snapshot.log"
logfile_max_lines="5000"
# Set default values for vars
if [ -z "${RETENTION_DAYS-}" ]; then RETENTION_DAYS=7; fi
if [ -z "${RETAIN_DAY_OF_WEEK-}" ]; then RETAIN_DAY_OF_WEEK=-1; fi
retention_date_in_seconds=$(date +%s --date "$RETENTION_DAYS days ago")
## Function Declarations ##
# Function: Setup logfile and redirect stdout/stderr.
log_setup() {
# Check if logfile exists and is writable.
( [ -e "$logfile" ] || touch "$logfile" ) && [ ! -w "$logfile" ] && echo "ERROR: Cannot write to $logfile. Check permissions or sudo access." && exit 1
tmplog=$(tail -n $logfile_max_lines $logfile 2>/dev/null) && echo "${tmplog}" > $logfile
exec > >(tee -a $logfile)
exec 2>&1
}
# Function: Log an event.
log() {
echo "[$(date +"%Y-%m-%d"+"%T")]: $*"
}
# Function: Confirm that the AWS CLI and related tools are installed.
prerequisite_check() {
for prerequisite in aws wget; do
hash $prerequisite &> /dev/null
if [[ $? == 1 ]]; then
echo "In order to use this script, the executable \"$prerequisite\" must be installed." 1>&2; exit 70
fi
done
}
# Function: Snapshot all volumes attached to this instance.
snapshot_volumes() {
for volume_id in $volume_list; do
log "Volume ID is $volume_id"
# Get the attched device name to add to the description so we can easily tell which volume this is.
device_name=$(aws ec2 describe-volumes --region $region --output=text --volume-ids $volume_id --query 'Volumes[0].{Devices:Attachments[0].Device}')
# Take a snapshot of the current volume, and capture the resulting snapshot ID
snapshot_description="$(hostname)-$device_name-backup-$(date +%Y-%m-%d)"
snapshot_id=$(aws ec2 create-snapshot --region $region --output=text --description $snapshot_description --volume-id $volume_id --query SnapshotId)
log "New snapshot is $snapshot_id"
# Add a "CreatedBy:AutomatedBackup" tag to the resulting snapshot.
# Why? Because we only want to purge snapshots taken by the script later, and not delete snapshots manually taken.
aws ec2 create-tags --region $region --resource $snapshot_id --tags Key=CreatedBy,Value=AutomatedBackup
# Add a name tag
aws ec2 create-tags --region $region --resource $snapshot_id --tags Key=Name,Value=$SNAPSHOT_NAME_PREFIX-$(date +%Y-%m-%d)
if [[ -n "${CLIENT-}" ]]; then
aws ec2 create-tags --region $region --resource $snapshot_id --tags Key=Client,Value="$CLIENT"
fi
if [[ -n "${PROJECT-}" ]]; then
aws ec2 create-tags --region $region --resource $snapshot_id --tags Key=Project,Value="$PROJECT"
fi
done
}
# Function: Cleanup all snapshots associated with this instance that are older than $RETENTION_DAYS
cleanup_snapshots() {
for volume_id in $volume_list; do
snapshot_list=$(aws ec2 describe-snapshots --region $region --output=text --filters "Name=volume-id,Values=$volume_id" "Name=tag:CreatedBy,Values=AutomatedBackup" --query Snapshots[].SnapshotId)
for snapshot in $snapshot_list; do
log "Checking $snapshot..."
# Check age of snapshot
snapshot_date=$(aws ec2 describe-snapshots --region $region --output=text --snapshot-ids $snapshot --query Snapshots[].StartTime | awk -F "T" '{printf "%s\n", $1}')
snapshot_date_in_seconds=$(date "--date=$snapshot_date" +%s)
snapshot_description=$(aws ec2 describe-snapshots --snapshot-id $snapshot --region $region --query Snapshots[].Description)
if (( $snapshot_date_in_seconds <= $retention_date_in_seconds )); then
if [[ $(date --date=$snapshot_date +%u) == $RETAIN_DAY_OF_WEEK ]]; then
log "Not deleting because retention day: $snapshot $snapshot_description"
else
log "Deleting because too old: $snapshot $snapshot_description"
aws ec2 delete-snapshot --region $region --snapshot-id $snapshot
fi
else
log "Not deleting because not old enough: $snapshot $snapshot_description"
fi
done
done
}
## SCRIPT COMMANDS ##
log_setup
prerequisite_check
# Grab all volume IDs attached to this instance
volume_list=$(aws ec2 describe-volumes --region $region --filters Name=attachment.instance-id,Values=$instance_id --query Volumes[].VolumeId --output text)
snapshot_volumes
if [ -z "${RETAIN_FOREVER-}" ]; then
cleanup_snapshots
fi