DEV Community

iainrough
iainrough

Posted on

Send Slack Notification via InvokeRESTAPI@1 - Azure DevOps Tricks #2

Need to send a slack notification from an Azure DevOps pipeline? The InvokeRESTAPI@1 task is one of the most versatile and useful in Azure DevOps. It handles sending messages to Slack in a couple of lines of YAML.


    - task: InvokeRESTAPI@1
      displayName: Slack
      inputs:
        connectionType: 'connectedServiceName'
        serviceConnection: 'Slack'
        method: 'POST'
        body: $body
        urlSuffix: $urlSuffix
        waitForCompletion: 'false'

Enter fullscreen mode Exit fullscreen mode
The finshed YAML Task

The Service Connection

Project Settings > Pipelines > Service connections

The service connection is where we define the URL we are going to post to. For this we will use the Generic Service Connection. You navigate to Project Settings > Pipelines > Service connections or append this string after your project name in the URL _settings/adminservices

Create a Generic Service Connection

The fields we need to fill:

Server URL: https://hooks.slack.com/services/
Service Connection Name: Slack
Description: A Generic Slack Service connection.


The other Variables in the task

$body: You can either generate this variable or Input the body inline. Here is an example body:


{
   "attachments":[
      {
         "mrkdwn_in":[
            "text"
         ],
         "color":"#36a64f",
         "pretext":"New Deployment",
         "title":"$(Pipeline.WebSiteName) deployed",
         "title_link":"$(Pipeline.WebSiteName)",
         "fields":[
            {
               "title":"Version",
               "value":"$(CurrentRelease)",
               "short":true
            },
            {
               "title":"Release Notes",
               "value":"<$(Pipeline.WebSiteAddress)/ReleaseNotes/$(PullId)>",
               "short":true
            },
            {
               "title":"Trigger",
               "value":"Pull Request",
               "short":true
            }
         ]
      }
   ]
}

Enter fullscreen mode Exit fullscreen mode
Example Slack Body

So here you can see we are passing variables like the PullId and using them in the Slack Message. The ability to use any of the variables in the pipeline allows for detailed Slack Messages.

$urlSuffix: T778W530Z/B021W918BNH/HQIPtyCfACfs5WVXg1w7b4Xk

This is the magic bit for Slack, I would recommend storing this value as secret or getting it from your Azure Key Vault.

Simple Quick and Easy.

Top comments (0)