Nerd in Training
Nerd in Training

Reputation: 2220

Dynamically choose variable template based on branch trigger

I have a folder structure as follows:

-> variables
    -> dev
       variables.yml
    -> pp
       variables.yml

I then have a azure-pipeline.yml that extends a pipeline template called template.yml. In my template.yml, I want to use logic to determine which template variable file I want to use. So if my $(Build.SourceBranch) starts with fix/*, I want to use dev, or else use pp

Ideally, this logic would work, but does not because in azure pipeline at run time cannot do this:

- ${{ if or(StartsWith(variables['Build.SourceBranch'], 'refs/head/features/'),StartsWith(variables['Build.SourceBranch'], 'refs/head/fix/')) }}:
   - template: variables/dev/variables.yml
- ${{ else }}:
   - template: variables/pp/variables.yml

I'm not sure what to do at this point. I don't want to use parameters because the list would be too large.

Upvotes: 1

Views: 1286

Answers (1)

wade zhou - MSFT
wade zhou - MSFT

Reputation: 8127

  1. Use "heads" in the branch name: "refs/heads/features", "refs/heads/fix".
  2. Remove / at the last of the branch name if it doesn't have sub branch, eg: branch features but no features/test1 branch.

The sample yaml:

trigger: 
 branches:
  include:
     - main
     - features
     - fix/*

pool:
  vmImage: ubuntu-latest

variables:
- ${{ if or(StartsWith(variables['Build.SourceBranch'], 'refs/heads/features'),StartsWith(variables['Build.SourceBranch'], 'refs/heads/fix')) }}:
   - template: variables1/dev/variables.yml
- ${{ else }}:
   - template: variables1/pp/variables.yml

steps:
- script: |
   echo the SourceBranch is $(Build.SourceBranch)
   echo the testvar1 value is ${{ variables.testvar1 }}.

enter image description here

Upvotes: 2

Related Questions