5
5

More than 5 years have passed since last update.

Capistrano3でAWS EC2インスタンスにタグ付けする

Posted at

やりたいこと

  • デプロイ完了後にEC2インスタンスにタグ付けしたい

困ったこと

こんなレシピ

まずはaws-sdkを読み込む

Capfile
require 'aws-sdk'

aws-sdkを使うために必要な通過儀礼。

production.rb
# AWSの接続用の情報
set :aws_access_key_id, "HOGEHOGE"
set :aws_secret_access_key, "fugafugafugafuga"
set :aws_region, "ap-northeast-1"

そしてレシピ

deploy.rb
  desc '指定したバージョンをVersionタグに設定する'
  task :finished do
    ec2 = AWS::EC2.new(
      access_key_id: fetch(:aws_access_key_id),
      secret_access_key: fetch(:aws_secret_access_key),
      region: fetch(:aws_region)
    ) 
    puts "set version tag #{fetch(:branch)}"
    on roles(:console) do
      instance_id = capture 'curl -s http://169.254.169.254/latest/meta-data/instance-id'
      ec2.instances[instance_id].add_tag('Version',:value=>fetch(:branch))
      # rollbackしたときにバージョン番号を戻す方法がTODO
    end
  end

ポイントは「AWSに用意されている謎のmetadata取得URLを叩いて自身のインスタンスIDを引っ張ってくる」です。

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