Skip to content

Instantly share code, notes, and snippets.

@bisko
Last active August 29, 2015 14:25
Show Gist options
  • Save bisko/70e5b49098dc6b57149d to your computer and use it in GitHub Desktop.
Save bisko/70e5b49098dc6b57149d to your computer and use it in GitHub Desktop.
A bitbucket deploy webhook, that respects ssh keys for a user without shell on the server.
<?php
/**
* Got the code and idea from http://jonathannicol.com/blog/2013/11/19/automated-git-deployments-from-bitbucket/
*
* Had to change the way the keys are loaded, as the www-data user on my host didn't have shell
*/
// where is the git repo located
$repo_dir = '/home/<user>/<repo>.git';
// where the clean code will go
$web_root_dir = '/home/<webserver>/<domain>/';
// what is the branch that the code will be released from
$release_branch = 'master';
// Full path to git binary is required if git is not in your PHP user's path. Otherwise just use 'git'.
$git_bin_path = '/usr/bin/git';
/**
* End of config, actual black magic below
*/
$update = false;
// Parse data from Bitbucket hook payload
$payload = json_decode($_POST['payload']);
if (empty($payload->commits)){
// When merging and pushing to bitbucket, the commits array will be empty.
// In this case there is no way to know what branch was pushed to, so we will do an update.
$update = true;
} else {
foreach ($payload->commits as $commit) {
$branch = $commit->branch;
if ($branch === $release_branch || isset($commit->branches) && in_array($release_branch, $commit->branches)) {
$update = true;
break;
}
}
}
if ($update) {
// We are going to checkout to the web root
/**
* Start ssh-agent and add the ssh keys
*
* This is the shell template that will be used below,
* when calling the commands with the appropriate parameters
*
*/
$baseCmd = "ssh-agent bash -c 'ssh-add; ssh-add -l; {{CMD}}'";
$fetch = str_replace('{{CMD}}', 'cd ' . $repo_dir . '; ' . $git_bin_path . ' fetch', $baseCmd);
$out = shell_exec($fetch);
$co = str_replace('{{CMD}}','cd ' . $repo_dir . ' ; GIT_WORK_TREE=' . $web_root_dir . ' ' . $git_bin_path . ' checkout -f', $baseCmd);
$out = shell_exec($co);
// Log the deployment
$commit_hash = shell_exec('cd ' . $repo_dir . ' && ' . $git_bin_path . ' rev-parse --short HEAD');
file_put_contents(dirname(__FILE__).'/deploy.log', date('m/d/Y h:i:s a') . " Deployed branch: " . $branch . " Commit: " . $commit_hash . "\n", FILE_APPEND);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment