Site icon D4D Blog

How to deploy code using rsync with bitbucket pipelines

This tutorial will explain how to deploy our PHP code to a remote server over SSH using Bitbucket pipelines!

Prerequisites

bitbucket-pipelines.yml file example

image: atlassian/default-image:4

pipelines:
  branches:
    dev:
      - step:
          name: Deploy to development
          deployment: test
          script:
            - apt-get update && apt-get install -y rsync
            - rsync -vcarzhO -e "ssh -p $SSH_PORT" --delete --stats --chmod=Du=rwx,Dg=rwx,Do=rx,Fu=rw,Fg=rw,Fo=r --exclude-from=.rsync-exclude . $SSH_USER@$SSH_HOST:$DEST_PATH
            
    master:
      - step:
          name: Deploy to production
          deployment: production
          script:
            - rsync -vcarzhO -e "ssh -p $SSH_PORT" --stats --chmod=Du=rwx,Dg=rwx,Do=rx,Fu=rw,Fg=rw,Fo=r --exclude-from=.rsync-exclude . $SSH_USER@$SSH_HOST:$DEST_PATH

Step 1. Enable pipelines.

You can enable pipelines in your repository by visiting the Bitbucket Repository settings -> Settings -> Enable Pipelines.

Step 2. Server

On your server side, we need to have a dedicated user that will be used to transfer your application files to the server. If you don’t have a user, create it for your deployment.

Step 3. SSH access

Since I like a more secure way. I will use SSH to deploy the code. The SSH deployment allows us to use public key authentication to take advantage of passwordless logins. You can either use your own existing SSH keys or generate unique ones. I recommend generating a new one.

Go to Bitbucket Repository settings -> Pipelines -> SSH Keys and take two simple steps:

After adding the SSH key to your bitbucket repository, don’t forget to put the public key into your server into ~/.ssh/authorized_keys file.

Step 4. Deployment variables

We can use pipeline deployment variables to keep secrets out of our code and also make things a bit more portable.

Add these deployment variables via the Bitbucket GUI here Repository Settings -> Pipelines -> Deployments -> Select environment and put variables which we use in our bitbucket-pipelines.yml script.

Step 5. Run your pipeline.

We are ready to run our first bitbucket pipeline on our server. Just go to your bitbucket repository. Select pipelines -> Run pipeline -> Select branch -> Select pipeline and click the button “Run.”

Exit mobile version