Deployment via GIT on Cloudways

Posted on: December 7th, 2022
By: Tadeo Martinez

Add a file to a server that’s called “gitautodeploy.php” it needs to contain the code below. This code is adapted to have multiple hooks.

Here are the Cloudways instructions:

https://support.cloudways.com/en/articles/5124785-automatically-deploy-from-git-to-server-using-webhooks

The webhook to add is:

https://application_url/gitautodeploy.php?server_id=server_id&app_id=app_id&git_url=git_ssh_url&branch_name=branch_name&deploy_path=wp-content/

For the path, I usually leave it at wp-content/

When authenticating the GIT Remote Addess, remove the .git from the URL, otherwise you might get an error on the Cloudways dashboard. You can give it a try but it never works for me.

const API_KEY = "API_KEY";
const API_URL = "https://api.cloudways.com/api/v1";
const EMAIL = "ACCOUNT_EMAIL";

/* examples
const BranchName = "master";
const GitUrl = "git@bitbucket.org:user22/repo_name.git";
*/

//Use this function to contact CW API
function callCloudwaysAPI($method, $url, $accessToken, $post = [])
{
    $baseURL = API_URL;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_URL, $baseURL . $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //Set Authorization Header
    if ($accessToken) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $accessToken]);
    }
  
    //Set Post Parameters
    $encoded = '';
    if (count($post)) {
        foreach ($post as $name => $value) {
            $encoded .= urlencode($name) . '=' . urlencode($value) . '&';
        }
        $encoded = substr($encoded, 0, strlen($encoded) - 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
        curl_setopt($ch, CURLOPT_POST, 1);
    }
    $output = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($httpcode != '200') {
        die('An error occurred code: ' . $httpcode . ' output: ' . substr($output, 0, 10000));
    }
    curl_close($ch);
    return json_decode($output);
}

//Fetch Access Token
$tokenResponse = callCloudwaysAPI('POST', '/oauth/access_token', null
    , [
    'email' => EMAIL, 
    'api_key' => API_KEY
    ]);

$accessToken = $tokenResponse->access_token;
$gitPullResponse = callCloudWaysAPI('POST', '/git/pull', $accessToken, [
    'server_id' => $_GET['server_id'],
    'app_id' => $_GET['app_id'],
    'git_url' => $_GET['git_url'],
    'branch_name' => $_GET['branch_name'],
    /* Uncomment it if you want to use deploy path, Also add the new parameter in your link
    */	
    'deploy_path' => $_GET['deploy_path']  
    ]);

echo (json_encode($gitPullResponse));

Have any questions or comments? Write them below!


Leave a Reply

Your email address will not be published. Required fields are marked *