-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathebs_backup
executable file
·72 lines (55 loc) · 2.62 KB
/
ebs_backup
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
#!/bin/bash
#
# This script is to ensure the consistent backup of our EBS volume onto Amazon Simple Storage Service via snapshots
# Script paramaters
days=30
echo -e "Automated Daily Snapshot of Important Volumes\r\n"
placement=$(wget -q -O - http://169.254.169.254/latest/meta-data/placement/availability-zone)
region=$(echo ${placement%?})
myid=$(wget -q -O - http://169.254.169.254/latest/meta-data/instance-id)
volumes=$(aws ec2 describe-volumes --filters Name=attachment.instance-id,Values="${myid}" Name=attachment.delete-on-termination,Values=false --region $region)
vol_id=$(echo ${volumes} | jq '.Volumes[].VolumeId' | tr -d '"')
# Define new array for volume names and IDs, to be filled from the volume ID query above.
vol_names=()
vol_ids=()
counter=0
for id in $vol_id
do
# Populate two arrays, one contains the volume IDs to be snapshotted, and the second containing the names for use later.
vol_ids[$counter]=$id
vol_names[$counter]=$(aws ec2 describe-tags --region $region --filters "Name=resource-id,Values=$id" "Name=key,Values=Name" | jq '.Tags[].Value' | tr -d '"')
# If the volume has no name, use the volume ID for the snapshot description instead
if [ -z ${vol_names[$counter]} ]; then
vol_names[$counter]=$id
fi
((counter++))
done
DESC_DATE=$(date +"%Y-%m-%d_%H:%M:%S")
LOG_DATE=$(date +"%b %d %R:%S")
process=0
while [ $process -lt $counter ]
do
Description="Automated - ${vol_names[$process]} snapshot - "${DESC_DATE}
echo "$LOG_DATE Creating snapshot of ${vol_names[$process]} on ${vol_ids[$process]} in $region with Description: ${Description}" >> /var/log/ebs_backups.log
aws ec2 create-snapshot --volume-id ${vol_ids[$process]} --description "${Description}" --region $region --output text >> /var/log/ec2snapshot.log
((process++))
done
# Reset process variable for next loop
process=0
# Purge old backups
OLD='`'$(date +%Y%m%d --date "$days days ago")'`'
# get snapshot id for all snapshots older than $OLD
while [ $process -lt $counter ]
do
snap_ids=$(aws ec2 describe-snapshots --region $region --filters Name=description,Values="Automated - ${vol_names[$process]} *" --query "Snapshots[?StartTime<$OLD]" | jq '.[].SnapshotId' | tr -d '"')
if [ ${#snap_ids} -eq 0 ]; then
echo "No snapshots to purge"
exit 0
fi
readarray snapshots <<< "${snap_ids}"
for snapshot in "${snapshots[@]}"
do
echo "Deleting snapshot $snapshot"
aws ec2 delete-snapshot --snapshot-id $snapshot --region $region >> /var/log/snapshot_purge.log
done
done