Method: Awspec::Helper::Finder::Ec2#find_ec2

Defined in:
lib/awspec/helper/finder/ec2.rb

#find_ec2(id) ⇒ Object



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
# File 'lib/awspec/helper/finder/ec2.rb', line 4

def find_ec2(id)
  # instance_id or tag:Name

  # First tries to search by using an educated guess, based on the
  # references below:
  # https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/resource-ids.html
  # https://docs.chef.io/inspec/resources/aws_ec2_instance/
  # This should be faster then just first trying ID when the parameter is
  # clearly not one

  # https://medium.com/@Bakku1505/ruby-start-with-end-with-vs-regular-expressions-59728be0859e
  if id.start_with?('i-') && id.length == 19 && id =~ /^i-[0-9a-f]/
    begin
      res = ec2_client.describe_instances({
                                            instance_ids: [id]
                                          })
    rescue Aws::EC2::Errors::InvalidInstanceIDNotFound, Aws::EC2::Errors::InvalidInstanceIDMalformed => e
      res = ec2_client.describe_instances({
                                            filters: [{ name: 'tag:Name', values: [id] }]
                                          })
    end
  else
    begin
      res = ec2_client.describe_instances({
                                            filters: [{ name: 'tag:Name', values: [id] }]
                                          })
    rescue Aws::EC2::Errors::InvalidInstanceIDNotFound, Aws::EC2::Errors::InvalidInstanceIDMalformed => e
      res = ec2_client.describe_instances({
                                            instance_ids: [id]
                                          })
      if res.reservations.count > 1
        STDERR.puts "Warning: '#{id}' unexpectedly identified as a valid instance ID during fallback search"
      end
    end
  end

  return nil if res.reservations.count == 0
  return res.reservations.first.instances.single_resource(id) if res.reservations.count == 1
  raise Awspec::DuplicatedResourceTypeError, dup_ec2_instance(id) if res.reservations.count > 1
  raise "Unexpected condition of having reservations = #{res.reservations.count}"
end