How to rerun a failed build step using after-script in Bitbucket Cloud
Platform Notice: Cloud Only - This article only applies to Atlassian apps 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 of BITBUCKET_EXIT_CODE.
You can then look to use the pipe Trigger Pipeline in the after script if the exit code is a failure, similar to the sample below:
script:
- ...
after-script:
- if [[ BITBUCKET_EXIT_CODE -eq 0 ]]; then exit 0; else echo "Step failed"; fi
- pipe: atlassian/trigger-pipeline:5.10.1
variables:
ATLASSIAN_ACCOUNT_EMAIL: $ATLASSIAN_ACCOUNT_EMAIL
ATLASSIAN_API_TOKEN: $ATLASSIAN_API_TOKEN
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:
ATLASSIAN_ACCOUNT_EMAIL - The Atlassian account email address of the Bitbucket user that will trigger the pipeline.
ATLASSIAN_API_TOKEN - An API token of the user that will trigger the pipeline. It will need to have the scopes read:pipeline:bitbucket, write:pipeline:bitbucket and read:repository:bitbucket.
BITBUCKET_ACCESS_TOKEN - The access token for the repository. Required unless ATLASSIAN_ACCOUNT_EMAIL and ATLASSIAN_API_TOKEN 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.
Was this helpful?