Trigger Visual Studio Team Services (VSTS) CI Build from BitBucket

We use BitBucket for our source control and VSTS for CI. VSTS build definition has a trigger option which will monitor the repository every so many seconds (min is 60s) and if new changes are there it will trigger the build. But that feature only works when you have VSTS repositories  and for any external repository the developer needs to login to VSTS after the changes are pushed and wait for at least 60 seconds for the build to kick off. I’m pretty sure that manually triggering the build takes less time. Also, that model by itself is not efficient specially in the world of Webhooks.

BitBucket supports Webhooks. For example you can call add Webhooks for each push (unfortunately you can not specify a branch). The problem is that VSTS CI build definition does not accept Webhooks as trigger.

In this post I’m going to show how this can be done by using BitBucket Webhooks , Azure Function Apps and VSTS REST API.

I’m pretty sure that if you wait a bit longer Webhooks will be added to CI trigegrs in VSTS however, if you are impatient like I am then the good news is this turned out to be much easier than I originally thought.

All you need is an Azure Function app and a piece of code (check below) that calls VSTS CI Build definition REST API in order to trigger a build definition.

Here are the ingredients:

  1. VSTS Personal Access Token
  2. The visual studio instance name. You can pick that up from the URL in which you access your VSTS -> http://{instance_name}.visualstudio.com
  3. The project name
  4. The build definition Id. When you click on a build definition you can pick that from the URL. There are also REST API available for getting the list of build definitions if you wish to make the code more advanced.
  5. An Azure Function App (or even a normal WebApi hosted somewhere but then you need to modify the code below)

Couple of notes about the code:

  • As you can see we need to look into the payload sent from BitBucket to check the branch name
  • I’m monitoring two different branches and triggering two different build definitions.

Now that you have that code in place all you need to do is to add the address of that function in the Webhooks setting of your repository in  BitBucket. From this point on whenever you push any changes to your repository, BitBucket will send a push payload to the Webhook azure function that you’ve defined and if the branch matches the condition the build definition will be triggered.

Resources:

 

Leave a Reply

Your email address will not be published. Required fields are marked *