How to securely deploy from Bitbucket to shared hosting

In the previous tutorial, we linked Bitbucket to our shared hosting (see the tutorial). But wouldn’t it be great to deploy the latest changes from Bitbucket directly, without having to access the shared hosting and run a git pull command in the terminal? Well, buckle up—we’re about to do exactly that!

Stage 1: Generating the SSH Key on Bitbucket

At this stage, we’ll generate an SSH key for our specific Bitbucket repository and retrieve the SSH public key.

Stage 2: Accessing the shared hosting terminal

In your cPanel, navigate to the Terminal page by following the steps in the screenshots below. Once there, make sure you’re in your main directory before getting started.

cd ~ && pwd

Stage 3: Allowing Bitbucket to deploy on the shared hosting

Here, we’ll save the SSH public key we copied in Stage 1 to our shared hosting using the terminal. Then, we’ll authorize a specific command to be executed with that key.

echo "your Bitbucket public key" >> .ssh/bitbucket_<repository-name>_key.pub
curl -o deploy.sh https://raw.githubusercontent.com/BadrHaimeur/tools/refs/heads/main/scripts/linux/autogitpull.sh && chmod 755 deploy.sh
echo 'command="~/deploy.sh <directory-name>" '$(cat .ssh/bitbucket_<repository-name>_key.pub) >> .ssh/authorized_keys

Stage 4: Adding the shared hosting details to the Bitbucket repository

After running all the commands from the previous stage on our shared hosting, we’ll head over to Bitbucket and create a new SSH key. This will allow us to deploy directly to the shared hosting.

Stage 5: Creating the pipeline on the Bitbucket repository

This is the final stage, where we’ll create a special file named “bitbucket-pipelines.yml” with the following content in our Bitbucket repository.

image: atlassian/default-image:3

pipelines:
  branches:
    production:
      - step:
          name: Deploy to Production
          deployment: production
          script:
          - ssh <ssh-username>@<website.com> -p <port-number>

Stage 6: Deploying to the shared hosting

Finally, we’re all set to deploy directly to our shared hosting from Bitbucket using the pipeline we created in the previous stage!

Leave a Reply