-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaws_backup.rb
71 lines (58 loc) · 1.94 KB
/
aws_backup.rb
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
#!/usr/bin/env ruby
require 'rubygems'
require 'aws/ec2'
SNAPSHOTS_TO_KEEP = ENV['SNAPSHOTS_TO_KEEP'] || 3
def setTags(snapshot)
if @client_tag
snapshot.tags['Client'] = @client_tag
snapshot.tags['Type'] = 'Prod'
snapshot.tags['Use'] = 'Storage'
end
end
def createSnapshot(project_name, volume_id, volume_name)
ec2 = AWS.ec2
volume = ec2.volumes[volume_id]
if volume.exists?
snapshot = volume.create_snapshot("#{project_name} - #{volume_name} volume backup - created by Jenkins")
setTags(snapshot)
puts "Creating a snapshot with ID=#{snapshot.id} of #{snapshot.volume_size}Gb"
else
abort "Volume #{volume_id} not found! Aborting..."
end
end
def getSnapshots(volume_id)
ec2 = AWS.ec2
volume_snapshots = Array.new
ec2.snapshots.each do |snapshot|
if snapshot.volume_id == volume_id
volume_snapshots.push(snapshot)
end
end
return volume_snapshots.sort_by {|volume| volume.start_time}.reverse
end
def removeExpiredSnapshots(volume_snapshots)
if volume_snapshots.length > SNAPSHOTS_TO_KEEP.to_i
volume_snapshots[SNAPSHOTS_TO_KEEP.to_i..volume_snapshots.length-1].each do |snapshot|
if snapshot.description =~ /volume backup - created by Jenkins/
puts "Deleting expired snapshot, created at #{snapshot.start_time}"
snapshot.delete
end
end
end
end
if ARGV.length != 4 and ARGV.length != 5
abort "Expecting 4 parameters: project_name volume_id volume_name region [Client tag]"
end
project_name = ARGV[0]
volume_id = ARGV[1]
volume_name = ARGV[2]
region = ARGV[3]
if [ARGV.length == 5]
@client_tag =ARGV[4]
end
AWS.config({:access_key_id=> ENV['AWS_ACCESS_KEY'], :secret_access_key=> ENV['AWS_SECRET_KEY'], :region => region})
puts "Starting EBS volume #{volume_id} backup in #{region.upcase}"
createSnapshot(project_name, volume_id, volume_name)
snapshots = getSnapshots(volume_id)
removeExpiredSnapshots(snapshots)
puts "Process completed successfully"