Kamsiinov
Kamsiinov

Reputation: 1490

Azure DevOps build agent does not have accesstokens in its tokencache

I am trying to invoke rest api from within Azure DevOps build agent. For that I need bearertoken which I can get in my local machine with:

$accessToken = ((Get-AzContext).TokenCache.ReadItems() | Where { $_.TenantId -eq (Get-AzContext).Tenant } | Sort-Object -Property ExpiresOn -Descending)[0].AccessToken

However, on the build agent this never returns any tokens. Is there some other way I should try to get that token?

Upvotes: 0

Views: 476

Answers (2)

Kamsiinov
Kamsiinov

Reputation: 1490

Thanks for the suggestions and ideas. Answer was too simple to figure it out. I ripped most of the oneliner and now it works by only using:

$accessToken = ((Get-AzContext).TokenCache.ReadItems()

Upvotes: 0

Jeff
Jeff

Reputation: 674

Have you enabled the 'Allow scripts to access the OAuth token' setting in the Agents settings?

enter image description here

This would be for builds and releases using the visual designer.

For YAML builds see the predefined variable documentation. There are notes about using the "System.AccessToken" variable in a script. Essentially, you must explicitly map System.AccessToken into the pipeline using a variable. You can do this at the step or task level:

steps:
  - bash: echo This is a script that could use $SYSTEM_ACCESSTOKEN
    env:
      SYSTEM_ACCESSTOKEN: $(System.AccessToken)
  - powershell: Write-Host "This is a script that could use $env:SYSTEM_ACCESSTOKEN"
    env:
      SYSTEM_ACCESSTOKEN: $(System.AccessToken)

Upvotes: 1

Related Questions