How to use declared variable for if statement in variables declarations in azure pipelines?

Viewed 33

this is my variable declaration section in azure-pipelines.yml, but at the moment even if the branchName is either prod or dev, the buildScript variable will be set from the else clause

What am I missing for the if/else clause to use the correct value?

variables:
  npm_config_cache: '$(Pipeline.Workspace)/.npm'
  ${{ if startsWith(variables['Build.SourceBranch'], 'refs/heads/') }}:
    branchName: $[ replace(variables['Build.SourceBranch'], 'refs/heads/', '') ]
  ${{ if startsWith(variables['Build.SourceBranch'], 'refs/pull/') }}:
    branchName: $[ replace(variables['System.PullRequest.TargetBranch'], 'refs/heads/', '') ]
  ${{ if or(eq(variables['branchName'], 'prod'), eq(variables['branchName'], 'dev')) }}:
    buildScript: 'npm run build:$(branchName)'
  ${{ else }}:
    buildScript: 'npm run build'
1 Answers

You can't use System.PullRequest.TargetBranch in template expressions (I mean ${{}})

enter image description here

So instead of this, you could use the bash/pwsh step to evaluate the branch name properly.

$sourceBranch = "$(Build.SourceBranch)"

if ( $sourceBranch -match "refs/heads/")
{
  $branchName = $sourceBranch.replace('refs/heads/','')
}
elseif ( $sourceBranch -match "refs/pull/")
{
  $targetBranch = "$(System.PullRequest.TargetBranch)"
  $branchName = $targetBranch.replace('refs/heads/','')
}

if ($branchName -eq "prod" -or $branchName -eq "dev")
{
  $buildScript = "npm run build:$branchName"
  Write-Host "##vso[task.setvariable variable=buildScript;]$buildScript"
}
else {
  $buildScript = "npm run build"
  Write-Host "##vso[task.setvariable variable=buildScript;]$buildScript"
}

This is not possible to do with filtering at the variable level.

Related