Eric Brown
Eric Brown

Reputation: 13932

Evaluate an expression at template expansion time

I have an azure pipeline template that takes parameters, and I'd like to set one of the parameters based on an expression:

  - template: templates/mytemplate.yml
    parameters:
      TestBackCompat: eq('${{ parameters.CIBuildId }}', 'MasterLatestBuildId')
      CreateNupkg: ${{ parameters.CreateNupkg }}

As written, it doesn't work, because the expression isn't evaluated until runtime.

Is there a way to evaluate the expression at compile-time? Simple variable replacement (e.g., the usage of CreateNuPkg in the script above) works OK.

Upvotes: 2

Views: 1397

Answers (1)

Bowman Zhu
Bowman Zhu

Reputation: 7146

From this official document:

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/templates?view=azure-devops#template-expressions

Template expressions can expand template parameters, and also variables. You can use parameters to influence how a template is expanded. The object works like the variables object in an expression.

How the variable object works:

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch#runtime-expression-syntax

enter image description here

So the usage in your situation should be like this:

give_parameters.yml

trigger:
- none

parameters:
  - name: CIBuildId
    type: string
    default: 'MasterLatestBuildId'

extends:
  template: using_parameters.yml
  parameters:
    TestBackCompat: ${{ eq(parameters.CIBuildId, 'MasterLatestBuildId')}}

using_parameters.yml

parameters:
  - name: CIBuildId
    type: string
    default: 'x'
  - name: TestBackCompat
    type: string
    default: 'x'
variables:
  - name: test1
    value: ${{ parameters.TestBackCompat}}
  - name: test2
    value: ${{ parameters.CIBuildId}}

steps:
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      Write-Host $(test1)
      Write-Host $(test2)
      Write-Host ${{ parameters.TestBackCompat}}

Result:

enter image description here

Upvotes: 4

Related Questions