Skip to content

Instantly share code, notes, and snippets.

@CyanoFresh
Last active April 23, 2022 19:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CyanoFresh/eb5cf2ab05b1805e185ee0ad6503709b to your computer and use it in GitHub Desktop.
Save CyanoFresh/eb5cf2ab05b1805e185ee0ad6503709b to your computer and use it in GitHub Desktop.
Auto pull for Yii2
<?php
namespace app\controllers;
use Yii;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
/**
* Class WebhookController
*
* Runs git pull & composer install & yii migrate after push on main repo.
*
* @package app\controllers
* @author CyanoFresh <cyanofresh@gmail.com>
*/
class WebhookController extends Controller
{
/**
* @inheritdoc
*/
public $enableCsrfValidation = false;
/**
* @var string Secret field on GitHub
*/
public $secret = '917a34072663f9c8beea3b45e8f129c5';
/**
* @var array of commands to be executed
*/
public $commands = [
'cd .. && /usr/bin/git pull 2>&1',
'/usr/bin/php ../yii migrate --interactive=0 2>&1',
];
public function actionIndex()
{
$requestSignature = Yii::$app->request->headers->get('x-hub-signature');
$hash = hash_hmac('sha1', Yii::$app->request->rawBody, $this->secret);
$actualSignature = 'sha1=' . $hash;
if ($requestSignature !== $actualSignature) {
throw new BadRequestHttpException('Wrong signature');
}
foreach ($this->commands as $command) {
echo 'Executing "' . $command . "\":\n\n";
echo shell_exec($command);
echo "\n\n";
}
}
}
  1. Generate ssh keys for www-data:
sudo mkdir /var/www/.ssh
sudo chown -R www-data /var/www/.ssh
sudo -u www-data ssh-keygen -t rsa
  1. Add that ssh key to the Deploy keys for your account or repo
  2. Put this WebhookController into your app and fill the secret with random data
  3. Create Webhook, put secret from controller into the Secret field. URL has to be like this:
site.com/webhook
  1. Add access to your repo for www-data user:
chown -R www-data /var/www/yourrepo/

All done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment