Skip to content

Instantly share code, notes, and snippets.

@tom-butler
Last active March 5, 2018 19:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tom-butler/dd85c32f1db49246f2f6ec84f555281f to your computer and use it in GitHub Desktop.
Save tom-butler/dd85c32f1db49246f2f6ec84f555281f to your computer and use it in GitHub Desktop.
Get Running Instance ID
require 'aws-sdk'
# Return only a single running instance with the Name tag specified
class EC2Helper
def self.GetIdFromName(name)
instances = Array.new
# Filter the ec2 instances for name and state pending or running
ec2 = Aws::EC2::Resource.new(region: ENV['AWS_DEFAULT_REGION'])
ec2.instances({filters: [
{name: 'tag:Name', values: [name]},
{name: 'instance-state-name', values: [ 'pending', 'running']}
]}).each do |i|
instances.push(i.id)
end
# If we found a single instance return it, otherwise throw an error.
if instances.count == 1 then
puts 'Found Running EC2 with Name: ' + name + ' ID: ' + instances[0]
return instances[0]
elsif instances.count == 0 then
STDERR.puts 'Error: ' + name + ' Instance not found'
else
STDERR.puts 'Error: ' + name + ' more than one running instance exists with that Name'
end
end
end
@arturopie
Copy link

arturopie commented Mar 5, 2018

Following some Ruby idioms:

module EC2Helper
  def self.get_id_from_name(name)
    # Filter the ec2 instances for name and state pending or running
    ec2 = Aws::EC2::Resource.new(region: ENV['AWS_DEFAULT_REGION'])    
    instances = ec2.instances({ filters: [
      { name: "tag:Name", values: [name] },
      { name: "instance-state-name", values: [ "pending", "running"] }
    ]}).map(&:id)

    if instances.count == 1
      instances[0]
    elsif instances.count == 0
      STDERR.puts "Error: '#{name}' Instance not found"
      []
    else
      STDERR.puts "Error: more than one running instance exists with name '#{name}'"
      instances
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment