'How to refer a variable in parameters block in azure pipelines
I'd like to set default value of a parameter from a variable. Unfortunately, below pipeline throws this error The 'Environment' parameter value '$[variables.deployToEnv]' is not a valid value.
I tried it with other expressions too but it doesn't work. How can I solve this problem?
variables:
- name: deployToEnv
${{ if in(variables['Build.SourceBranchName'], 'Development') }}:
value: dev
${{ if in(variables['Build.SourceBranchName'], 'Staging', 'Testing') }}:
value: test
${{ if in(variables['Build.SourceBranchName'], 'Production') }}:
value: prod
parameters:
- name: Environment
type: string
displayName: Environment
default: $(deployToEnv)
# default: $[variables.deployToEnv]
# default: ${{ variables.deployToEnv }}
values:
- dev
- test
- prod
Solution 1:[1]
From my experience, it was simply impossible to reference a variable in parameters context.
I found solution for my problem by flipping dependency. Instead setting parameter base on a variable, I set a variable base on a parameter.
parameters:
- name: Environment
type: string
displayName: Environment
default: none
values:
- none
- dev
- test
- prod
variables:
- name: deployToEnv
${{ if not(eq(parameters.Environment, 'none')) }}:
value: ${{ parameters.Environment }}
${{ if and(eq(parameters.Environment, 'none'), in(variables['Build.SourceBranchName'], 'Development')) }}:
value: dev
${{ if and(eq(parameters.Environment, 'none'), in(variables['Build.SourceBranchName'], 'Staging', 'Testing')) }}:
value: test
${{ if and(eq(parameters.Environment, 'none'), in(variables['Build.SourceBranchName'], 'Production')) }}:
value: prod
- group: k8s-cluster-${{ variables.deployToEnv }}
Solution 2:[2]
This is because parameters are parsed early in the processing of the pipeline before the variables are computed. So you cannot set a parameter based on a variable.
This is not really a problem you just have to re-think the flow of your pipeline.
You have not provided details how you are trying to use this parameter so it's difficult to help solve your problem.
@Lukasz suggestion of using conditional insertions is useful.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lukasz Dynowski |
| Solution 2 | James |
