Azure pipeline: conditional env variable based on OS

Viewed 2837

I am trying to make my environment variables dependent on the Agent operating system.

I wrote the following test.yml, but it does not work:

jobs:
  - job: Test
    pool:
      vmImage: 'ubuntu-latest'
    steps:
      - pwsh: |
          echo $env:TestVar
          echo $env:OS
        env:
          OS: $[variables['Agent.OS']]
          ${{ if eq(variables['Agent.OS'], 'Windows_NT') }}:
            TestVar: "I am Windows"
          ${{ if eq(variables['Agent.OS'], 'Linux') }}:
            TestVar: "I am Linux"

Is there a problem with my YAML indentation?

3 Answers

Based on the answer of Cece Dong, Agent variables can't be used in this syntax. The cleanest way to achieve the same effect is just to use the shell for managing environment variables.

jobs:
  - job: Test
    pool:
      vmImage: 'ubuntu-latest'
    steps:
      - pwsh: |
           if ($env:AGENT_OS -eq "Windows_NT") {
             $env:TestVar="I am Windows"
           }
           if ($env:AGENT_OS -eq "Linux") {
             $env:TestVar="I am Linux"
           }

and if TestVar is supposed to be used in another step use this afterwards:

           echo "##vso[task.setvariable variable=env:TestVar]$env:TestVar"

Your YAML seems to be correct, but there is sth not clear on Azure DevOps. However, you can use this as a workaround:

trigger:
- master

jobs:
- job: Test
  pool:
    vmImage: 'ubuntu-latest'
  variables:
    varOS: $(Agent.OS)
  steps:
    - pwsh: |
        $testVar = ''
        $os = '$(Agent.OS)'
        if ($os -eq 'Windows_NT') {
          $testVar = "I am Windows";
        } elseif ($os -eq 'Linux') {
          $testVar = "I am Linux";
        }
        Write-Host $testVar
        Write-Host "##vso[task.setvariable variable=HelloOS;isOutput=true]$testVar"
      name: Initialize
    - pwsh: |
        echo $env:TestVar
        echo $env:OS
        echo $env:AGENT_OS
        echo $env:IsMaster
        printenv
      env:
        OS: $(varOS)
        TestVar: $(Initialize.HelloOS)
        ${{ if eq(variables['Build.SourceBranch'], 'refs/heads/master')}}:
          IsMaster: "true"

for this build I got:

I am Linux
Linux
Linux
true

I tried few approached, also putting conditional setup in variables section. But only this gave expected result. Of course since you can access $env:AGENT_OS you can put this conditional logic directly in target step. I just assumed that you want to have TestVar provided somewhere else.

Related