6
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CapistranoのdeployタスクをVagrantマシンに適用して開発する

Last updated at Posted at 2015-05-13

やりたいこと: capistrano のタスクを vagrant マシンに適用して開発したい。vagrant へのログイン情報を capistrano から取得したい

事前準備

vagrant 内で git clone などすると思うので、ssh agent forward の設定をしておく

Vagrantfile
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
+  config.ssh.forward_agent = true
end

Mac の keychain に鍵を登録しておく. keychain に入れておくと毎回 ssh-add しなくてすむ。-K オプションを使う。

$ ssh-add -K .ssh/id_rsa

やりかた

vagrant ssh-config で諸々情報が取れる

$ vagrant ssh-config
Host vagrant-centos
  HostName 127.0.0.1
  User vagrant
  Port 2200
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile /Users/seo.naotoshi/.vagrant/machines/vagrant-centos/virtualbox/private_key
  IdentitiesOnly yes
  LogLevel FATAL
  ForwardAgent yes

なので、これを capistrano の変数に設定するメソッドをちょろっと書いて利用する

config/deploy.rb
set :application, 'oreno'
set :repo_url, 'git@github.com:sonots/oreno.git'
set :deploy_to, '/var/app/oreno'

def set_vagrant_user
  ssh_config = {}
  Bundler.with_clean_env do
    out = `vagrant ssh-config`
    out.split("\n").each do |line|
      line.strip!
      key, value = line.split(" ", 2)
      value.slice!(0) if value.start_with?('"')
      value.slice!(-1) if value.end_with?('"')
      ssh_config[key] = value
    end
  end

  set :user, ssh_config["User"]
  set :ssh_options,
    user: ssh_config["User"],
    port: ssh_config["Port"],
    keys: [ssh_config["IdentityFile"]],
    forward_agent: ssh_config["ForwardAgent"] == "yes" ? true : false
end
config/deploy/development.rb
set_vagrant_user

roles :app, ['127.0.0.1']

これで、

$ cap development deploy

で vagrant にログインしてデプロイできる。

ToDo

めっちゃ小さいメソッドだけど gem にしてもいいのかもね。

6
9
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
6
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?