詳細検索

Using the AWS SDK for Ruby to check the status of your EC2 instance

Avatar
by maeno
3 min read

Using the AWS SDK for Ruby to check the status of your EC2 instance
Translated from 日本語 • View original

On the application side, there are times when you want to check the current health status of any AWS EC2 instance in real time. For example, when starting or stopping an EC2 instance from an external application, this is the case where you want to check the operation status of the instance and run the next process when the status changes.

The SDK for Ruby allows you to get the status of a specific EC instance using the 'client.describe_instance_status' method of the 'AWS::EC2' class. There are two types of instance statuses: 'system_status' and 'instance_status', and if you want to check the exact operating status, you need to obtain these two statuses. And it's important to note that when the instance is stopped, the status doesn't exist. In other words, if you run the 'client.describe_instance_status' method on a stopped instance, you will not be able to retrieve the contents of the 'instance_status_set' object that stores the status information, so if you do not code based on that, you will get a status retrieval error. For example, when monitoring the status of a stopped instance, it is necessary to assume that there is no status in the 'instance_status_set' object because the instance is stopped at first. Also, it is important to note that the terminated instance does not have a target to execute the 'client.describe_instance_status' method.

Now, based on the above, I created a Ruby program to check the status of EC2 instances.

chkins.rb
# encoding: utf-8
require "aws-sdk"

def check_instance_status

ec2 = AWS::EC2.new(
      :access_key_id => Params[:access_key_id], 
      :secret_access_key => Params[:secret_access_key], 
      :region => Params[:region]
    )

AWS.memoize do
      status = []
      if ec2.instances[Params[:instance_id]].exists?
        ec2info = ec2.client.describe_instance_status({ 'instance_ids' => [Params[:instance_id]] })
        if ec2info.instance_status_set.empty?
          # instance has stopped
          status < 'stopped'
          message = '%s has stopped'
        else
          ec2info.instance_status_set.map { |i| 
            sys_status = i.respond_to?(:system_status) ? i.system_status.details[0].status : nil
            ins_status = i.respond_to?(:instance_status) ? i.instance_status.details[0].status : nil
            status < sys_status < ins_status
          }
          if status.include?('passed')
            # instance is running
            message = '%s is running'

          elsif status.include?('initializing')
            # instance is initializing
            message = '%s is starting'

          else
            # otherwise
            message = '%s is unknown status'

          end
        end
      else
        # instance has terminated
        status < 'terminated'
        message = '%s has already terminated'
      end
      puts sprintf("#{message}. status: %s", "Instance: #{Params[:instance_id]}", status)
    end
end

begin
  # init
  Params = { 
    :access_key_id => ARGV[0], 
    :secret_access_key => ARGV[1], 
    :region => ARGV[2], 
    :instance_id => ARGV[3], 
    :timeout => ARGV[4].nil? ? 1 : ARGV[4].to_i
  }
  raise 'Parameter is missing.' if Params.values.include? (nil)

for i in 1..Params[:timeout] do
    sleep 1 if i > 1
    check_instance_status
  end

rescue => e
  puts e
end

As an argument at program execution,

  • AWS access key (required)
  • AWS Secret Access Key (required)
  • Region (required)
  • Instance ID (the instance ID you want to check the status of)
  • Number of timeouts (how many times in 1 second) Omitting is acceptable. Only once when omitted)

If you pass it to the customer, it will monitor the status of the specified instance with standard output for almost the number of timeouts ≒ seconds.

Execution example:
$ ruby -Ku chkins.rb <AWSアクセスキー> <AWSシークレットキー> ap-southeast-1 <インスタンスID> 10
Instance: i-******** is running. status: ["passed", "passed"]
Instance: i-******** is running. status: ["passed", "passed"]
Instance: i-******** is running. status: ["passed", "passed"]
Instance: i-******** is running. status: ["passed", "passed"]
Instance: i-******** is running. status: ["passed", "passed"]
Instance: i-******** is running. status: ["passed", "passed"]
Instance: i-******** is running. status: ["passed", "passed"]
Instance: i-******** is running. status: ["passed", "passed"]
Instance: i-******** is running. status: ["passed", "passed"]
Instance: i-******** is running. status: ["passed", "passed"]

If the specified instance ID is running, the above results are monitored for about 10 seconds.

  • Before running, you need to install the 'AWS SDK for Ruby' (version 1).

If you add tasks such as sending an email when a specific status is detected, register the script launch in 'cron', and run it regularly, you may be able to monitor the operation status of the instance without relying on AWS CloudWatch. </インスタンスID></AWSシークレットキー></AWSアクセスキー>

Related Articles