LoginSignup
8
8

More than 5 years have passed since last update.

rubyのaws-sdkでEC2のイベント情報を取得する

Posted at

EC2のイベントを1日1回監視してIRCに通知するようにしている(管理者ではないのでメールが飛んでこない)。
そのスクリプトのイベント取得部分を記録する。

イベント情報取得スクリプト

  • Gemfile
    • aws-sdk (1.38.0) で 動作確認
source "https://rubygems.org"

gem "aws-sdk"
  • 全てのリージョンのイベントを表示するスクリプト
# -*- encoding: utf-8 -*-
require 'aws-sdk'

ec2 = AWS::EC2.new(proxy_uri: ENV['HTTP_PROXY'] || ENV['http_proxy'])
# 各リージョンのEC2全て取得対象
ec2.regions.each do |region|
  reg = ec2.regions[region.name]
  reg.instances.each do |instance|
    # イベント取得
    status = reg.client.describe_instance_status({"instance_ids" => [ instance.id ]})
    events = status.data[:instance_status_set][0][:events_set] rescue nil
    events = [] unless events
    next if events.empty?

    events.each do |event|
      next if event[:description] =~ /^\[Completed\]/ # 完了したイベントはスキップ
      puts "EC2[#{instance.tags["Name"] || instance.dns_name}](#{region.name})のイベント #{event}"
   end
  end
end

出力サンプル

EC2[test](us-east-1)のイベント {:code=>"instance-stop", :description=>"The instance is running on degraded hardware", :not_before=>2014-05-02 00:00:00 UTC}
  • Completedのイベントサンプル
{:code=>"instance-stop", :description=>"[Completed] The instance is running on degraded hardware", :not_before=>2013-09-05 00:00:00 UTC}
8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8