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:

trigger:
- none

pool:
  vmImage: ubuntu-latest

steps:
- task: AzureCLI@2
  displayName: Get Application Insights Connection String
  inputs:
    azureSubscription: 'MSDN Sub'
    scriptType: 'bash'
    scriptLocation: 'inlineScript'
    inlineScript: |
      MSYS_NO_PATHCONV=1
      connString=$(az monitor app-insights component show -a appi-titan-prod -g rg-skynet-prod --query 'connectionString' -o tsv)
      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:

ERROR: (ResourceGroupNotFound) Resource group 'rg-skynet-prod' could not be found.
Code: ResourceGroupNotFound
Message: 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

set -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

failOnStderr: true

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

Finally, the

continueOnError: false

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