How to rerun a failed build step using after-script in Bitbucket Cloud

Platform Notice: Cloud Only - This article only applies to Atlassian products on the cloud platform.

Summary

When running pipelines, particularly scheduled pipelines, there is sometimes a need or use case to re-run a failed pipeline. Currently Bitbucket Cloud does not have a feature to automatically re-run a failed build.

Solution

Caution:

The following can be destructive if there is no manual intervention in case of continuous failures. When setting up the following, you add the possibility that the pipeline will keep re-running a failed step as the same issue that caused the failure could occur when the step runs again. When using this technique, users will need to rely on email notifications or other monitoring to check for continuous failures. In the event of a continuous failure, users will need to manually stop pipelines from triggering builds by logging into Bitbucket Cloud, navigating to the pipeline view and cancel/stop the pipelines. We suggest to test out a setup like this to see if it works for your environment and your workflow.

While we do not currently have a specific feature that would re-run a failed build under some conditions, you could take the following steps:

In the "after_script" section, check the value ofBITBUCKET_EXIT_CODE.

You can then look to use the trigger pipe:Trigger Pipein the after script if the exit code is a failure similar to the sample below:

1 2 3 4 5 6 7 8 9 10 11 script:   - ... after-script:   - if [[ BITBUCKET_EXIT_CODE -eq 0 ]]; then exit 0; else echo "Step failed"; fi     - pipe: atlassian/trigger-pipeline:5.1.3     variables:       BITBUCKET_USERNAME: $BITBUCKET_USERNAME       BITBUCKET_APP_PASSWORD: $BITBUCKET_APP_PASSWORD       REPOSITORY: 'your-repo'       # BITBUCKET_ACCESS_TOKEN: '<string>' # Optional   ...

The sample follows the following flow:

If the value is 0, the build was successful and the pipeline will finish.

If the value is not 0, then additional scripts would be ran.

Where variables:

BITBUCKET_USERNAME- Bitbucket user that will trigger the pipeline. Note, that this should be an account name, not the email.

BITBUCKET_APP_PASSWORD- Bitbucket app password of the user that will trigger the pipeline. Remember to check the Pipelines Write and Repositories Read permissions when generating the app password.

BITBUCKET_ACCESS_TOKEN- The access token for the repository. Required unless BITBUCKET_USERNAME and BITBUCKET_APP_PASSWORD are used.

This pipe will trigger the branch pipeline for master in your-repo. This pipeline will continue, without waiting for the triggered pipeline to complete.

Updated on March 21, 2025

Still need help?

The Atlassian Community is here for you.