LoginSignup
13
16

More than 5 years have passed since last update.

【メモ】Githubのwebhookを使った自動git pull

Posted at

背景

ローカルでプログラミングをしているとソースコードをGithubで管理し、外部のサーバでレポジトリをクローンし
開発しているウェブサイトなどをデプロイすることをよく行います。
ローカルでプログラミングしているとよく思うのが、外部のサーバのレポジトリを最新の状態に保ちたいということがよくあります。

なので、ローカルでプログラミングを行い、それをGithubにpushすると、Githubのwebhook機能で、
外部のサーバでgit pullを行うという、自動デプロイ的なことを行います。
(何番煎じかわかりませんが、よくやるので個人的にメモしておく)

外部サーバでの設定

レポジトリをクローン

最新の状態に保ちたいレポジトリをGithubからクローンしてくる。

ハマりポイント
クローンしたレポジトリの所有者をapacheにしておく。(httpdのとき)
webhookからgit pullするプログラムが実行されるので、そのままだとPermission deniedされる
設定例)
# chown apache:apache -R <target_repo>

外部サーバにgit pullするスクリプトを用意

webhook.php
<?php

// 設定
$LOG_FILE = dirname(__FILE__).'/hook.log';
$SECRET_KEY = 'hoge'; //githubで設定するsecretもところ

$header = getallheaders();
$hmac = hash_hmac('sha1', $HTTP_RAW_POST_DATA, $SECRET_KEY);
if ( isset($header['X-Hub-Signature']) && $header['X-Hub-Signature'] === 'sha1='.$hmac ) {
    $payload = json_decode($HTTP_RAW_POST_DATA, true);  // 受け取ったJSONデータ
    // ここに実行したいコードを書く(testレポに移動して、git pullする)
    exec('cd test ; git pull');
    file_put_contents($LOG_FILE, date("[Y-m-d H:i:s]")." ".$_SERVER['REMOTE_ADDR']." git pulled: ".$payload['after']." ".$payload['commits'][0]['message']."\n", FILE_APPEND|LOCK_EX);
} else {
    // 認証失敗
    file_put_contents($LOG_FILE, date("[Y-m-d H:i:s]")." invalid access: ".$_SERVER['REMOTE_ADDR']."\n", FILE_APPEND|LOCK_EX);
}

Githubの設定

対象のレポジトリにて
Settings

webhooks

設定

payload URL
http://hoge/webhook.php

※外部サーバの先程用意したgit pullをたたくようにプログラムを指定
※今回の場合webhook.php

Content type
application/json

※どっちでもok

Secret
今回の場合は`hoge`

Which events would you like to trigger this webhook?
 Just the push event. ←これ
 Send me everything.
 Let me select individual events.
 Active
We will deliver event details when this hook is triggered.

※webhook機能実行の条件を指定する。今回、pushされたら実行してほしいので一番上

動作確認

実際にpushを行い、動作を確認する
うまくいない場合はwebサーバのerror.logをみるとよい。

13
16
1

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
13
16