LoginSignup
3
2

More than 5 years have passed since last update.

capistranoからitamaeを実行する「capistrano-itamae」

Posted at

capistrano-itamaeとは?

capistranoに登録してるhostに対してitamae sshするためのgemです

使い方とか

基本的な使い方は以前Qiitaに書いたのでそっちを参照

capistrano-itamaeというgemを作った - Qiita を参照

最近使ってる設定

capistrano-itamaeを3〜4つくらいのアプリに入れてみて自分の中のテンプレができたので書いておきます

lib/capistrano/tasks/itamae.rake

lib/capistrano/tasks/itamae.rake
require "yaml"

ROLES = %i(web db).freeze

namespace :itamae do
  ROLES.each do |role|
    namespace role do
      # nodes.ymlから特定のstageだけ取り出してtmp/stage.ymlに書き出す
      # (nodes.ymlにstageがなければdefaultを採用する)
      task :setup_stage_node do
        stage = fetch(:stage)
        data = YAML.load_file("cookbooks/nodes.yml")
        node = data[stage.to_s] || data["default"]
        File.open("tmp/#{stage}.yml", "wb") do |f|
          YAML.dump(node, f)
        end
      end

      desc "Run itamae to #{role}"
      task :apply => :setup_stage_node do
        on roles(role) do
          itamae_ssh "#{role}.rb", "--node-yaml=tmp/#{fetch(:stage)}.yml"
        end
      end

      desc "Run itamae to #{role} (dry run)"
      task :dry_run => :setup_stage_node do
        on roles(role) do
          itamae_ssh "#{role}.rb", "--node-yaml=tmp/#{fetch(:stage)}.yml --dry-run"
        end
      end
    end
  end

  namespace :all do
    desc "Run itamae to all roles"
    task :apply => ROLES.map { |role| "itamae:#{role}:apply" } do
    end

    desc "Run itamae to all roles (dry run)"
    task :dry_run => ROLES.map { |role| "itamae:#{role}:dry_run" } do
    end
  end
end

taskを動的生成しているので分かりづらいですが、 cap -T するとこんな感じです。

$ bundle exec cap -T | grep itamae
cap itamae:all:apply                                 # Run itamae to all roles
cap itamae:all:dry_run                               # Run itamae to all roles (dry run)
cap itamae:db:apply                                  # Run itamae to db
cap itamae:db:dry_run                                # Run itamae to db (dry run)
cap itamae:web:apply                                 # Run itamae to web
cap itamae:web:dry_run                               # Run itamae to web (dry run)

webロール、dbロールへのそれぞれのdry_runとapply(本実行)、ロールの個別指定を省略した全ロールへのdry_runとapplyが生成されます。

cookbooks/nodes.yml

cookbooks/nodes.yml
default: &default

staging:
  <<: *default
  db_name: "hoge_staging"

production:
  <<: *default
  db_name: "hoge_production"

stage毎に値を変えたいということがあったので 1、Railsのdatabase.ymlみたいな形式にして実行時のstageの値でymlを出力して、itamae ssh に渡すようにしています

itamae実行時のエンドポイント

この中で include_recipe 書いたりしています。

cookbooks/web.rb
# webロールで実行したいレシピ
cookbooks/db.rb
# dbロールで実行したいレシピ

  1. データベース名とか 

3
2
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
3
2