Skip to content

Instantly share code, notes, and snippets.

@ddonovan
Created June 26, 2014 15:07
Show Gist options
  • Save ddonovan/3e81e686885317955e78 to your computer and use it in GitHub Desktop.
Save ddonovan/3e81e686885317955e78 to your computer and use it in GitHub Desktop.
Laravel / Github Webhooks

Notes about how I used this.

  1. Needed run ssh-keygen as www-data user to create the .ssh keys used by github.
  2. Created a var/www/.ssh folder to place ssh key in, as well as allow Recognized hosts file creation.
  3. Manually used git clone as user www-data to pull master branch down, and answered any prompts.

Once I did things as user www-data instead of ubuntu doing a git deploy worked like a charm.

Thanks to these two links..

http://jondavidjohn.com/git-pull-from-a-php-script-not-so-simple/

http://www.thisprogrammingthing.com/2013/automatically-updating-your-website-using-githubs-service-hooks/

Event::listen('github.webhook', function($payload)
{
Log::info('Github Webhook Push Event fired');
Log::info('Deploying new code because of a commit push by ' . $payload->head_commit->author->name);
Log::info('Deploying commit ID : ' . $payload->after);
// really only need to use this if you have ngrok running and testing the webhook code.
if (App::environment('local'))
{
Log::info('Skipping github webhook on local machine');
Log::info(shell_exec('ls -la'));
return;
}
Log::info('Performing git pull');
Log::info(shell_exec('cd /var/www/{project folder} && /usr/bin/git pull 2>&1'));
});
Route::post('/github/webhook', function(){
try{
$xEvent = Request::header('X-GitHub-Event');
$payload = json_decode(Request::getContent());
}
catch(Exception $e){
Log::info('Error Handling Webhook content');
return;
}
# Check if it's a push event, just in case we register for all events.
if($xEvent !='push'){
Log::info('Ignoring X-GitHub-Event' .$xEvent );
return Response::json(['message'=>'ignored non push event'], 200);
}
# Check if it's a push to the master branch.
if($payload->ref !='refs/heads/master'){
Log::info('Ignoring push on branch' .$payload->ref);
return Response::json(['message'=>'ignored push to branch :' .$payload->ref ], 200);
}
# Firte our webhook event handler.
$event = Event::fire('github.webhook', [$payload]);
return Response::json(['message'=>'processing push event deploying updates, thanks'], 200);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment