m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

Capistranoの調査

PHPカンファレンス2014でいろいろ知ったので

業務でも趣味でもwinSCPとかで地道にしているので手動でやるよりはある程度、更新処理を自動化してみたい。

環境

mac book airCapistranoを入れる)
vm(デプロイ先)

Capistrano設定

macにインストール
sudo gem install capistrano

macなのでsudoを使用しないとpermission関係でエラーになるかも

helpコマンド
$ cap --help
cap [-f rakefile] {options} targets...

Options are ...
        --backtrace=[OUT]            Enable full backtrace.  OUT can be stderr (default) or stdout.
        --comments                   Show commented tasks only
        --job-stats [LEVEL]          Display job statistics. LEVEL=history displays a complete job list
        --rules                      Trace the rules resolution.
        --suppress-backtrace PATTERN Suppress backtrace lines matching regexp PATTERN. Ignored if --trace is on.
    -A, --all                        Show all tasks, even uncommented ones (in combination with -T or -D)
    -B, --build-all                  Build all prerequisites, including those which are up-to-date.
    -D, --describe [PATTERN]         Describe the tasks (matching optional PATTERN), then exit.
    -e, --execute CODE               Execute some Ruby code and exit.
    -E, --execute-continue CODE      Execute some Ruby code, then continue with normal task processing.
    -f, --rakefile [FILENAME]        Use FILENAME as the rakefile to search for.
    -G, --no-system, --nosystem      Use standard project Rakefile search paths, ignore system wide rakefiles.
    -g, --system                     Using system wide (global) rakefiles (usually '~/.rake/*.rake').
    -I, --libdir LIBDIR              Include LIBDIR in the search path for required modules.
    -j, --jobs [NUMBER]              Specifies the maximum number of tasks to execute in parallel. (default is number of CPU cores + 4)
    -m, --multitask                  Treat all tasks as multitasks.
    -n, --dry-run                    Do a dry run without executing actions.
    -N, --no-search, --nosearch      Do not search parent directories for the Rakefile.
    -P, --prereqs                    Display the tasks and dependencies, then exit.
    -p, --execute-print CODE         Execute some Ruby code, print the result, then exit.
    -q, --quiet                      Do not log messages to standard output.
        --roles ROLES                Filter command to only apply to these roles (separate multiple roles with a comma)
    -r, --require MODULE             Require MODULE before executing rakefile.
    -R, --rakelibdir RAKELIBDIR,     Auto-import any .rake files in RAKELIBDIR. (default is 'rakelib')
        --rakelib
    -s, --silent                     Like --quiet, but also suppresses the 'in directory' announcement.
    -t, --trace=[OUT]                Turn on invoke/execute tracing, enable full backtrace. OUT can be stderr (default) or stdout.
    -T, --tasks [PATTERN]            Display the tasks (matching optional PATTERN) with descriptions, then exit.
    -v, --verbose                    Log message to standard output.
    -V, --version                    Display the program version.
    -W, --where [PATTERN]            Describe the tasks (matching optional PATTERN), then exit.
    -X, --no-deprecation-warnings    Disable the deprecation warnings.
    -z, --hosts HOSTS                Filter command to only apply to these hosts (separate multiple hosts with a comma)
    -h, -H, --help                   Display this help message.
$

vm設定

よしなに設定したものを用意
git clone https://github.com/mshige1979/vagrant-centos-dev-001.git -b cakephp3.x cap01
cd cap01/
vagrant up

初期設定

設定ファイルを生成
mkdir sample1
cd sample1/
cap install

※ディレクトリへ移動して、設定ファイルを生成

$ cap install
mkdir -p config/deploy
create config/deploy.rb
create config/deploy/staging.rb
create config/deploy/production.rb
mkdir -p lib/capistrano/tasks
Capified
$

簡単なコマンドを実行

config/deploy/staging.rb
# roleの設定
role :app, %w{192.168.33.10}
role :web, %w{192.168.33.10}
role :db,  %w{192.168.33.10}

# serverの設定
server '192.168.33.10', port: 22, user: 'vagrant', roles: %w{web app db}, ssh_options: {
  user: 'vagrant',
  keys: %w(~/.vagrant.d/insecure_private_key),
  auth_methods: %w(publickey)
}

vagrantからアクセスするので秘密鍵のパスを設定する

config/deploy.rbを以下とする
# config valid only for Capistrano 3.1
lock '3.2.1'

set :application, 'sample1'

task :list do
    on roles(:app), in: :sequence do
        execute "ls -la"
    end
end

