admin管理员组

文章数量:1313362

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 variable?

I have tried doing it like this (note parameter name/value is not real):

variables:
  ${{ if eq(parameters['PARAM'], 'VALUE') }}
    - name: environment
      value: "PROD"

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 variable?

I have tried doing it like this (note parameter name/value is not real):

variables:
  ${{ if eq(parameters['PARAM'], 'VALUE') }}
    - name: environment
      value: "PROD"
Share Improve this question edited Jan 31 at 12:07 Rui Jarimba 18.2k11 gold badges64 silver badges98 bronze badges Recognized by CI/CD Collective asked Jan 30 at 21:55 user29437807user29437807 1
  • Instead of parameters['PARAM'] syntax I'd recommend using parameters.PARAM - it's slightly more readable IMO :-) – Rui Jarimba Commented Jan 31 at 11:41
Add a comment  | 

1 Answer 1

Reset to default 2

As an alternative to Scott's answer, consider creating several variable templates (one for each environment) and dynamically reference these templates using a parameter.

Example pipeline:

parameters:
  - name: environment
    type: string
    default: development
    values:
      - development
      - production

pool:
  vmImage: ubuntu-latest

trigger: none

variables:
  - template: /pipelines/variables/${{ parameters.environment }}-variables.yaml

steps:
  - checkout: none
  - script: |
      echo "Selected environment: $(environment)"
    displayName: 'Print environment'

/pipelines/variables/production-variables.yaml:

variables:
  - name: environment
    value: PROD
    readonly: true
  
  # other production specific variables here

/pipelines/variables/development-variables.yaml:

variables:
  - name: environment
    value: DEV
    readonly: true
  
  # other development specific variables here

Advantages:

  • Code is cleaner: no ${{ if ... }} statements in the middle of the code
  • Better variables anization: each environment has its own specific template

本文标签: How do I use expressions when defining variables in Azure DevOps yaml pipelinesStack Overflow