-
-
Save arturopie/b762a1e0df2d22b098ce0caa8330970e to your computer and use it in GitHub Desktop.
Get Running Instance ID
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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