Introduction

GitHub Actions is a powerful tool that allows you to automate workflows directly from your GitHub repository. One common use case is sending notifications to a Slack channel whenever a certain event occurs, such as a successful or failed build.

This blog post will walk you through the steps to set up Slack notifications in GitHub Actions, format the message with detailed information about the workflow run, and dynamically include details such as commit hashes, authors, and build duration.

Step-by-Step Guide to Set Up Slack Notifications Using Incoming Webhook

1. Setting Up a Slack Incoming Webhook

Before you can send notifications to Slack, you need to set up an Incoming Webhook:

  1. Create a Slack App: Go to the Slack API: Applications, and create a new app for your workspace.
  2. Enable Incoming Webhooks: Once the app is created, go to the "Incoming Webhooks" section, and click "Activate Incoming Webhooks".
  3. Create a Webhook URL: Click on "Add New Webhook to Workspace", select the channel you want to post to and click "Allow". This will generate a Webhook URL.
  4. Store Your Webhook URL in GitHub Secrets: Copy the Webhook URL, and add it to your GitHub repository as a secret:
    • Go to your GitHub repository.
    • Click on Settings > Secrets and variables > Actions.
    • Click New repository secret and add a new secret named SLACK_WEBHOOK_URL with your Webhook URL as the value.

2. Creating Your GitHub Actions Workflow

Next, you'll create a GitHub Actions workflow file to send notifications to Slack. Here's a step-by-step breakdown of the YAML configuration:

2.1 Basic Setup

Create a new file in your repository under .github/workflows/slack_notification.yml.

name: Slack Notification
run-name: Pushing notification on Slack channel

on: [push]

2.2 Define the Jobs

Next, define the job that will send the Slack notification:

jobs:
  Notify-Slack-Channel:
    runs-on: ubuntu-latest

2.3 Calculate Build Start Time

To dynamically calculate the build duration, we first capture the build start time:

steps:
  - name: Calculate build start time
    id: build_start_time
    run: echo "BUILD_START_TIME=$(date +%s)" >> $GITHUB_ENV

2.4 Checkout Code

To ensure that the workflow has access to the repository’s code, use the checkout action:

  - name: Checkout code
    uses: actions/checkout@v2

2.5 Calculate Build Duration

Calculate the time taken for the job to complete:

  - name: Calculate build duration
    id: calculate_duration
    run: |
      end_time=$(date +%s)
      duration=$((end_time - $BUILD_START_TIME))
      echo "duration=$duration" >> $GITHUB_ENV
      echo "::set-output name=duration::$duration"

2.6 Get Short Commit Hash

To shorten the commit hash to just the first 7 characters:

  - name: Get short commit hash
    id: short_commit
    run: echo "SHORT_SHA=${GITHUB_SHA:0:7}" >> $GITHUB_ENV

2.7 Send Slack Notification

Finally, use the slackapi/slack-github-action to send the formatted Slack message:

  - name: Send custom JSON data to Slack workflow
    id: slack
    uses: slackapi/[email protected]
    with:
      payload: |
        {
          "blocks": [
            {
              "type": "section",
              "text": {
                "type": "mrkdwn",
                "text": "*:white_check_mark: Succeeded GitHub Actions*"
              }
            },
            {
              "type": "section",
              "fields": [
                {
                  "type": "mrkdwn",
                  "text": "*Repo*\n<https://github.com/${{ github.repository }}|${{ github.repository }}>"
                },
                {
                  "type": "mrkdwn",
                  "text": "*Commit*\n<${{ github.event.head_commit.url }}|${{ env.SHORT_SHA }}>"
                },
                {
                  "type": "mrkdwn",
                  "text": "*Author*\n${{ github.event.head_commit.author.name }}"
                },
                {
                  "type": "mrkdwn",
                  "text": "*Job*\n`${{ github.job }}`"
                },
                {
                  "type": "mrkdwn",
                  "text": "*Event Name*\n`${{ github.event_name }}`"
                },
                {
                  "type": "mrkdwn",
                  "text": "*Workflow*\n`${{ github.workflow }}`"
                },
                {
                  "type": "mrkdwn",
                  "text": "*Build Logs*\n<${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|View Logs>"
                },
                {
                  "type": "mrkdwn",
                  "text": "*Took*\n`${{ steps.calculate_duration.outputs.duration }} sec`"
                },
                {
                  "type": "mrkdwn",
                  "text": "*Message*\n${{ github.event.head_commit.message }}"
                }
              ]
            }
          ]
        }
    env:
      SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
      SLACK_WEBHOOK_TYPE: INCOMING_WEBHOOK

This is how the Slack notification looks like -

Key Features

Conclusion

By following the steps above, you can automate Slack notifications from GitHub Actions to keep your team informed about the status of your workflows. The notification is dynamically populated with key information about the run, short commit hashes, and build durations, providing a comprehensive overview directly in Slack. Now, you're all set to keep your team updated with every push!

Feel free to share this post with anyone who might find it useful.

Happy automating! 🚀