How to Automate Git Deployment using Webhooks on CloudwaysDecember 14, 2016

 

Git auto-deployment allows a user to get updated code deployed on their live servers as soon as the changes in the remote repositories occur. You can achieve this using Cloudways API, but it’s necessary that git repository supports git over SSH.

Before you start, learn the manual deployment of your repository using git. This will allow you to exchange SSH keys between Cloudways server and your git repo. You can continue once you have setup your SSH connection in your repository.

Step 1: Generate API Key

Log in to the Cloudways Platform,  and generate your API key using this link. Copy the Key and Email as it will be required as a part of the script in the next step.

Generate API Key

Step 2: Create Auto-deployment File

You can either use an existing application or launch a new Application on your Cloudways Server. Inside your applications public_html folder, create a file and name it gitautodeploy.php. This file will enable the auto-deployment of the code on the given server and application of your Cloudways Account. Copy and paste the code below into the file:

Step 3: Add a Webhook in your Git Repository

A simple webhook will be required, which will trigger the request to the app we created above and will auto-deploy the code.

To generate a webhook, copy your application URL and append these arguments at the end:

    1. filename = (auto-deployment file name)
    2. server_id = ( your server id on which you need to deploy the code)
    3. app_id = ( your app id where you need to deploy the code )
    4. git_url = ( it should be something like git@bitbucket.org:username122/phptest.git)
    5. branch_name = ( branch name in your repo eg. master )
    6. deploy_path = ( leaving it empty will deploy code at public_html, optional parameter)

Webhook URL Example:

http://phpstack-1111-12345-678910.cloudwaysapps.com/gitautodeploy.php?server_id=12345&app_id=678910&git_url=git@bitbucket.org:username123/phptest.git&branch_name=master.

To add a Webhook on Bitbucket:

  1. Get into your Bitbucket repo and click Settings
  2. Now under WORKFLOW, select Webhooks and Click on Add Webhook
  3. Name your webhook and add the webhook URL to your app, then Click Save.

Bitbucket Add Webhook

You can add a webhook in your Github account by:

  1. Get into your Github repo and click Settings
  2. Now click Webhooks and Click on Add Webhook
  3. Name your webhook and add the webhook URL to your app, then Click Save.

Github Add Webhook

You can test your webhook while making a small change to your repository which will automatically trigger your application, to generate a pull request using Cloudways API. For complete documentation of the API, visit our playground.

Leave a Reply

Still need help? Our support team is waiting to help you. Ask them now