Class: AwsHelpers::EC2::Image

Inherits:
Object
  • Object
show all
Defined in:
lib/aws_helpers/ec2/image.rb

Instance Method Summary collapse

Constructor Details

#initialize(ec2_client) ⇒ Image

Returns a new instance of Image


9
10
11
12
# File 'lib/aws_helpers/ec2/image.rb', line 9

def initialize(ec2_client)
  @now = Time.now
  @ec2_client = ec2_client
end

Instance Method Details

#create(instance_id, name, additional_tags = []) ⇒ Object


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/aws_helpers/ec2/image.rb', line 14

def create(instance_id, name, additional_tags = [])
  image_name = "#{name} #{@now.strftime('%Y-%m-%d-%H-%M')}"
  puts "Creating Image #{image_name}"
  begin
    image_id = create_image(image_name, instance_id)
    tag_image(image_id, name, additional_tags)
    poll_image_available(image_id)
    image_id
  rescue
    begin
      poll_image_available(image_id) if image_id
    rescue
      # _ Needed because deletion will fail if the image hasn't finished processing
    end
    delete_by_id(image_id) if image_id
    raise
  end
end

#delete(name, options) ⇒ Object


33
34
35
36
# File 'lib/aws_helpers/ec2/image.rb', line 33

def delete(name, options)
  delete_time = Time.subtract_period(@now, options)
  delete_by_time(name, delete_time)
end

#delete_by_time(name, time) ⇒ Object


38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/aws_helpers/ec2/image.rb', line 38

def delete_by_time(name, time)
  puts "Deleting images created before #{time}"
  images = find_by_tag([{ name: 'Name', value: name }])
  images.each { |image|
    image_id = image[:image_id]
    date_tag = image[:tags].detect { |tag| tag[:key] == 'Date' }
    create_time = Time.parse(date_tag[:value])
    if create_time < time
      delete_by_id(image_id)
    end
  }
end

#find_by_tag(tags) ⇒ Object


51
52
53
54
55
56
# File 'lib/aws_helpers/ec2/image.rb', line 51

def find_by_tag(tags)
  filters = tags.map { |tag|
    { name: "tag:#{tag[:name]}", values: [tag[:value]] }
  }
  @ec2_client.describe_images(filters: filters)[:images]
end