skip to Main Content

This query is regarding Azure DevOps YAML pipeline. Is it possible to put an execution condition on any template defined inside ‘steps’?

For ex:

  1. Based on any pipeline variable value (dynamic, passed during pipeline run), decide whether to execute or not ‘Task-1.yml’
  2. Based on any variable value defined inside a shell script (using ##vso[task.setvariable variable=name]$value), decide whether to execute or not ‘Task-3.yml’

Below is the Azure devops yaml pipeline structure:

stages:
- stage: Stage-A
  jobs:
  - job: Job-A
    steps:
      - template : Task-1.yml
      - template : Task-2.yml
      - template : Task-3.yml

I was able to do this at job level, however I cannot change pipeline structure to have more than 1 jobs since I need all tasks to execute on same build agent allocated at pipeline run.

I did lot of hit and trial to achieve this but somehow this is not working for me.

Please help!

2

Answers


  1. You cannot apply a run-time condition for pipelines. The only way is to use template expression ${{ }} but this is evaluated at a compile-time.

    You can find these details here

    Within a template expression, you have access to the parameters context that contains the values of parameters passed in. Additionally, you have access to the variables context that contains all the variables specified in the YAML file plus many of the predefined variables (noted on each variable in that article). Importantly, it doesn’t have runtime variables such as those stored on the pipeline or given when you start a run. Template expansion happens early in the run, so those variables aren’t available.

    Login or Signup to reply.
  2. The way I do it is passing the condition to the template like so:

    stages:
    - stage: Stage-A
      jobs:
      - job: Job-A
        steps:
          - template : Task-1.yml
            parameters:
              condition: ${{ yourConditionHere }} # such as "and(succeeded())"
          - template : Task-2.yml
          - template : Task-3.yml
    

    And use it in the template like so:

    parameters:
      - name:  condition
        type: string
    
    steps:
      - task: PowerShell@2
        displayName: "Task name"
        inputs:
          targetType: "inline"
          script: |
            Write-Host "Hello world"
        condition: ${{ variables.condition }}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search