When defining a variable in an Azure DevOps .yaml pipeline:
variables:
- name: environment
value: "PROD"
How can I use an expression to dynamically set the value of the expression?
I have tried doing it like this (note parameter name/value is not real):
variables:
${{ if eq(parameters['PARAM'], 'VALUE') }}
- name: environment
value: "PROD"
Expression usage with variables can be achieved in a few ways. In my example, I will define a parameter named envName
, and dynamically create a variable named envCode
based on the value of envName
.
The important part to note about what is wrong in your example is the usage of the -
and the spacing. A simple method to know how to format an expression within .yaml is if the statement directly after the expression contains a -
at the start, then your expression should also contain the -
at the start.
Example one:
parameters:
- name: envName
type: string
values:
- "Production"
- "Development"
variables:
- name: envCode
${{ if eq(parameters['envName'], 'Production') }}:
value: "PROD"
${{ elseif eq(parameters['envName'], 'Development') }}:
value: "DEV"
${{ else }}:
value: "INVALID"
Example two:
parameters:
- name: envName
type: string
values:
- "Production"
- "Development"
variables:
${{ if eq(parameters['envName'], 'Production') }}:
envCode: "PROD"
${{ elseif eq(parameters['envName'], 'Development') }}:
envCode: "DEV"
${{ else }}:
envCode: "INVALID"
Example three:
parameters:
- name: envName
type: string
values:
- "Production"
- "Development"
variables:
- ${{ if eq(parameters['envName'], 'Production') }}:
- name: envCode
value: "PROD"
- ${{ elseif eq(parameters['envName'], 'Development') }}:
- name: envCode
value: "DEV"
- ${{ else }}:
- name: envCode
value: "INVALID"
Example four: Variable file
parameters:
- name: envName
type: string
values:
- "Production"
- "Development"
variables:
- template: .\environments-vars.yaml
parameters:
envName: ${{ parameters.envName}}
The environments-vars.yaml
file:
parameters:
- name: envName
variables:
${{ if eq(parameters['envName'], 'Production') }}:
envCode: "PROD"
${{ elseif eq(parameters['envName'], 'Development') }}:
envCode: "DEV"
${{ else }}:
envCode: "INVALID"