Reputation: 16309
We're using TeamCity 7 and wondered if it's possible to have a step run only if a previous one has failed? Our options in the build step configuration give you the choice to execute only if all steps were successful, even if a step failed, or always run it.
Is there a means to execute a step only if a previous one failed?
Upvotes: 19
Views: 9142
Reputation: 191
I was surprised that TeamCity does not support it out of the box in 2021. But API gives you a lot usefull features and you can do it
As a solution you need to write bash script and call TeamCity API inside
#!/bin/bash
set -e -x
declare api_response=$(curl -v -H "Authorization: Bearer %env.teamcity_internal_api_key%" %teamcity.serverUrl%/app/rest/latest/builds?locator=buildType:%system.teamcity.buildType.id%,running:any,canceled:all,count:2\&fields=build\(id,status\))
declare current_status=`echo ${api_response} | jq '.build[0].status'`
declare prev_status=`echo ${api_response} | jq '.build[1].status'`
if [ "$current_status" != "$prev_status" ]; then
do you code here
fi
some explanation of code above. with API call you get 2 last builds of current buildType. This is last build and previous build. After you assign variable with statuses and compare them in if statement. If you need to run some code in case of current build failed use
if [ "$current_status" = "FAILURE" ]; then
write your code here
fi
Upvotes: 1
Reputation: 2292
Another solution is Webhooks.
This plugin can send webhook to an URL if build fails too. On the webhook side, you can handle some actions, for example, send notification.
Upvotes: 0
Reputation: 30548
As a work around it is possible to set a variable via a command line step that only runs on success which can be checked later.
echo "##teamcity[setParameter name='env.BUILD_STATUS' value='SUCCESS']"
This can then be queried inside a powershell step that is set to run even if a step fails.
if($env:BUILD_STATUS -ne "SUCCESS"){
}
Upvotes: 10
Reputation: 5468
Theres no way to setup a step to execute only if a previous one failed.
The closest I've seen to this, is to setup a build that has a "Finish Build" trigger that would always execute after your first build finishes. (Regardless of success or failure).
Then in that second build, you could use the TeamCity REST API to determine if the last execution from the first build was successful or not. If it wasn't successful then you could whatever it is you want to do.
Upvotes: 10