Skip to content

Instantly share code, notes, and snippets.

@arturopie
Forked from tom-butler/ec2_helper.rb
Created March 5, 2018 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arturopie/b762a1e0df2d22b098ce0caa8330970e to your computer and use it in GitHub Desktop.
Save arturopie/b762a1e0df2d22b098ce0caa8330970e 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment