Back to all articles
Send a Slack message whenever a Bitbucket pipeline fails
Application

Send a Slack message whenever a Bitbucket pipeline fails

Updated on November 21, 2023

Bitbucket pipelines are an amazing tool! You can automate everything that goes into deploying a new website or application. It helps you streamline your go-live process. Also, it’s a breeze for your co-workers to add updates to existing projects.

When everything is set up alright, you only have a sea of green successfully built pipelines — yay! But, as we all know, sometimes things change. Production environments get updated, bugs slip through code reviews, and it’s a fact that some days everything can go haywire.

Monitoring projects for their up-time is something we do by default for all our projects. Yet a notification for when a Bitbucket pipeline would fail was still absent. Slack is our internal communication tool. We dreamt of having a Slack notification whenever a build fails. You can use the slack-notify pipe for this to integrate a webhook call inside of all your pipelines.

many pipelines running across river in dark forest

This can work for new projects, but we already had many projects running. So this was not on the table. Configuring this for all our projects would add unnecessary overhead.

Finding failed pipes with Bitbucket API

We have a Laravel playground where we integrate various APIs like Combell, Teamleader, ClickUp, and Bitbucket to power our internal workings. So instead of changing all configuration files for our projects, we wanted to check if we could find a workaround…

Let’s write some code, and find some repos that have failed pipelines!

Using the Bitbucket API in Laravel is easily done by using https://github.com/GrahamCampbell/Laravel-Bitbucket. Install it via the following code:

composer require "graham-campbell/bitbucket:^10.2"

Next, let’s publish the configuration file to setup the necessary API keys.

php artisan vendor:publish

You should see a new file created config/bitbucket.php.

If you’ve filled in all of your information we should be able to retrieve our repositories like so:

use GrahamCampbell\Bitbucket\Facades\Bitbucket;

$repos = Bitbucket::repositories()->workspaces('weichie.com')->list(['pagelen' => 100]);

This should return your current repositories on Bitbucket with a maximum of 100. For each and every one
of the repositories we’ll now fetch specific information regarding the pipelines.

use GrahamCampbell\Bitbucket\Facades\Bitbucket;

$failedPipelines = collect();

foreach ($repos as $repo) {
    try {
        $query = 'https://api.bitbucket.org/2.0/repositories/weichie.com/' . $repo['slug'] . '/pipelines?page=1&pagelen=1&sort=-created_on';
        $response = Bitbucket::getHttpClient()->get($query);
        $pipelines = collect(json_decode($response->getBody()->getContents(), true)['values']);

        $failedPipelines = $failedPipelines->merge($pipelines->where('state.result.name', 'FAILED'));
    } catch (\Exception $e) {
        // Handle exceptions (e.g., logging, user feedback)
    }
}

Whenever you run this code you should be left with all of the failed pipelines for each and every repository that has been checked.

Because we don’t want to receive notifications on old failed pipelines we’ve implemented a filter to only those that have failed in the last 15 minutes.

use Carbon\Carbon;

foreach( $failedPipelines as $failedPipeline ){
        if( Carbon::parse($failedPipeline['completed_on'])->isAfter(Carbon::now()->subMinutes(15)) ){
                Slack::message(':warning: Hey Weichie.com, a pipeline failed for ' . $failedPipeline['repository']['name']);
        }
}

One command to find all failed pipelines

For ease of use, we created the following command NotifyFailedPipelines with this command:

php artisan make:command NotifyFailedPipelines

It houses all of the above codes. Through Laravel Task Scheduling, we now have an automated system that sends us Slack notifications whenever a pipeline has failed.

Our team is using pipelines for all our websites, applications, and dashboards. We really can’t imagine life without it.

Leave a Reply

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