This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Join our live AMA on the Future of Page Builders with Brizy's CEO! Register Now →

How to Clone Github Repository Using Cloudways API

Updated on December 9, 2021

8 Min Read
github-repository-cloudways-api

Cloudways API has been released to all developers and re-sellers, with some excellent third-party solutions. In order to educate the developers, I have written several tutorials that highlight how to purge Varnish using the API and carry out API based CRUD operations for servers and applications.

In this article, I am going to explain how you can clone your GitHub application from your Git repository to the Cloudways application. The process has the following five steps that systematically cover all aspects of  cloning the GitHub app onto the Cloudways platform.

Create Server and Application on Cloudways

The first step is to launch the server and then the application on Cloudways platform. To illustrate the process, I have created the following GIF.

DO installation

Simply follow the steps in the GIF and the server and the application is ready for the next step.

Get the API Secret Key

This is an important step for the process. API key is an important of the cloning process. The API key could be found in the application tab after the signing into the platform.

cloudways-api

Get the SSH Key and Deploy in GitHub

Getting the SSH requires a bit of code.

First I will make a class to connect with Cloudways API using authenticated access token and then pass email, and the API key to prepare access token. The function `prepareacesstoken()` will then send the request to Cloudways API for access token. Once received, it will be saved in  $accesstoken.

I have used Guzzle for making HTTP requests. If you  have not installed Guzzle, you should refer  How to create and delete applications via cloudways api . Now create a file CloudwaysAPI.class.php and copy-paste the class code from the above mentioned tutorial. I will next extend this class with new methods.

get_servers() > to get your launched server,

get_applications() > for launched applications,

GenerateKey() > for SSH key generation,

GetKey() > for fetching key,

Since you have copied the class from above article, add the following methods to `CloudwaysAPIClient` class.

 Public function get_servers()
        {
            try
            {
                $url = self::API_URL . "/server";
                $option = array('exceptions' => false);
                $header = array('Authorization'=>'Bearer ' . $this->accessToken);
                $response = $this->client->get($url, array('headers' => $header));
                $result = json_decode($response->getBody()->getContents());
                return $result;
            }
            catch (RequestException $e)
            {
                $response = $this->StatusCodeHandling($e);
                return $response;
            }
        }

Public function get_applications()
        {
            try
            {
                $url = self::API_URL . "/apps";
                $header = array('Authorization'=>'Bearer ' . $this->accessToken);
                $response = $this->client->get($url, array('headers' => $header));
                return json_decode($response->getBody()->getContents());
            }

            catch (RequestException $e)
            {
                $response = $this->StatusCodeHandling($e);
                return $response;
            }

        }

Public function GenerateKey($serverid,$applicationid)
        {
            try
            {
                $url = self::API_URL . "/git/generateKey";
                $data = [
                    'server_id' => $serverid,
                    'app_id' => $applicationid               
                ];
                $header = array('Authorization'=>'Bearer ' . $this->accessToken);
                $response = $this->client->post($url, array('query' => $data,'headers' => $header));
                
                $key = $this->GetKey($serverid,$applicationid);
                return $key;          
            }
            catch (RequestException $e)
            {              
                $response = $this->StatusCodeHandling($e);               
                return $response;
            }
        }

 Public function GetKey($serverid,$applicationid)
        {
            try
            {
                $url = self::API_URL . "/git/key";
                $data = [
                    'server_id' => $serverid,
                    'app_id' => $applicationid               
                ];
                $header = array('Authorization'=>'Bearer ' . $this->accessToken);
                $response = $this->client->get($url, array('query' => $data,'headers' => $header));
                return json_decode($response->getBody()->getContents());
              }

            catch (RequestException $e)
            {
                $response = $this->StatusCodeHandling($e);
                return $response;
            }

        }

Notice that I have passed two parameters in `GenerateKey()` and `GetKey()` methods. These two parameters,server ID and application ID are required to create the SSH key.

Now create a file gkey.php and add the following PHP code to it.

