My build script uses the SYSTEM_ACCESSTOKEN
environment variable.
In the designer build definition I checked Allow scripts to access the OAuth token and everything works.
After copying the designer generated YAML definition I cannot access the SYSTEM_ACCESSTOKEN
environment variable.
How do I allow my YAML build to access the OAuth Token?
This is my azure-pipelines.yaml:
queue:
name: Hosted VS2017
steps:
- checkout: self
lfs: true
persistCredentials: true
- powershell: ./build.ps1
To fix it - edit the pipeline, go to “Run on agent” job settings, scroll down and check the “Allow scripts to access the OAuth token” option. Now the job will finish as expected - the System. AccessToken is visible to the process.
Allow scripts to access the OAuth tokenSelect this check box in classic build pipelines if you want to enable your script to use the build pipeline OAuth token. This check box is located under the "additional settings" section after selecting the agent job in the pipeline.
System. AccessToken is a special variable that carries the security token used by the running build. You can configure the default scope for System. AccessToken using build job authorization scope. You can allow scripts and tasks to access System.
I found the solution in the Pipeline Variable docs: The variable must be declared in YAML.
At pipeline level for all jobs / tasks:
variables:
system_accesstoken: $(System.AccessToken)
jobs:
job: ...
Or at script / task level for example PowerShell:
- powershell: ./build.ps1
env:
system_accesstoken: $(System.AccessToken)
This is what worked for me.
- pwsh: |
$pat = "Bearer $env:SYSTEM_ACCESSTOKEN"
Write-Host "PAT is: $pat"
$getItemsUrl = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/git/repositories/$(Build.Repository.ID)/items?recursionLevel=Full&includeContentMetadata=true&api-version=6.0"
Write-Host "url: $getItemsUrl"
$data = Invoke-RestMethod -Uri "$getItemsUrl" -Headers @{Authorization = $pat}
Write-Host "Raw data returned from Get Items API call: $data"
Foreach ($i in $data.value)
{
Write-Host "Detailed data returned from Get Items API call: $i"
}
env:
SYSTEM_ACCESSTOKEN: $(System.AccessToken)
displayName: Power!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With