0

I have a BRANCH_NAME variable based on the trigger branch which is working great. Now based on my BRANCH_NAME value I have to select a json file. Im using starts with but not sure why my TARGET_ENV is not working

variables:
  system.debug: 'false'
  ${{ if startsWith(variables['Build.SourceBranch'], 
'refs/heads/') }}:
    BRANCH_NAME: $[replace(variables['Build.SourceBranch'], 
'refs/heads/', '')]
  ${{ if startsWith(variables['Build.SourceBranch'], 
'refs/heads/feature') }}:
    BRANCH_NAME: $[replace(variables['Build.SourceBranchName'], 
'/', '-')]
  ###
  ${{ if eq(variables['BRANCH_NAME'], 'dev') }}:
    TARGET_ENV: dev
  ${{ if startsWith(variables['BRANCH_NAME'], 'test') }}:
    TARGET_ENV: test
  ${{ if or( startsWith(variables['BRANCH_NAME'], 'XX'), startsWith(variables['BRANCH_NAME'], 'VV') ) }}:
    TARGET_ENV: feature

And the value of TARGET_ENV should be used in a script ( echo $TARGET_ENV )

dheeraj
  • 49
  • 1
  • 8

1 Answers1

2

The yaml file isn't executes as soon as an element is parted, the yaml file is parted in stages. During the template expansion stage only the variables set at queue time are available.

After the template has been expanded (e.g. the ${{}} blocks have been evaluated the yaml is interpreted top to bottom. So the value of BRANCH_NAME isn't available yet.

You can set the variable either from a pre (like my variable tasks) or from a script by printing one of the special command statements.

    - bash: | 
        echo "##vso[task.setvariable variable=myVar;]foo" 
      condition: $[ eq(variables['BRANCH_NAME'], 'dev' ]
  

Or you can put all the logic in a single PowerShell block and let PowerShell evaluate the values of the variables.

- powershell: |
    if ($env:BRANCH_NAME -eq 'dev') {
      Write-host ##vso[task.setvariable variable=TARGET_ENV;]dev
    } 
    ...
    ...

This variable will only be available in the job the task runs. You can make it an output variable to make the task available in other jobs, but then you need to refer to it by its long name:

Dependencies.jobname.stepname.outputvariable

See also:

jessehouwing
  • 106,458
  • 22
  • 256
  • 341
  • In that case should i add a script , use the same if condition and save as env variable ? can you tell me how can I achieve this ? – dheeraj Dec 13 '22 at 17:43
  • Thanks @jessehouwing that helped. one last thing is , Im doing echo $BRANCH_NAME and $TARGET_ENV in a shell script task: ShellScript@2. BRANCH_NAME o/p is good, but TARGET_ENV still o/p null. – dheeraj Dec 13 '22 at 19:41
  • 1
    I think the ; is missing and quotes , can you add in your answer ? - bash: | echo "##vso[task.setvariable variable=myVar;]foo" – dheeraj Dec 13 '22 at 20:12