Search code examples
powershellazure-devopsautomated-testsazure-pipelinesazure-devops-rest-api

Setting and using an environment variable in multiple release tasks


Problem

How do I pass a value from a release pipeline to a test assembly and a console application (.exe)? In this particular case, I need to pass a Personal Access Token (PAT) that is used by both the test assembly and the console application, something like this:

string token = Environment.GetEnvironmentVariable("appSettings_personalAccessToken");

I've been trying to set an environment variable in one particular task but I'm not able to use it in the the other tasks.

Details

I have configured a release pipeline that runs some integration tests and runs a powershell script that executes a console application:

Release pipeline tasks

Both the integration tests and the console application use a Personal Access Token (PAT) to access the Azure DevOps REST API. I'm reading this value from an environment variable named appSettings_personalAccessToken, which should be set in the release pipeline.

Set token release task

I'm trying to set the PAT in the first task (Powershell task - inline script) but it seems to be ignored in the other tasks, what I am doing wrong?

I tried to set the PAT in the powershell task like this:

Write-Host ##vso[task.setvariable variable=appSettings_personalAccessToken;isSecret=false;isOutput=true;]$personalAccessToken

Or like this:

[Environment]::SetEnvironmentVariable('appSettings_personalAccessToken', $personalAccessToken, 'User')
[Environment]::SetEnvironmentVariable('appSettings_personalAccessToken', $personalAccessToken, 'Machine')

But the value seems to be ignored in the other tasks. What am I missing here?

EDIT 1

Even trying to set the PAT hard-coded in the powershell task doesn't work:

Write-Host "##vso[task.setvariable variable=appSettings_personalAccessToken;isSecret=false;isOutput=true;]MY_TOKEN_VALUE"

Solution

  • There is no need for you to use a PAT for this. Use $(System.AccessToken). You can grant your build or release access to a system-provided OAuth token and then refer to that in instances where you need an auth token.

    Please note that you need to grant access to the OAuth token, otherwise this will not work.