Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Azure DevOps yaml variables conditionally based on parameter value

I am trying to set variables based on a parameter value in a yaml pipeline. It seems that I've read many other posts which show examples like the one below that the authors have said worked, but I cannot get past issues when trying to do something like below.

I've tried many variations on this example as well, too many to list here. Sometimes it will show 'values' as a duplicate key. In other cases I've been able to try and start a run and get the prompt with environment selection, but then opening the stage dialog throws a parse error.

Is there some sort of difference between variable declaration at the top of the file vs in a stage or job? That seems to be the difference that I notice when reading through other examples.

Ultimately what I'm trying to do is set the ServiceConnection variable value based on the value of the environment parameter.

parameters:
- name: environment
  displayName: Environment
  type: string
  values:
  - DEV
  - TEST

pr: none
trigger: none

pool: PrivateAgentPool

variables:
  - name: 'isMain'
    value: $[eq(variables['Build.SourceBranch'], 'refs/heads/main')]
  - name: 'buildConfiguration'
    value: 'Release'

  - name: 'environment'
    value: ${{ parameters.environment }}

  - name: 'ServiceConnection'
    ${{ if eq(variables['environment'], 'DEV') }}:
      value: 'svcConnectionDev'
    ${{ if eq(variables['environment'], 'TEST') }}:
      value: 'svcConnectionTest'
like image 734
Mike Avatar asked Mar 15 '26 20:03

Mike


1 Answers

Looks like your solution is almost correct. Consider the below example.

parameters:
  - name: region
    type: string
    default: westeurope
    values:
      - westeurope
      - northeurope

variables:
  ${{ if eq(parameters['region'], 'westeurope') }}:
    ServiceConnection: "svcConnectionDev"
  ${{ else }}:
    enter code here

if you want to used this ServiceConnectionvar across you can do it just by calling $ServiceConnection

like image 62
ElonMusk99 Avatar answered Mar 18 '26 22:03

ElonMusk99



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!