iabhee
iabhee

Reputation: 610

conditional build based on branch for multi stage pipeline using different templates under stages

How to trigger by branch to use specific template under "stages"?

trigger:

 branches

   include:

     - ci

     - prod

stages:

Tried above condition but didn't work. I was getting "unexpected value condition". Any help is appreciated

***** Tried one of the solution as by passing condition as parameter to the template:

stages:

Getting "unexpected parameter condition"

Pipeline structure:

master.yml (contains runtime parameters) stages:

template: ci.yml

parameters:

condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/ci'))

template: prod.yml

parameters:

condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/prod'))

ci.yml

stages:

prod.yml

stages:

Upvotes: 1

Views: 8986

Answers (1)

Leo Liu
Leo Liu

Reputation: 76660

How to trigger by branch to use specific template under "stages"?

To resolve this issue, we could add the condition on the job level, like:

stages:
- stage: Test1
  jobs:
  - job: ci
    displayName: ci
    pool:
      name: MyPrivateAgent
    condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/ci'))
    steps:
        - template: ci.yml

  - job: prod
    displayName: prod
    pool:
      name: MyPrivateAgent
    condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/prod'))
    steps:
        - template: prod.yml

Check the document Specify conditions for some more details.

On the other hand, we could also set the condition as parameter to the template yml, like:

- template: ci.yml
  parameters:
    doTheThing: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/ci'))

The template yml file:

# template.yml
parameters:
  doTheThing: 'false'
steps:
- script: echo This always happens!
  displayName: Always
- script: echo Sometimes this happens!
  condition: ${{ parameters.doTheThing }}
  displayName: Only if true

You could check the thread YAML - Support conditions for templates for some more details.

Hope this helps.

Upvotes: 2

Related Questions