Search code examples
azure-devopsdeploymentazure-pipelinescicd

Skip Azure Pipeline jobs (or the whole pipeline) if change is from a merge from a specific branch


I want to skip pipeline jobs (or the whole pipeline) if triggered from a merge from a specific branch.

The source branch is fe-release-inte-package and the merge message is always Merge pull request XXX from fe-release-inte-package into development, where XXX is an integer.

Below is what I have done:

variables:
  CUSTOM_SOURCE_VERSION_MESSAGE: $(Build.SourceVersionMessage)

jobs:
  - job: deploy
    pool:
      name: Azure Pipelines
      vmImage: ubuntu-latest
    condition: not(contains(variables['CUSTOM_SOURCE_VERSION_MESSAGE'], 'fe-release-inte-package'))
    steps:
      - script: |
          echo "Printing all pipeline variables:"
          printenv
        displayName: Print all variables

The condition is already set and in the Print all variables step, I see the following output:

CUSTOM_SOURCE_VERSION_MESSAGE=Merge pull request 8415 from fe-release-inte-package into development

Everything looks correct to me, the problem is the job still runing (because I see the above printenv output).

I don't see any other variable that contains fe-release-inte-package text. How I can update the condition to make it works in this case?


Solution

  • The value of variable CUSTOM_SOURCE_VERSION_MESSAGE comes from predefined variable $(Build.SourceVersionMessage), it's only available on the `step level and is not available in the job or stage levels. You cannot use it in job condition.

    enter image description here

    As an alternative, you can add the condition in each step of the job(add for all steps):

    variables:
      CUSTOM_SOURCE_VERSION_MESSAGE: $(Build.SourceVersionMessage)
    
    jobs:
      - job: deploy
        pool:
          vmImage: ubuntu-latest
        steps:
          - script: |
              echo "Printing all pipeline variables:"
              printenv
            displayName: Print all variables
            condition: not(contains(variables['CUSTOM_SOURCE_VERSION_MESSAGE'], 'fe-release-inte-package'))
    

    enter image description here

    Or to cancel the whole job, you can evaluate the value and fail the 1st task in the job if branch name is met:

    variables:
      CUSTOM_SOURCE_VERSION_MESSAGE: $(Build.SourceVersionMessage)
    
    
    jobs:
      - job: deploy
        pool:
          vmImage: ubuntu-latest
        steps:
          - script: |
              if [[ "$(CUSTOM_SOURCE_VERSION_MESSAGE)" == *"fe-release-inte-package"* ]]; then
                echo "Skipping steps because source branch is met"
                exit 1
              fi
              echo "Printing all pipeline variables:"
              printenv
            displayName: Check condition and print variables