1
votes

In my current assignment, I am integrating terraform to our Azure DevOps CI/CD pipeline. My requirements are as follows:

  1. The creation of PR should trigger a build pipeline.
  2. A task in the build pipeline should publish a comment to the raised PR. The content of comment will be the terraform plan output i.e the new infrastructure that is going to be deployed.
  3. Once the PR is approved and code merged to master, a CD pipeline would be triggered and that will deploy the infrastructure to Azure.

Up until now, I am all sorted on 1 and 3 requirements but I have no clue how can I publish a comment on PR with the contents from terraform plan command. Is there any built-in task for this? If not how can I achieve this? Is this possible at all? If so, can someone point out a resource that can help or just show the same .yml file?

I have searched a lot but did not find anything. My guess is you cannot add a comment from the build pipeline. Need your suggestions.

1

1 Answers

1
votes

Add terraform plan output as PR comment in Azure Devops Build Pipeline

I am afraid there is no such a out of box way to Add terraform plan output as PR comment at this moment.

The workaround I am thinking of right now is invoke Rest API to create a PR comment with the contents from terraform plan command.

We could use the 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

to create comment to the PR. We could write the contents from terraform plan command as Request Body:

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

But above API need the pullRequestId. So, we also need another API to get the pullRequestId for current project Pull Requests - Get Pull Requests By Project:

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

It will return a series of pullRequestIds, then we could use powershell argument Select-Object -first 1 like: $LastPullRequestId= $pullRequestIds.value.id | Select-Object -first 1 to get the latest pullRequestId.

So, we could add two inline powershell task in the build pipeline to invoke Rest API to get the latest pullRequestId, then use this pullRequestId to create a PR comment.

Hope this helps.