ようへいの日々精進XP

よかろうもん

初老丸のきゃぴきゃぴ Capistrano3 メモ(EC2 Name タグで操作対象を絞り込んでコマンド操作してみる)

きゃぴきゃぴ

してますか。

Capistrano はバージョン 2 の時代に少し触ったことがあったんですが、改めて Capistrano 3 を用いて EC2 Name タグで操作対象を絞り込んでコマンド操作してみたいと思います。

参考

メモ

やりたいこと

  • EC2 タグ名から IP アドレスを取得してきて、何らかのコマンドを流し込む

準備

bash-3.2$ cat Gemfile
# A sample Gemfile
source "https://rubygems.org"

# gem "rails"

gem 'capistrano'
gem 'aws-sdk'

bundle install しましょう。

bundle install --path vendor/bundle

ファイル達

bash-3.2$ tree -L 3
.
├── Capfile
├── Gemfile
├── Gemfile.lock
├── config
│   ├── deploy
│   │   ├── dev.rb
│   │   ├── production.rb
│   │   └── staging.rb
│   └── deploy.rb
├── lib
│   └── capistrano
│       └── tasks
├── log
│   └── capistrano.log
└── vendor
    └── bundle
        └── ruby

config/deploy.rb

グローバルな設定は config/deploy.rb に書きましょう。

require 'aws-sdk'

set :aws_region, 'ap-northeast-1'
set :aws_profile, 'your_profile'

def ec2
  Aws::EC2::Client.new(
    region: fetch(:aws_region),
    profile: fetch(:aws_profile)
  )
end

def get_ec2_instances(name)
  hosts = []
  ec2.describe_instances(
    filters:[
      { name: "tag:Name", values: [name]},
      { name: "instance-state-name", values: ["running"]}
    ]).reservations.each do |reservation|
    reservation.instances.each do |instance|
      hosts << instance.public_ip_address
    end
  end
  return hosts
end

# run_locally で echo "demo" を実行する
# :app Role を対象として pwd と uptime を実行する
namespace :demo do
  desc 'uptime を実行'
  task :uptime do
    run_locally do
      execute 'echo "demo"'
    end
    on roles(:app) do
      execute 'pwd'
      execute 'uptime'
    end
  end
end

set :foo で定義した値は fetch :foo で取得出来る。

config/deploy/dev.rb

環境毎の設定は config/deploy/*.rb に記載しましょう。

# インスタンス Name タグに dev- が含まれているインスタンスの Public IP を取得する
hosts = get_ec2_instances('dev-*')
role :app, hosts

set :ssh_options, {
  user: %w(user),
  keys: %w(/Path/to/key.pem)
}

実行

  • タスクを確認
bash-3.2$ bundle exec cap dev -T | grep demo
cap demo:uptime                    # uptime を実行
  • タスクを実行
bash-3.2$ bundle exec cap dev demo:uptime
00:00 demo:uptime
      01 echo "demo"
      01 demo
    ✔ 01 kawahara@localhost 0.013s
      02 pwd
      02 /home/ssh_user
    ✔ 02 ssh_user@xx.xxx.xx.xx1 0.736s
      03 uptime
      02 /home/ssh_user
    ✔ 02 ssh_user@xx.xxx.xx.xx2 0.775s
      03  14:54:24 up 27 min,  0 users,  load average: 0.00, 0.00, 0.00
    ✔ 03 ssh_user@xx.xxx.xx.xx1 0.612s
      03  14:54:24 up 27 min,  0 users,  load average: 0.00, 0.01, 0.04
    ✔ 03 ssh_user@xx.xxx.xx.xx2 0.688s

以上

メモでした。