Powershell / VSTS Build - Store Credentials Independent/ Agnostic of User Running Script

前端 未结 1 1871
野的像风
野的像风 2021-01-24 02:38

I\'m trying to create a script for a build that checks out a file, edits it and checks it back in.

I want it to work when running as a developer, or as a build agent.

1条回答
  •  北海茫月
    2021-01-24 03:05

    Builds allow you to access PAT token via a settings in build definition. These are on the fly generated PAT tokens, so you won't need to store any secret anywhere.

    For running the script at a developer's machine, you can ask a developer to enter PAT or have an if else logic where you can ask him for username password.

    More info at

    https://www.visualstudio.com/en-us/docs/build/scripts/#use-the-oauth-token-to-access-the-rest-api

    Update (full solution):

    In your build, you must go to 'Options' and turn on 'Allow scripts to access OAuth token'.

    Your final script will look something like the following.

    Add-PSSnapin Microsoft.TeamFoundation.PowerShell
    # This file requires the TFS Power Tools (2015+). When installing, you must select Custom Installation and select PowerShell Cmdlets
    
    # *VSTS Login*
    $url = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/build/definitions/$($env:SYSTEM_DEFINITIONID)?api-version=2.0"
    Write-Host "URL: $url"
    $definition = Invoke-RestMethod -Uri $url -Headers @{
        Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
    }
    Write-Host "Definition = $($definition | ConvertTo-Json -Depth 100)"
    "***************** Authenticated *****************"
    
    " *VSTS Check Out file* from $fileToUpdate"
    Add-TfsPendingChange -Edit -Item $fileToUpdate -Verbose -ErrorAction Stop -wa 0
    
    
    # read the file, update the number and save it back
    $stuff = Get-Content $fileToUpdate
    # modify stuff - make sure you actually make a change!
    Set-Content -Value $stuff -Path $fileToUpdate
    
    
    # *VSTS Check In* Check in the file after changes.
    " *VSTS Check In"
    New-TfsChangeset -Item $fileToUpdate -Verbose -Comment "***NO_CI***" -Override true -ErrorAction Stop
    

    0 讨论(0)
提交回复
热议问题