<?php
    include 'CloudwaysAPI.class.php';
    $api_key = 'W9bqKca9ndi5myJqxI7afJrmbjEfY0';
    $email = '[email protected]';
    $cw_api = new CloudwaysAPI($email,$api_key);
    $servers = $cw_api->get_servers();
    $apps = [];
    $success = null;
    
    if(!empty($_POST)){
        $server = $_POST['server'];
        $appname = $_POST['app'];
        $re = $cw_api->GenerateKey($server,$appname);
              
        if(isset($re->key)){
            $success = $re->key;
        } else {
            $success = $re->message;
        }

    }

?>

I included the parent class file and then passed the API key and email address. These are required for the access tokens. After that, I fetched the server’s list, which will be shown in the select box.

I will now create a simple form to show servers and applications. I will use bootstrap for UI design so the bootstrap CDN should be added to the file. Now in the body tag, add the following code.

<div class="container-fluid">
    <div class="row">
      <div class="col-md-10">
        <form class="form-horizontal" method="post" action="">
          <fieldset>     
            <legend>Get Application Key</legend>    
            <div class="form-group">
              <label class="col-md-4 control-label" for="server">Server</label>
              <div class="col-md-4">
                <select id="server" name="server" class="form-control">
                  <option value="">Select Your Server</option>
                  <?php foreach($servers->servers as $server) { echo "
                  <option value='".$server->id."'>".$server->label."</option>"; } ?>
                </select>
              </div>
            </div>
      
            <div class="form-group">
              <label class="col-md-4 control-label" for="application">Application</label>
              <div class="col-md-4">
               <select id="app" name="app" class="form-control disable">
                </select>
              </div>
            </div>
       
            <div class="form-group">
              <label class="col-md-4 control-label" for=""></label>
              <div class="col-md-4">
                <button id="" name="" class="btn btn-danger">Get Key</button>
              </div>
            </div>
            
            <!-- Textarea -->
            <div class="form-group">
              <label class="col-md-4 control-label" for="textarea">Text Area</label>
              <div class="col-md-4">                     
                 <textarea class="form-control" id="textarea" name="textarea" rows="15" cols="50"><?php echo $success; ?></textarea>
              </div>
           </div>

          </fieldset>
        </form>
      </div>
    </div>
  </div>

This code will generate a basic form with servers’ name in the server select box. By using the foreach loop, I populated the server select box. Now, every time you select a server name, it will automatically fetch the applications of that server. To achieve this, add the following script before closing the body tag.

 <script type="text/javascript">
    $("#server").change(function() {
        val = $(this).val();
        switch (val) {
            <?php foreach($servers -> servers as $server) { ?>
            case <?php echo "\"".$server -> id.
        "\""; ?>:
                $('#app')
                    .find('option')
                    .remove()
                    .end();
                <?php 
          $i = "<option value=''>Select Your Application</option>";
          foreach($server -> apps as $app) {
              $i .= "<option value='".$app -> id.
              "'>".$app -> label.
              " (".$app -> application.
              ")</option>";
              $i++;
            } ?>
                apps = "<?php echo $i;?>";
                $('#app').html(apps);
                break;
                <?php
        } ?>
            default:
                $('#app')
                    .find('option')
                    .remove()
                    .end();
                break;
        }
    });
</script>

This concludes the process of getting the SSH key using Cloudways API. When the form is submitted, the POST variables catch the values and pass them over to `GenerateKey()` method as arguments. The response will be returned, collected in the variable $success and will be shown in the textarea.

image03

Copy the SSH key and deploy it in your GitHub repository. I have created a repo with demo code. See the following screenshot for adding the key to the repository.

image00

Once successful, the Cloudways SSH key has been deployed to the GitHub repo. This also finishes the main part of the application.

Get branches of GitHub Repository

After deploying the key,  the next step is fetching GitHub branches in the application that needs to be cloned. At this point, I will add the `GetBranches()` method in CloudwaysAPI.class.php

 public function GetBranches($serverid,$applicationid,$git_url)
        {
            try
            {
                $url = self::API_URL . "/git/branchNames";
                $data = [
                    'server_id' => $serverid,
                    'app_id' => $applicationid,
                    'git_url' => $git_url             
                ];
                $header = array('Authorization'=>'Bearer ' . $this->accessToken);
                $response = $this->client->get($url, array('query' => $data,'headers' => $header));
                return json_decode($response->getBody()->getContents());     
            }
            catch (RequestException $e)
            {             
                $response = $this->StatusCodeHandling($e);                
                return $response;
            }

        }

Now create another file cloneapp.php. Next, I will create a form in the bootstrap Modal that will be shown upon page load. In the form, select the server and the application and input your GitHub SSH URL. To fetch the branches, I will pass three arguments, the Server ID, Application ID and the Git URL. Add the following code. To the file’

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Enter Git SSH URL</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" method="post">
                    <fieldset>

                        <!-- Text input-->
                        <div class="form-group">
                            <label class="col-md-4 control-label" for="server">Server</label>
                            <div class="col-md-4">
                                <select id="git_server" name="git_server" class="form-control" required>
                                    <option value="">Select Your Server</option>
                                    <?php foreach($servers->servers as $server) { echo "
                   <option value='".$server->id."'>".$server->label."</option>"; } ?>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-md-4 control-label" for="application">Application</label>
                            <div class="col-md-4">
                                <select id="git_app" name="git_app" class="form-control disable" required>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-md-4 control-label" for="textinput">Enter Git SSH URL</label>
                            <div class="col-md-4">
                                <input id="git_url" name="git_url" type="text" placeholder="placeholder" class="form-control input-md" required>
                            </div>
                        </div>

                        <!-- Button -->
                        <div class="form-group">
                            <label class="col-md-4 control-label" for="singlebutton">Get Git</label>
                            <div class="col-md-4">
                                <button id="submit" name="submit" class="btn btn-primary">fetch branches</button>
                            </div>
                        </div>

                    </fieldset>
                </form>
            </div>
        </div>
    </div>
</div>

To show the applications available on a specific server, add the following JavaScript code.

<script type="text/javascript">
    $("#git_server").change(function() {
        val = $(this).val();
        switch (val) {
            <?php foreach($servers -> servers as $server) { ?>
            case <?php echo "\"".$server -> id.
        "\""; ?>:
                $('#git_app')
                    .find('option')
                    .remove()
                    .end();
                <?php 
          $i = "<option value=''>Select Your Application</option>";
          foreach($server -> apps as $app) {
              $i .= "<option value='".$app -> id.
              "'>".$app -> label.
              " (".$app -> application.
              ")</option>";
              $i++;
            } ?>
                apps = "<?php echo $i;?>";
                $('#git_app').html(apps);
                break;
                <?php
        } ?>
            default:
                $('#git_app')
                    .find('option')
                    .remove()
                    .end();
                break;
        }
    });
</script>

The Submit button sends the arguments to `GetBranches()` method and fetch branches from Github repo. You must also add the SSH URL of your GitHub repo. To send the response, add the following PHP code.

if(isset($_POST['submit'])){
 
        $server = $_POST['git_server'];
        $appname = $_POST['git_app'];
        $giturl = $_POST['git_url'];
        $re = $cw_api->GetBranches($server,$appname,$giturl);
 
        foreach($re->branches as $branch){        
        $options.="<option value='".$branch."'>".$branch."</option>";
        }      

}

Finally, $options has the branches from the GitHub repository.

image01

Read more: Enhanced Cloudways Staging Environment Is Now Available for All Users

Clone Application in the Cloudways App

The final step is the actual cloning of the GitHub application. Add the last method, GetClone().  This method will need five parameters: server ID, application ID, git url, git branch and the deploy path.

 Public function GetClone($serverid,$applicationid,$git_url,$git_branch,$deploy_path)
        {
            try
            {
                $url = self::API_URL . "/git/clone";
                $data = [
                    'server_id' => $serverid,
                    'app_id' => $applicationid,
                    'git_url' => $git_url,
                    'branch_name' => $git_branch,
                    'deploy_path' => $deploy_path        
                ];
                $header = array('Authorization'=>'Bearer ' . $this->accessToken);
                $response = $this->client->post($url, array('query' => $data,'headers' => $header));
                return json_decode($response->getBody()->getContents());
            }

            catch (RequestException $e)
            {             
                $response = $this->StatusCodeHandling($e);
                
                return $response;
            }

        }

Now add the following HTML code in the body tag of clone app.php.

<div class="container-fluid">
    <div class="row">
        <div class="col-md-10">
            <form class="form-horizontal" method="post" action="">
                <fieldset>

                    <!-- Form Name -->

                    <legend>Clone Application</legend>               
    
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="server">Server</label>
                        <div class="col-md-4">
                            <select id="server" name="server" class="form-control" required>
                                <option value="">Select Your Server</option>
                                <?php foreach($servers->servers as $server) { echo "
                  <option value='".$server->id."'>".$server->label."</option>"; } ?>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-md-4 control-label" for="application">Application</label>
                        <div class="col-md-4">
                            <select id="app" name="app" class="form-control disable" required>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-md-4 control-label" for="textinput">Enter Git SSH URL</label>
                        <div class="col-md-4">
                            <input id="github_url" name="github_url" type="text" placeholder="placeholder" class="form-control input-md" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-md-4 control-label" for="application">Git Branches</label>
                        <div class="col-md-4">
                            <select id="git_branch" name="git_branch" class="form-control disable" required>
                                <?php echo $options; ?>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-md-4 control-label" for="textinput">Deploy Path</label>
                        <div class="col-md-4">
                            <input id="deploy_path" name="deploy_path" type="text" placeholder="placeholder" class="form-control input-md">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-md-4 control-label" for=""></label>
                        <div class="col-md-4">
                            <button id="clone_project" name="clone_project" class="btn btn-danger">Clone Project</button>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-4 control-label" for=""></label>
                        <div class="col-md-4">
                            <?php echo $success  ?>
                        </div>
                    </div>
                </fieldset>
            </form>
        </div>
    </div>
</div>

Add the PHP code that will deploy your GitHub app in Cloudways

if(isset($_POST['clone_project'])){
        
        $server = $_POST['server'];
        $appname = $_POST['app'];
        $giturl = $_POST['github_url'];
        $git_branch = $_POST['git_branch'];
        $deploy_path = $_POST['deploy_path'];
        $re = $cw_api->GetClone($server,$appname,$giturl,$git_branch,$deploy_path);

        if($re->operation_id){

          echo $re->operation_id;
        }
}

Add JavaScript to auto select application for the servers.

<script type="text/javascript">
    $("#server").change(function() {
        val = $(this).val();
        switch (val) {
            <?php foreach($servers -> servers as $server) { ?>
            case <?php echo "\"".$server -> id.
        "\""; ?>:
                $('#app')
                    .find('option')
                    .remove()
                    .end();
                <?php 
          $i = "<option value=''>Select Your Application</option>";
          foreach($server -> apps as $app) {
              $i .= "<option value='".$app -> id.
              "'>".$app -> label.
              " (".$app -> application.
              ")</option>";
              $i++;
            } ?>
                apps = "<?php echo $i;?>";
                $('#app').html(apps);
                break;
                <?php
        } ?>
            default:
                $('#app')
                    .find('option')
                    .remove()
                    .end();
                break;
        }
    });
</script>

image02

Conclusion

This is a lengthy tutorial with several inter-dependent steps. However, if you follow the order of the steps, you will see that the code works without any hassle. If you still have a question about the code or wish to add to the conversation, do leave a comment below or email us, with screenshots attached using a snipping tool, if that you think it will be helpful for our support staff.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now