黃金俠

Ruby on Rails / Rubygems / Javascript / Git

Rubygems 處理 Amazon Web Service (AWS) EC2

| Comments

參考: https://github.com/grempe/amazon-ec2

安裝設定

Gemfile
1
gem 'amazon-ec2', :require => "AWS"
config/aws.yml
1
2
3
4
5
6
development: &default
  :access_key_id: "abcdabcd"
  :secret_access_key: "abcdabcd"
  :host: "ap-southeast-1.ec2.amazonaws.com"
test:
  <<: *default

access_key_idsecret_access_key 可至 AWS Security Credentials 查看
host 則是目標 region 所對應的 endpoint,對應表可至 https://github.com/garnaat/missingcloud/blob/master/aws.json#L372 查看

養成好習慣, 請勿將 yaml 檔 commit 進去…

.gitignore
1
config/aws.yml
config/aws.yml.example
1
2
3
4
5
6
7
8
# to see region and host mapping :
#   https://github.com/garnaat/missingcloud/blob/master/aws.json#L372
development: &default
  :access_key_id: ""
  :secret_access_key: ""
  :host: ""
test:
  <<: *default

使用方法

  • 初始化
example.rb
1
2
config = YAML::load(File.open("#{Rails.root}/config/aws.yml"))[Rails.env]
ec2 = AWS::EC2::Base.new(:access_key_id => config[:access_key_id], :secret_access_key => config[:secret_access_key], :server => config[:host])
  • 取得 instance 列表
exmaple.rb
1
2
instances = ec2.describe_instances
# instances["reservationSet"]["item"] 才會取得 array
  • 取得所有 snapshots (自己 create 的)
exmaple.rb
1
2
snapshots = ec2.describe_snapshots(:owner => "self")
# snapshots["snapshotSet"]["item"] 才會取得 array
  • 取得所有 volumes
exmaple.rb
1
2
volumes = ec2.describe_volumes
# volumes["volumeSet"]["item"] 才會取得 array
  • 建立 snapshot, 必須先取得 volume id
example.rb
1
2
volume_id = volumes["volumeSet"]["item"].first["volumeId"]
ec2.create_snapshot(:volume_id => volume_id, :description => "my snapshot")
  • 建立某個 instance 的 snapshot, 有 instance id 的情況下
example.rb
1
2
3
4
5
6
instance_id = "i-abcd"
volume_id = (((ec2.describe_volumes["volumeSet"] || {})["item"] || []).select { |volume|
  (volume["attachmentSet"]["item"].select{ |ins| ins["instanceId"] == instance_id }.first || {})["instanceId"] == instance_id
}.first || {})["volumeId"]
result = ec2.create_snapshot(:volume_id => volume_id, :description => "foo bar")
puts result["snapshotId"] # 新的 snapshot id

Comments