5
5

More than 5 years have passed since last update.

aws-sdkでELBにEC2を紐付ける

Last updated at Posted at 2013-10-21

やりたいこと

  • EC2をELBに紐付けるのを自動化
  • In ServiceになるまでManagement Consoleから更新ボタンをポチポチしなくていいようにする

処理概要

  1. 引数はTrollopで処理
    • EC2はInstance IDベースで処理する
    • ELB はName指定
    • ELBへの紐付けに時間がかかることがあるのでTimeoutを設定
  2. ELBへの登録
    • elb.availability_zones.enableしないとエラーが発生することがある(後述)
  3. ELBへの紐付け後、EC2のステータスがIn Serviceになるまで待つ
    • 紐付け中、EC2が起動中、EC2上のアプリが起動中の場合は15秒待って再度ステータスチェック
    • その他の場合はEC2のステータスとその説明を表示して終了する

コード

register_elb.rb
require 'aws-sdk'
require 'trollop'

# 引数チェック
ec2 = AWS::EC2.new
regions = ec2.regions.map{ |regions| regions.name }
opts = Trollop::options do
  opt :region,       "aws region (#{regions.join(", ")})",      :type => :string,  :default => "us-east-1"
  opt :instance_ids, "ec2 instance id",                         :type => :strings, :required => true
  opt :elb_name,     "elb name",                                :type => :string,  :required => true
  opt :timeout,      "wait time from in service (default:300)", :type => :integer, :default => 300
end
Trollop::die :region, "aws region are eu-west-1, sa-east-1, ... " unless regions.include?(opts[:region])

# ELBにEC2を登録
elb = AWS::ELB.new(:region => opts[:region]).load_balancers[opts[:elb_name]]
opts[:instance_ids].each do |instance_id|
  ec2 = AWS::EC2.new(:region => opts[:region]).instances[instance_id]
  elb.availability_zones.enable(ec2.availability_zone)
  elb.instances.register(ec2)
end

# EC2がIn Serviceになるまで待つ
opts[:instance_ids].each do |instance_id|
  puts "EC2 instance registered elb : #{opts[:elb_name]}."
  puts "Please wait for EC2 instances state is in service."
  ec2 = elb.instances[instance_id]
  timeout(opts[:timeout]){
    while ec2.elb_health.state != "InService"
      case ec2.elb_health[:description]
      when /in progress/, /in pending state/, /failed at least the UnhealthyThreshold number/
        puts "  [#{instance_id}] #{ec2.elb_health[:description]}"
        sleep 15
      else
        puts "  [#{instance_id}] #{ec2.elb_health.state}"
        puts "  [#{instance_id}] #{ec2.elb_health[:description]}"
        exit
      end
      STDOUT.flush
    end
  }
  puts "EC2 instance (#{instance_id}) state is #{ec2.elb_health.state}"
end
puts "Completed"

elb.availability_zones.enable でエラー

T.B.D

5
5
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
5
5