Reputation: 1287
I want to have an expression as a default value for a parameter but I get "a template expression is not allowed in this context" Since templates cannot have variables unless they ONLY have variables (another thing I don't get...), I am looking for other alternatives. Anyone has any idea?
What I'm trying is this:
parameters:
- name: paramOne
default: ${{ lower(replace('$(System.TeamProject)',' ','')) }}
type: string
Here's a full example. This is azure-pipelines.yml
trigger:
- main
pool:
vmImage: windows-2019
steps:
- template: test-template.yml
This is test-template.yml:
parameters:
- name: paramOne
default: ${{ lower(replace(variables['System.TeamProject'],' ','')) }}
type: string
steps:
- task: PowerShell@2
displayName: "Run PowerShell script"
inputs:
targetType: 'inline'
script: Write-Host "${{parameters.paramOne}}"
This results in the error: "a template expression is not allowed in this context"
Variables cannot be added to test-template.yml, as indicated here: https://learn.microsoft.com/en-us/azure/devops/pipelines/process/templates?view=azure-devops#variable-reuse "If you are using a template to include variables in a pipeline, the included template can only be used to define variables"
Upvotes: 3
Views: 8254
Reputation: 40969
It looks that this is not possible. I tested with this:
parameters:
- name: paramOne
default: $[lower(replace(variables['System.TeamProject'],' ',''))]
type: string
- name: paramTwo
default: $(runtimeVar)
type: string
- name: paramThree
default: $(compileVar)
type: string
steps:
- task: PowerShell@2
displayName: "Run PowerShell script"
inputs:
targetType: 'inline'
script: |
Write-Host "${{parameters.paramOne}}"
Write-Host "${{parameters.paramTwo}}"
Write-Host "${{parameters.paramThree}}"
and
trigger: none
variables:
runtimeVar: $[lower(replace(variables['System.TeamProject'],' ',''))]
compileVar: ${{ lower(replace(variables['System.TeamProject'],' ','')) }}
pool:
vmImage: windows-2019
steps:
- template: parameter-with-default-runtime-template.yml
and I got:
$[lower(replace(variables['System.TeamProject'],' ',''))]
devopsmanual
devopsmanual
So you see, the same syntax which is used to populate variable doesn't do the same when you use it as default for parameter.
Upvotes: 3
Reputation: 16238
Ok, then I would propose the following workaround
parameters:
- name: paramOne
displayName: 'My param. Leave empty to populate with default value (project name). bla bla...'
default: ''
type: string
steps:
- task: PowerShell@2
name: 'setVar'
inputs:
targetType: inline
script: |
if( "${{ parameters.paramOne }}" -eq "") {
$val = "$(System.TeamProject)".ToLower().Replace(" ","")
} else {
$val = "${{ parameters.paramOne }}"
}
echo "##vso[task.setvariable variable=varOne]$val"
and from there on use varOne
instead of paramOne
Upvotes: 4