Run CI / CD by Pull Requests on Bitbucket pipeline

2019-05-22 • 2 min read
#continuous delivery#continuous integration#bitbucket#docker

Recently I have the opportunity to build CI/CD for our projects. The requirements are running unit tests by pull requests and deploy the current version of the pull requests to our development server, then sending a preview link after it’s done. By doing so, we can let stakeholders test on new features before rolling out to production.

Since we use Bitbucket as part of our service, we would like to take advantage of its functionality. Luckily, Bitbucket just released a new version of bitbucket pipeline that allows users to trigger its pipeline by pull requests (ref1, ref2) in October 2018!

What we need to do is to simply write a bitbucket-pipelines.yml file, such as the following:

image: my-public-image # any image you want
pipelines:
pull-requests:
'**':
- step:
name: Unit Test and Build
caches:
- node
script:
- yarn --no-progress --pure-lockfile
- yarn run type-check
- yarn test --silent
- yarn build
artifacts:
- builds/**
- step:
name: Deploy
script:
- aws s3 sync ./builds/ s3://s3-bucket-name --quiet
- curl 'https://bitbucket.org/!api/2.0/repositories/$REPO_SLUG/$REPO/pullrequests/$PR_NUMBER/comments/' \
-X POST -u $USER:$TOKEN -H 'Content-Type: application/json' \
-d '{"content":{"raw": "https://preview.link/$BRANCH_NAME"}}'

The image is the environment/docker image that you need to run your pipeline. You can get the public ones from dockerhub easily or create your own one and push to dockerhub (see how to push your docker image). After that, all you need is to type in the scripts to test or build your project.

We host our static files on AWS S3. Thus, we need to sync the builds to our S3 buckets. Then, just like now.sh does for deployment, we only need to make a post request (check Bitbucket api doc) to comment the preview link to our pull request on Bitbucket. There are plenty of environment variables available in bitbucket pipeline if you need any of them. You might face some authentication issue when making post request. What I did is making an app password/token for my comment bot (check how to create it here). Alternatively, you could use OAuth to solve authentication issue.

That’s it! 😄

This article is originally published on my Medium.