skip to Main Content

I have set environment variable in azure yaml pipeline like this

- task: PowerShell@2
  inputs:
targetType: 'inline'
script: |      $env:MY_VARIABLE = "$(my-value)"
$env:MY_VARIABLE >> test.txt
...

when I run the pipeline and go to published artifact in summary section of the pipeline, I can see that test.txt has correct value. Is there a way I can read this MY_VARIABLE in c# code, which is going to be run with a specflow task in this yaml pipeline

2

Answers


  1. Chosen as BEST ANSWER

    Found that by using env: in task like below we can have compiled C# code ( in my case running on ms hosted agent) read the variables directly.

    - task: VSTest@2
      displayName: tests
      env:
        MY_VARIABLE = "$(my-value)"
    

    and then in c# code we can do like this

     string  var= Environment.GetEnvironmentVariable("MY_VARIABLE", EnvironmentVariableTarget.Process);
    

    Note that without using env: , it may not work


  2. You can’t read Azure Pipelines variable directly in C#. However, each Azure Pipeline variable is mapped to an environment variable (except for secrets). You can read about this here.

    So, all that you need is Environment.GetEnvironmentVariable.

    And of course you need to run your code on pipeline, not compile create package and then run somewhere else.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search