コマンドで実行
$ cap staging list
INFO[066ae942] Running /usr/bin/env ls -la on 192.168.33.10
DEBUG[066ae942] Command: ls -la
DEBUG[066ae942] 	合計 28
DEBUG[066ae942] 	drwx------  3 vagrant vagrant 4096 10月 13 02:18 2014 .
DEBUG[066ae942] 	drwxr-xr-x. 4 root    root    4096  4月 27 10:05 2013 ..
DEBUG[066ae942] 	-rw-------  1 vagrant vagrant   52 10月 13 03:12 2014 .bash_history
DEBUG[066ae942] 	-rw-r--r--  1 vagrant vagrant   18  2月 21 21:09 2013 .bash_logout
DEBUG[066ae942] 	-rw-r--r--  1 vagrant vagrant  176  2月 21 21:09 2013 .bash_profile
DEBUG[066ae942] 	-rw-r--r--  1 vagrant vagrant  124  2月 21 21:09 2013 .bashrc
DEBUG[066ae942] 	drwx------  2 vagrant root    4096  4月 27 10:05 2013 .ssh
INFO[066ae942] Finished in 0.104 seconds with exit status 0 (successful).
$

※タスクを指定することで「cap config配下のファイル名 タスク名」で実行できる。
※deployや別かも


ファイル転送

ローカルにデータ準備
$ mkdir test1
$ echo "aaa" > test1/aaa.txt
$ echo "bbb" > test1/bbb.txt
$
config/deploy.rb
 config valid only for Capistrano 3.1
lock '3.2.1'

set :application, 'sample1'

task :list do
    on roles(:app), in: :sequence do
        execute "ls -la"
    end
end

task :upload1 do
    on roles(:app), in: :sequence do
        if test "[ ! -d /vagrant/sample1 ]"
            execute "mkdir -p /vagrant/sample1"
        end
        upload!("test1", "/vagrant/sample1/test1", :via => :sftp, :recursive => true)
    end
end
実行
$ cap staging upload1
DEBUG[cd7e9ac8] Running /usr/bin/env [ ! -d /vagrant/sample1 ] on 192.168.33.10
DEBUG[cd7e9ac8] Command: [ ! -d /vagrant/sample1 ]
DEBUG[cd7e9ac8] Finished in 0.099 seconds with exit status 1 (failed).
DEBUGUploading test1/aaa.txt 0.0%
INFOUploading test1/aaa.txt 100.0%
DEBUGUploading test1/bbb.txt 0.0%
INFOUploading test1/bbb.txt 100.0%
$

※なんかうまく動いている感じ


注意

$ cap staging deploy
INFO[c67d24fa] Running /usr/bin/env mkdir -p /tmp/sample1/ on 192.168.33.10
DEBUG[c67d24fa] Command: /usr/bin/env mkdir -p /tmp/sample1/
INFO[c67d24fa] Finished in 0.115 seconds with exit status 0 (successful).
DEBUGUploading /tmp/sample1/git-ssh.sh 0.0%
INFOUploading /tmp/sample1/git-ssh.sh 100.0%
INFO[895b5f53] Running /usr/bin/env chmod +x /tmp/sample1/git-ssh.sh on 192.168.33.10
DEBUG[895b5f53] Command: /usr/bin/env chmod +x /tmp/sample1/git-ssh.sh
INFO[895b5f53] Finished in 0.011 seconds with exit status 0 (successful).
DEBUG[44846c50] Running /usr/bin/env git ls-remote -h  on 192.168.33.10
DEBUG[44846c50] Command: ( GIT_ASKPASS=/bin/echo GIT_SSH=/tmp/sample1/git-ssh.sh /usr/bin/env git ls-remote -h  )
DEBUG[44846c50] 	usage: git ls-remote [--heads] [--tags]  [-u <exec> | --upload-pack <exec>]
DEBUG[44846c50] 	                     [-q|--quiet] [--exit-code] [--get-url] [<repository> [<refs>...]]
DEBUG[44846c50] Finished in 0.012 seconds with exit status 129 (failed).
cap aborted!

※deployの場合はgitなどのリポジトリパスが必須かもしれない



所感

簡単そうな感じに見えたけど、最初のとっかかりで結構つまづきがち、
最初なんかのデプロイをやってみないと使えるかはまだわからない。
今までの手動設定より楽できるかが重要。
なんか学習コストが高そうな感じがする…

参考


Capistrano3を最後にもう一度だけ懇切丁寧にまとめてみる - そのねこが学ぶとき


Capistrano3 をファイル転送のためだけに使ってみる - zonote


Capistranoについて調べてみたこと - Qiita

書籍

CakePHPで学ぶ継続的インテグレーション

CakePHPで学ぶ継続的インテグレーション