Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow scripts to access OAuth token from yaml builds

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
like image 656
Christian Held Avatar asked Oct 16 '18 14:10

Christian Held


People also ask

How do I enable allow scripts to access the OAuth token Yaml?

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.

How do I allow scripts to access the OAuth token?

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.

What is system access token in Azure Devops?

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.


2 Answers

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)
like image 180
Christian Held Avatar answered Oct 18 '22 01:10

Christian Held


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!
like image 44
Louis Cribbins Avatar answered Oct 18 '22 00:10

Louis Cribbins