2022-10-11 14:21:14 -06:00
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# Purpose:
# ec2-ruby-example-get-all-instance-info.rb demonstrates how to
# list the IDs and current states of available
# Amazon Elastic Compute Cloud (Amazon EC2) instances.
# snippet-start:[ec2.Ruby.getAllInstances]
2024-09-25 15:25:54 -04:00
require 'aws-sdk-ec2'
2022-10-11 14:21:14 -06:00
# @param ec2_resource [Aws::EC2::Resource] An initialized EC2 resource object.
# @example
# list_instance_ids_states(Aws::EC2::Resource.new(region: 'us-west-2'))
def list_instance_ids_states ( ec2_resource )
response = ec2_resource . instances
if response . count . zero?
2024-09-25 15:25:54 -04:00
puts 'No instances found.'
2022-10-11 14:21:14 -06:00
else
2024-09-25 15:25:54 -04:00
puts 'Instances -- ID, state:'
2022-10-11 14:21:14 -06:00
response . each do | instance |
puts " #{ instance . id } , #{ instance . state . name } "
end
end
rescue StandardError = > e
puts " Error getting information about instances: #{ e . message } "
end
2024-02-16 11:17:29 -05:00
# Example usage:
2022-10-11 14:21:14 -06:00
def run_me
2024-09-25 15:25:54 -04:00
region = ''
2022-10-11 14:21:14 -06:00
# Print usage information and then stop.
2024-09-25 15:25:54 -04:00
if ARGV [ 0 ] == '--help' || ARGV [ 0 ] == '-h'
puts 'Usage: ruby ec2-ruby-example-get-all-instance-info.rb REGION'
2022-10-11 14:21:14 -06:00
# Replace us-west-2 with the AWS Region you're using for Amazon EC2.
2024-09-25 15:25:54 -04:00
puts 'Example: ruby ec2-ruby-example-get-all-instance-info.rb us-west-2'
2022-10-11 14:21:14 -06:00
exit 1
# If no values are specified at the command prompt, use these default values.
# Replace us-west-2 with the AWS Region you're using for Amazon EC2.
elsif ARGV . count . zero?
2024-09-25 15:25:54 -04:00
region = 'us-west-2'
2022-10-11 14:21:14 -06:00
# Otherwise, use the values as specified at the command prompt.
else
region = ARGV [ 0 ]
end
ec2_resource = Aws :: EC2 :: Resource . new ( region : region )
list_instance_ids_states ( ec2_resource )
end
run_me if $PROGRAM_NAME == __FILE__
# snippet-end:[ec2.Ruby.getAllInstances]