LoginSignup
19
19

More than 5 years have passed since last update.

BitbucketやGithubにPUSHしたらサーバー側で自動PULLするNode.jsでのミニマム構成

Last updated at Posted at 2014-12-17

BitbucketやGithubにPushしたときにサーバー側で自動pullさせたいときってよくあります。

けっこう処理複雑そうなイメージはありますが、 httpでPOSTを受け取ったらupdate()でコマンド実行って感じです。

注意: 全体的にノンセキュリティなやり方なのでこのままやる場合は気をつけましょう。

以下のソースコードをコピペ

サーバーに設置して実行しましょう。
3行目のcmdにコマンドを文字列で代入しておきます。 この場合/var/www/htmlに移動して git pull してますね。
Node.jsではexec()でコマンド実行出来るのでこれを利用しています。 ポートは3000です。

deploy.js
var exec = require('child_process').exec
var http = require('http');
var cmd = 'cd /var/www/html && git pull origin master'; //git>コマンド設定

/*コマンド実行関数*/
function update() {
    return exec(cmd, {timeout: 90000},
        function(error, stdout, stderr) {
            console.log('stdout: '+(stdout||'none'));
            console.log('stderr: '+(stderr||'none'));
            if(error !== null) {
                console.log('exec error: '+error);
            }
        }
    )
};

http.createServer(function (req, res) {
  if(req.method == 'POST'){
        update();
  }
}).listen(3000);

実行

通常起動

$ node deploy.js

or

デーモン化 (ex; pm2)

$ pm2 start deploy.js

ホスティング側設定

Bitbucketの場合

リポジトリのSetting -> フック -> POST -> ホックを追加
でURLにホスト名(or IPアドアレス):ポート名を設定します。

Githubの場合

リポジトリのSetting -> Webhooks & Services -> Webhooks -> Add webhook
でPayk¥load URLにホスト名(or IPアドアレス):ポート名を設定します。あとはデフォルトのままで大丈夫です。

注意: 全体的にノンセキュリティなのでこのままやる場合は気をつけましょう。

これだと全てのHOSTからでもpostされるので攻撃されちゃいます。また全てのpushが自動pullされるので注意してください。

まとめ

カンタンに試すくらいなイメージで使ってください。

19
19
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
19
19