我目前正在为 Azure DevOps 创建管道以验证 Terraform 配置并将其应用于不同的订阅。
我的 Terraform 配置使用模块,这些模块“托管”在与 Terraform 配置相同的 Azure DevOps 项目中的其他存储库中。
遗憾的是,当我尝试执行 terraform init
来获取这些模块时,管道任务“挂起”在那里等待凭据输入。
按照 Pipeline Documentation on Running Git Commands in a script 中的建议我尝试使用 persistCredentials:true
属性添加 checkout
步骤。
从我在任务日志中看到的(见下文),凭据信息专门添加到当前存储库,不能用于其他存储库。
添加persistCredentials:true
时执行的命令
2018-10-22T14:06:54.4347764Z ##[command]git config http.https://my-org@dev.azure.com/my-org/my-project/_git/my-repo.extraheader "AUTHORIZATION: bearer ***"
terraform init 任务的输出
2018-10-22T14:09:24.1711473Z terraform init -input=false
2018-10-22T14:09:24.2761016Z Initializing modules...
2018-10-22T14:09:24.2783199Z - module.my-module
2018-10-22T14:09:24.2786455Z Getting source "git::https://my-org@dev.azure.com/my-org/my-project/_git/my-module-repo?ref=1.0.2"
如何设置 git 凭据以用于其他存储库?
最佳答案
基本上有两种方法可以做到这一点。
先决条件
确保您已阅读并根据需要应用 Enable scripts to run Git commands “在脚本中运行 Git 命令”文档中的部分。
解决方案 #1:在管道运行时动态插入 System.AccessToken
(或 PAT,但我不推荐它)
您可以通过以下方式之一:
- 在您的代码中插入一个替换 token ,例如
__SYSTEM_ACCESSTOKEN__
(如 Nilsas 建议的那样)并使用一些 token 替换代码或qetza.replacetokens.replacetokens-task.replacetokens
插入值的任务。此解决方案的缺点是,当您在本地运行terraform
时,您还必须替换 token 。 - 使用一些代码将所有
git::https://dev.azure.com
文本替换为git::https://YOUR_ACCESS_TOKEN@dev.azure.com
.
我通过使用以下 bash 任务脚本来使用第二种方法(它搜索 terragrunt
文件,但您可以在不做太多更改的情况下适应 terraform
文件):
- bash: |
find $(Build.SourcesDirectory)/ -type f -name 'terragrunt.hcl' -exec sed -i 's~git::https://dev.azure.com~git::https://$(System.AccessToken)@dev.azure.com~g' {} \;
Abu Belai提供一个 PowerShell 脚本来做类似的事情。
但是,如果您的 terraform
模块 git
存储库中的模块在另一个 git
存储库中调用自己的模块,则此类解决方案不起作用,这是我们的案例。
解决方案 #2:在 terraform
模块 git
repos
的 url 的 extraheader
中全局添加访问 token
这样,所有由您的代码直接调用或由被调用模块的代码间接调用的模块的存储库都将能够使用您的访问 token 。为此,我在您的 terraform
/terragrunt
调用之前添加了以下步骤:
- bash: |
git config --global http.https://dev.azure.com/<your-org>/<your-first-repo-project>/_git/<your-first-repo>.extraheader "AUTHORIZATION: bearer $(System.AccessToken)"
git config --global http.https://dev.azure.com/<your-org>/<your-second-repo-project>/_git/<your-second-repo>.extraheader "AUTHORIZATION: bearer $(System.AccessToken)"
您需要为每个调用的 git
存储库设置 extraheader
。
请注意,如果您的管道在同一工作人员上多次设置 extraheader
,则您可能需要在 terraform
调用后取消设置 extraheader
。这是因为 git
可能会与多个 extraheader
声明混淆。您可以通过添加以下步骤来执行此操作:
- bash: |
git config --global --unset-all http.https://dev.azure.com/<your-org>/<your-first-repo-project>/_git/<your-first-repo>.extraheader
git config --global --unset-all http.https://dev.azure.com/<your-org>/<your-second-repo-project>/_git/<your-second-repo>.extraheader
关于azure-devops - 在 Azure Pipelines 构建中使用 Azure Repos git 模块源进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52931994/