使用 $(System.AccessToken) 在 Azure DevOps 构建管道上使用私有 git 存储库中的 tox 安装包

问题描述

在 Azure DevOps 上的构建过程中,我尝试使用 tox 从私有 git 存储库安装包,但它出错了

Collecting git+https://****@<company>.visualstudio.com/<team>/_git/<repo_name>@<branch>
  cloning https://****@<company>.visualstudio.com/<team>/_git/<repo_name> (to revision <branch>) to c:\users\vssadm~1\appdata\local\temp\pip-req-build-xpl77xit
  Running command git clone -q 'https://****@<company>.visualstudio.com/<team>/_git/<repo_name>' 'C:\Users\VSSADM~1\AppData\Local\Temp\pip-req-build-xpl77xit'
  fatal: Cannot prompt because user interactivity has been disabled.
  fatal: Could not read Password for 'https://$(System.Accesstoken)@<company>.visualstudio.com': terminal prompts disabled

tox.ini 设置为

passenv = *
deps = 
  git+https://$(System.Accesstoken)@<company>.visualstudio.com/<team>/_git/<repo_name>@<branch>

我已确保 Azure DevOps 构建代理用户 存储库具有读取权限,并且已选中“允许脚本访问 OAuth 令牌”。

当我创建一个脚本任务来简单地运行 pip install git+https://$(System.Accesstoken)@<company>.visualstudio.com/<team>/_git/<repo_name>@<branch> 时,它会成功安装。

有没有办法将 $(System.Accesstoken) 与 tox 结合使用?

解决方法

在 tox.ini 中,不要使用 $(System.AccessToken),而是使用 {env:SYSTEM_ACCESSTOKEN}

Azure DevOps 管道允许从其预定义的管道变量 System.AccessToken 或环境变量中获取访问令牌。管道变量可用于构建定义或任务。

在尝试在 tox.ini 中使用 $(System.AccessToken) 的情况下,该构建变量不会被交换,因为 tox 是直接读取文件并且仅使用该字符串而不进行任何替换。由于日志显示 Collecting git+https://****@<company>.visualstudio.com,这似乎是替代,但这只是 DevOps 看到 Collecting git+https://$(System.AccessToken)@<company>.visualstudio.com 并在打印到日志之前进行交换。也请注意在它写入的最后一个致命日志中 $(System.AccessToken) fatal: could not read Password for 'https://$(System.AccessToken)@<company>.visualstudio.com': terminal prompts disabled

Azure DevOps 使这些管道变量可用作环境变量。对于 System.AccessToken,此环境变量为 SYSTEM_ACCESSTOKEN。要访问 tox 中的环境变量,语法为 {env:KEY}。因此,要通过 tox 访问 System.AccessToken,请使用 {env:SYSTEM_ACCESSTOKEN}:

passenv = *
deps = 
  git+https://{env:SYSTEM_ACCESSTOKEN}@<company>.visualstudio.com/<team>/_git/<repo_name>@<branch>