Skip to content

Instantly share code, notes, and snippets.

@taka328w
Created January 15, 2012 13:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taka328w/1615935 to your computer and use it in GitHub Desktop.
Save taka328w/1615935 to your computer and use it in GitHub Desktop.
EC2インスタンス生成
# coding: utf-8
require 'rubygems'
require 'aws-sdk'
require 'net/ssh'
config = {:access_key_id => 'アクセスキー ID',
:secret_access_key => 'シークレットアクセスキー'}
AWS.config(config)
ec2 = AWS::EC2.new
# appXXXとタグ付けされているNameタグ一覧を作成
names = []
ec2.instances.each do |instance|
next if instance.status == :terminated
next if instance.status == :shutting_down
tags = instance.tags.to_h
names << tags['Name'] if tags['Name'] =~ /app[\d]+/
end
# 連番の最大値
last = names.sort.last
if last
max_number = names.sort.last.gsub('app', '').to_i
else
max_number = 0
end
# 新しいインスタンス用のホスト名決定
number = sprintf('%03d', max_number + 1)
name = "app#{number}"
# インスタンス起動
create_config = {
:image_id => '使用するAMIのID',
:instance_type => 'm1.small'
}
new_instance = ec2.instances.create(create_config)
# インスタンスが立ち上がるまでsleep
sleep 1 while new_instance.status == :pending
exit 1 unless new_instance.status == :running
# タグ付け
ec2.tags.create(new_instance, "Name", :value => name)
# sshコネクションが確立するまで待つ
# 確立したら、hostname設定
begin
Net::SSH.start(new_instance.private_ip_address, "user") do |ssh|
ssh.exec!("hostname")
ssh.exec!("sudo hostname #{name}")
end
rescue SystemCallError, Timeout::Error => e
sleep 3
retry
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment