Module: Sonic::Ssh::Ec2Tag

Included in:
IdentifierDetector
Defined in:
lib/sonic/ssh/ec2_tag.rb

Overview

ec2 tag related methods

Instance Method Summary collapse

Instance Method Details

#ec2_instancesObject



6
7
8
9
10
11
# File 'lib/sonic/ssh/ec2_tag.rb', line 6

def ec2_instances
  return @ec2_instances if @ec2_instances

  filters = [{ name: 'tag-value', values: tags_filter }]
  @ec2_instances = ec2_resource.instances(filters: filters)
end

#ec2_tag_exists?Boolean

matches any tag value

Returns:

  • (Boolean)


14
15
16
# File 'lib/sonic/ssh/ec2_tag.rb', line 14

def ec2_tag_exists?
  ec2_instances.count > 0
end

#find_ec2_instanceObject

If no instances found

Exit immediately with error message

If all instances found have the same tag name

Immediately return the first instance id

If multiple tag values

Prompt user to select instance tag value of interest


24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/sonic/ssh/ec2_tag.rb', line 24

def find_ec2_instance
  tag_values = ec2_instances.map{ |i| matched_tag_value(i) }.uniq
  case tag_values.size
  when 0
    UI.error("Unable to find an instance with a one of the tag values: #{@identifier}")
    exit 1
  when 1
    ec2_instances.first.instance_id
  else
    # prompt
    select_instance_type(tag_values).instance_id
  end
end

#matched_tag_value(instance) ⇒ Object



49
50
51
52
53
# File 'lib/sonic/ssh/ec2_tag.rb', line 49

def matched_tag_value(instance)
  tags = instance.tags
  tag = tags.find {|t| tags_filter.include?(t.value) }
  tag.value
end

#select_instance_type(tag_values) ⇒ Object



38
39
40
41
42
43
44
45
46
47
# File 'lib/sonic/ssh/ec2_tag.rb', line 38

def select_instance_type(tag_values)
  UI.say("Found multiple instance types matching the tag filter: #{@identifier}")
  prompt = TTY::Prompt.new
  tag_value = prompt.select("Select an instance type tag:", tag_values)

  # find the first instance with the tag_value
  instance = ec2_instances.find do |i|
    i.tags.find { |t| t.value == tag_value }
  end
end

#tags_filterObject



55
56
57
# File 'lib/sonic/ssh/ec2_tag.rb', line 55

def tags_filter
  @identifier.split(',') # identifier from CLI could be a comma separated list
end