Class: EbsSnapper::Ebs

Inherits:
Object
  • Object
show all
Defined in:
lib/ebs_snapper/ebs.rb

Defined Under Namespace

Classes: TTL

Constant Summary collapse

DEFAULT_TAG_NAME =
'Snapper'

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Ebs

Returns a new instance of Ebs.



21
22
23
24
25
26
27
28
29
# File 'lib/ebs_snapper/ebs.rb', line 21

def initialize(opts = {})
  AWS.config(
    :access_key_id => opts[:access_key_id],
    :secret_access_key => opts[:secret_access_key])
    
  @logger = opts[:logger] || Logger.new(STDOUT)
  @retain = opts[:retain]
  @tag_name = opts[:volume_tag] || DEFAULT_TAG_NAME # default
end

Instance Method Details

#each_regionObject



86
87
88
89
90
# File 'lib/ebs_snapper/ebs.rb', line 86

def each_region
  ec2.regions.each do |region|
    yield (region)
  end
end

#ec2Object



92
93
94
95
# File 'lib/ebs_snapper/ebs.rb', line 92

def ec2
  @ec2 ||= AWS::EC2.new
  @ec2
end

#purge_old_snapshots(ttl, region, vol_id) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
# File 'lib/ebs_snapper/ebs.rb', line 73

def purge_old_snapshots(ttl, region, vol_id)
  region.snapshots.filter('volume-id', vol_id).filter('tag-key', @tag_name).each do |snapshot|
    unless snapshot.status == :pending
      ts = snapshot.tags[@tag_name]
      if ttl.purge?(ts)
        @logger.info {"Purging #{vol_id} snapshot: #{snapshot}"}
        snapshot.delete
      end
    end
  end
end

#snapshot_and_purgeObject



31
32
33
34
35
36
37
# File 'lib/ebs_snapper/ebs.rb', line 31

def snapshot_and_purge
  # now snapshot the list
  tagged_volumes.each do |vol_info|
    snapshot_volume(vol_info[:region], vol_info[:volume_id])
    purge_old_snapshots(vol_info[:ttl], vol_info[:region], vol_info[:volume_id])
  end
end

#snapshot_volume(region, vol_id) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/ebs_snapper/ebs.rb', line 60

def snapshot_volume(region, vol_id)
  timestamp = Time.now.utc
  @logger.info {"Snapshotting #{vol_id} at: #{timestamp}"}
  vol = region.volumes[vol_id]
  if vol != nil
    snapshot = vol.create_snapshot("Snapper Backup #{timestamp}")
    # tag the snapshot with the timestamp so we can look it up later for cleanup
    snapshot.tag(@tag_name, :value => "#{timestamp.to_i}")
  else
    @logger.error "Error: Volume #{vol_id} in Region: #{region} not found"
  end
end

#tagged_volumesObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ebs_snapper/ebs.rb', line 39

def tagged_volumes
  volumes = []
  
  each_region do |r|
    r.tags.filter('resource-type', 'volume').filter('key', @tag_name).each do |tag|
      # if the tag exists, it's using the default retention (TTL)
      ttl_value = @retain
      if tag.value != nil && !tag.value.strip.empty?
        ttl_value = tag.value.strip
      end
      
      volumes << {
        :ttl => TTL.new(ttl_value),
        :region => r,
        :volume_id => tag.resource.id # volume id
      }
    end
  end
  volumes
end