PowerShell / VST构建 - 存储凭据独立 /运行脚本的用户不可知



我正在尝试为构建创建一个检查文件,进行编辑并将其重新检查的脚本。

我希望它在作为开发人员或构建代理运行时工作。

我有一个与此类似的解决方案,该解决方案将密码存储在文件中并为构建检索。

即。

文件创建:

read-host -prompt Password -assecurestring | convertfrom-securestring | out-file .ps-password.pwd -ErrorAction Stop

文件使用:

# *VSTS Login*
$Username = $tfsUserName
$Password = Get-Content $tfsUserPasswordPath | ConvertTo-SecureString
$creds = New-Object -typename System.Management.Automation.PSCredential -ArgumentList $Username,$Password
$tfsServer = New-Object System.Uri("https://myaccount.visualstudio.com")
$tfsCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($tfsServer,$creds)
$tfsCollection.Authenticate()
"***************** 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
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

SecureStrings基于机器/用户帐户,因此当我从 Powershell ISE作为我的帐户运行时,构建正常运行,而不是从构建服务器触发时(现在以NetworkService运行)。

我已经尝试关注这篇文章以创建密码文件为"网络服务",并尝试为安全字符串的键尝试,但在我的用户和网络服务下都无法使用任何工作。

我如何简单地存储将在运行脚本的用户中使用的凭据?

,或者这只是错误的方法,我应该以某种方式使用PAT?

构建允许您通过构建定义中的设置访问PAT令牌。这些是在生成PAT令牌上的,因此您无需在任何地方存储任何秘密。

对于在开发人员的计算机上运行脚本,您可以要求开发人员输入PAT或有其他逻辑,您可以在其中要求他提供用户名密码。

更多信息

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

更新(完整解决方案):

在您的构建中,您必须转到"选项",然后打开"允许脚本访问oauth token"。

您的最终脚本将看起来像以下内容。

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

最新更新