Handling failing tasks in Azure pipelines
Sometimes failing scripts are not failing the task when they should. And sometimes a failing command should not fail the task.
How to handle these situations?
An unpleasant surprise
Let’s dive straight into our topic and take a look at an example script
task
that tries to tag a pipeline run:
In this example the az
command fails due to some missing extension. This
results in output like this:
The command fails and prints an ERROR
(to stderr
). But both the task and the
pipeline still succeed:
Why does this not fail the task? It’s because the az
command does not exit
with a non-zero code.
This is often not the desired behavior. Fortunately, when we want to fail the pipeline we do have some options:
- Use the
failOnStderr
task option - Use
set -e
inside the script
Let’s look what happens when either of these are used.
Fail on errors written to stderr
Here we can add failOnStderr
as a task configuration option:
This will execute the whole script, but make the task fail, since the az
command prints the error to stderr
:
The pipeline fails:
Another unpleasant surprise
As a side note, when we want to do the same for a task (as opposed to a
script), this requires a different setting. For tasks the failOnStandardError
option needs to be set as part of the inputs
:
This is not consistent. But let’s continue with the set -e
option we still
have left.
Halt on script error
To make the script fail on errors, use set -e
at the start of the script:
This will fail the script immediately:
And again, the pipeline fails as intended:
But notice the difference in behavior: the “Tagged build for my-container” message is not printed here.
Depending on the use case one or the other is the better choice, although I think in general failing immediately is the better option.
Continue on error
Last but not least, sometimes the pipeline should continue even if the task
failed. For this use case, there is continueOnError
to the rescue:
This will result in a green pipeline, but also a warning sign for the stage with the failed task:
Compare this to the initial situation where everything is naively green. At least now we can see something is off.
Azure DevOps documentation links
- Command Line task covers
failOnStderr
- Azure CLI task covers
failOnStandardError
- Task types & usage covers
continueOnError