How to set and read user environment variable in Azure DevOps Pipeline?

set up pipeline variables and then try this mapping in your yaml file:

# ASP.NET Core (.NET Framework)
# Build and test ASP.NET Core projects targeting the full .NET Framework.
# Add steps that publish symbols, save build artifacts, and more:
# https://docs.microsoft.com/azure/devops/pipelines/languages/dotnet-core

pool:
  vmImage: 'VS2017-Win2016'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'
  yourEnvVar: '$(yourPipelineVariable)'
  yourOtherEnvVar: '$(yourOtherPipelineVariable)'

The easiest method is to pass the Azure DevOps(ADO) Env Variable values into your keys like this:

- task: DotNetCoreCLI@2
  displayName: 'Run tests'
  env:
    SAUCE_USERNAME: $(sauceUsername) #this will store the value from 'sauceUsername' into SAUCE_USERNAME
    SAUCE_ACCESS_KEY: $(sauceKey)

Displaying or using the value will work if you try

- bash: echo $(SAUCE_USERNAME) # will output our username stored in SAUCE_USERNAME env variable

And if you are referencing SAUCE_USERNAME in your code, the code will pick up the value from the Azure server.

This article has a good explanation

Previously, I also used Powershell, but this method is more involved and convoluted:

  1. Create your variables in your Azure DevOps pipeline and provide those variables the values.
  2. Create a Powershell script that you will run in the beginning to set your Env Variables. This is what my Posh looks like.
  3. Run this Posh in the beginning as a separate step in your CI pipeline and this will set the environment variables for the VM that's being used to run your pipeline.

This is another detailed article that could help you with this.

As per request, I'm also attaching the PowerShell code that makes this possible.

Param(
[string]$sauceUserName,
[string]$sauceAccessKey,
[string]$sauceHeadlessUserName,
[string]$sauceHeadlessAccessKey
)
Write-Output "sauce.userName that was passed in from Azure DevOps=>$sauceUserName"
Write-Output "sauce.accessKey that was passed in from Azure DevOps=>$sauceAccessKey"
Write-Output "sauce.headless.userName that was passed in from Azure DevOps=>$sauceHeadlessUserName"
Write-Output "sauce.headless.access.key that was passed in from Azure DevOps=>$sauceHeadlessAccessKey"

[Environment]::SetEnvironmentVariable("SAUCE_USERNAME", "$sauceUserName", "User")
[Environment]::SetEnvironmentVariable("SAUCE_ACCESS_KEY", "$sauceAccessKey", "User")
[Environment]::SetEnvironmentVariable("SAUCE_HEADLESS_USERNAME", "$sauceUserName", "User")
[Environment]::SetEnvironmentVariable("SAUCE_HEADLESS_ACCESS_KEY", "$sauceAccessKey", "User")