【问题标题】:Add terraform plan output as PR comment in Azure Devops Build Pipeline在 Azure Devops Build Pipeline 中添加 terraform 计划输出作为 PR 注释
【发布时间】:2020-03-10 19:11:23
【问题描述】:

在我当前的任务中,我正在将 terraform 集成到我们的 Azure DevOps CI/CD 管道中。我的要求如下:

  1. PR 的创建应触发构建管道。
  2. 构建管道中的任务应向提出的 PR 发布评论。评论内容将 是地形计划输出,即将要部署的新基础设施。
  3. 一旦 PR 获得批准并将代码合并到 master,CD 管道将被触发,这将 将基础结构部署到 Azure。

到目前为止,我都按照 1 和 3 的要求进行了排序,但我不知道如何使用 terraform plan 命令的内容在 PR 上发表评论。是否有任何内置任务?如果没有,我怎么能做到这一点?这可能吗?如果是这样,有人可以指出可以提供帮助的资源还是只显示相同的 .yml 文件?

我搜索了很多,但没有找到任何东西。我的猜测是您无法从构建管道中添加评论。需要你的建议。

【问题讨论】:

标签: azure-devops terraform devops


【解决方案1】:

在 Azure Devops Build Pipeline 中添加 terraform 计划输出作为 PR 注释

恐怕目前还没有这种开箱即用的方式来添加 terraform plan output 作为 PR 评论。

我现在正在考虑的解决方法是调用 Rest API 以使用来自 terraform plan 命令的内容创建 PR 评论。

我们可以使用 Rest API Pull Request Thread Comments - Create:

POST https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/pullRequests/{pullRequestId}/threads/{threadId}/comments?api-version=5.1

创建对 PR 的评论。我们可以将 terraform plan 命令中的内容写为请求正文:

{
  "content": "YourContentsFromTerraformPlan ",
  "parentCommentId": 1,
  "commentType": 1
}

但以上 API 需要pullRequestId。因此,我们还需要另一个 API 来获取当前项目的 pullRequestId Pull Requests - Get Pull Requests By Project

GET https://dev.azure.com/{organization}/{project}/_apis/git/pullrequests?api-version=5.1

它会返回一系列 pullRequestIds,然后我们可以使用 powershell 参数Select-Object -first 1 like: $LastPullRequestId= $pullRequestIds.value.id | Select-Object -first 1 来获取最新的pullRequestId

因此,我们可以在构建管道中添加两个内联 powershell 任务来调用 Rest API 以获取最新的 pullRequestId,然后使用此 pullRequestId 创建 PR 评论。

希望这会有所帮助。

【讨论】:

  • 由于是PR触发的构建,pullRequestId也可以通过预定义变量$(System.PullRequest.PullRequestId)获取
猜你喜欢
  • 2020-12-20
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
  • 2019-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多