获取有关特定 Amazon EC2 实例的信息 - 适用于 Ruby 的 Amazon 开发工具包
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

获取有关特定 Amazon EC2 实例的信息

以下示例列出了指定 Amazon EC2 实例的状态。

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX - License - Identifier: Apache - 2.0 require 'aws-sdk-ec2' # Lists the state of an Amazon Elastic Compute Cloud (Amazon EC2) instance. # # Prerequisites: # # - An Amazon EC2 instance. # # @param ec2_client [Aws::EC2::Client] An initialized EC2 client. # @param instance_id [String] The ID of the instance. # @example # list_instance_state( # Aws::EC2::Resource.new(region: 'us-east-1'), # 'i-123abc' # ) def list_instance_state(ec2_client, instance_id) response = ec2_client.describe_instances( instance_ids: [instance_id] ) if response.count.zero? puts 'No matching instance found.' else instance = response.reservations[0].instances[0] puts "The instance with ID '#{instance_id}' is '#{instance.state.name}'." end rescue StandardError => e puts "Error getting information about instance: #{e.message}" end # Full example call: def run_me instance_id = '' region = '' # Print usage information and then stop. if ARGV[0] == '--help' || ARGV[0] == '-h' puts 'Usage: ruby ec2-ruby-example-list-state-instance-i-123abc.rb ' \ 'INSTANCE_ID REGION' puts 'Example: ruby ec2-ruby-example-list-state-instance-i-123abc.rb ' \ 'i-123abc us-east-1' exit 1 # If no values are specified at the command prompt, use these default values. elsif ARGV.count.zero? instance_id = 'i-123abc' region = 'us-east-1' # Otherwise, use the values as specified at the command prompt. else instance_id = ARGV[0] region = ARGV[1] end ec2_client = Aws::EC2::Client.new(region: region) list_instance_state(ec2_client, instance_id) end run_me if $PROGRAM_NAME == __FILE__