Deploying Automatically with Github WebHooks

May 7, 2013

I recently had to set up a super simple auto-deploy routine for a dev team working on a responsive website for a large U.S. publisher. Since we are using Github to host our code repo, it was pretty easy to set up. Everyone has been digging the workflow so I thought I'd share the details here.

The Basics

  1. Set up a web page on your dev server that is accessible at a public URL and has read/write permission to the dev directory on the dev server. See below for a stupidly simple example using PHP.
  2. On github.com, navigate to the WebHook URL settings for your repo:

    YOUR_REPO > Settings > Service Hooks > WebHook URLs

    Enter the URL to the page you created in step 1. When you push to Github, Github will send a POST request with a bunch of info about the push to the URL you provided.

    NOTE: Only the repo owner has access to the settings area.

Tricky Bits

  • The web page needs to have permission to read/write to the dev directory on the dev server. It can be tough to do this is a way that is secure.
  • If the repo on github is private, you have to monkey around to grant the dev server access to the repo on github.
  • Debugging sucks. If the WebHook isn't working, it's pretty hard to figure out why.

Related Links

PHP Example

<?php

// Init vars
$LOCAL_ROOT         = "/var/www/my_new_site";
$LOCAL_REPO_NAME    = "public_html";
$LOCAL_REPO         = "{$LOCAL_ROOT}/{$LOCAL_REPO_NAME}";
$REMOTE_REPO        = "git@github.com:jonathanstark/my_new_site.git";
$DESIRED_BRANCH     = "dev";

// Delete local repo if it exists
if (file_exists($LOCAL_REPO)) {
    shell_exec("rm -rf {$LOCAL_REPO}");
}

// Clone fresh repo from github using desired local repo name and checkout the desired branch
echo shell_exec("cd {$LOCAL_ROOT} && git clone {$REMOTE_REPO} {$LOCAL_REPO_NAME} && cd {$LOCAL_REPO} && git checkout {$BRANCH}");

die("done " . mktime());