Failing failed bash Azure DevOps tasks

Scenario Link to heading

Automating infrastructure as code or continuous delivery with AzDevOps pipelines sometimes requires bash scripts when Arm/Bicep or the built-in tasks fell short. Bash scripts work great, however one issue that surprised me in a production release a few weeks ago is the fact that the failure of one of the commands in the script is not enough to mark the task as failed. For example, this YAML pipeline:

 1trigger:
 2- none
 3
 4pool:
 5  vmImage: ubuntu-latest
 6
 7steps:
 8- task: AzureCLI@2
 9  displayName: Get Application Insights Connection String
10  inputs:
11    azureSubscription: 'MSDN Sub'
12    scriptType: 'bash'
13    scriptLocation: 'inlineScript'
14    inlineScript: |
15      MSYS_NO_PATHCONV=1
16      connString=$(az monitor app-insights component show -a appi-titan-prod -g rg-skynet-prod --query 'connectionString' -o tsv)
17      echo "##vso[task.setvariable variable=connString;isoutput=true;isreadonly=true;]$connString"      

Intended to set a pipeline variable, when ran is marked as success:

AzDevOps Success Job Run

despite the fact that the resource group wasn’t present:

From the run logs:

1ERROR: (ResourceGroupNotFound) Resource group 'rg-skynet-prod' could not be found.
2Code: ResourceGroupNotFound
3Message: Resource group 'rg-skynet-prod' could not be found.

But because the last command, echo, succeeds, the exit code of the task is 0, causing AzDevOps to mark the task as success.

Making the task fail Link to heading

After trying everything I found in the web, the solution is to add the

1set -e

command at the beginning of the script. From the documentation, this command instructs the system to exit immediately if a command fails.

AzDevOps failed job run

Other solutions make reference to the

1failOnStderr: true

task input parameter. This parameter on its own didn’t work for me, at least when dealing with AZ CLI commands.

Finally, the

1continueOnError: false

task parameter seems to be the default behavior and doesn’t need to be added.