Way to add condition on Running a Stage on Azure DevOps Multi stage YAML pipeline

71 Views Asked by At

I am trying to implement a multi-stage pipeline in azure devops that is running everytime a push is committed all branches.

But, I would like to skip a certain stage in executing a pipeline stage using condition, given certain branches

Here is the initial script:

jobs:
- job: JOB A
  variables:
    protected_branches: master, main
  condition: containsValue(variables['protected_branches'], variables['Build.SourceBranchName'])

Seems this script is not working

Thank you!

2

There are 2 best solutions below

2
Scott Richards On BEST ANSWER

Since variables in Azure DevOps pipelines can only be defined as strings, you should use contains instead of containsValue.

Here is a code sample where I trigger the pipeline from a branch named test-pipeline:

jobs:
- job: Job_A
  variables:
    protected_branches: 'master, main'
  condition: contains(variables['protected_branches'], variables['Build.SourceBranchName'])
  steps:
  - powershell: |
      Write-Host "Will only if source branch is: master or main"

- job: Job_B
  variables:
    protected_branches: 'test-pipeline'
  condition: contains(variables['protected_branches'], variables['Build.SourceBranchName'])
  steps:
  - powershell: |
      Write-Host "Will only if source branch is: test-pipeline"

Output: enter image description here

0
Andy Li-MSFT On

Scott is right, the variable is defined as strings, in this case we can use contains instead of containsValue.

However, we can use the containsValue expression to find a matching value in an object like below sample. See the expression contains and containsValue for details.

also added this approach but is returning an error when attempting to run pipeline - name: protected_branches type: object default: - main - master condition: containsValue('main', '${{ variables['protected_branches'] }}')

That's because you used the wrong syntax. The correct one should look like this:

parameters:
- name: protected_branches
  displayName: Source branch options
  type: object
  default:
    - master
    - main

jobs:
  - job: Job_B  
    condition: ${{ containsValue(parameters.protected_branches, variables['Build.SourceBranchName']) }}
    steps:
      - script: echo "Matching branch found -SourceBranchName - $(Build.SourceBranchName)"