Christian Held
Christian Held

Reputation: 2828

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

Upvotes: 18

Views: 26458

Answers (2)

Louis Cribbins
Louis Cribbins

Reputation: 189

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!

Upvotes: 5

Christian Held
Christian Held

Reputation: 2828

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)

Upvotes: 28

Related Questions