paint-brush
How to Send Detailed Slack Notifications From GitHub Actionsby@saurabhd
722 reads
722 reads

How to Send Detailed Slack Notifications From GitHub Actions

by Saurabh DhariwalSeptember 8th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

GitHub Actions is a powerful tool for automating workflows directly within your GitHub repositories. One common use case is to send notifications to a Slack channel whenever specific events occur in your repository. This guide will show you how to set up detailed Slack notifications using GitHub Actions.
featured image - How to Send Detailed Slack Notifications From GitHub Actions
Saurabh Dhariwal HackerNoon profile picture

GitHub Actions is a powerful tool for automating workflows directly within your GitHub repositories. One common use case is to send notifications to a Slack channel whenever specific events occur in your repository, such as successful builds, failed tests, or completed deployments. This guide will show you how to set up detailed Slack notifications using GitHub Actions, complete with examples to help you get started.

1. Why Send Slack Notifications from GitHub Actions?

Integrating Slack notifications with GitHub Actions is beneficial for several reasons:

  • Real-time updates: Keep your team informed about the status of your CI/CD pipelines.


  • Centralized communication: All relevant information can be sent directly to your team’s Slack channels, avoiding the need to constantly check GitHub.


  • Enhanced collaboration: Immediate notifications can prompt quick actions or discussions, reducing bottlenecks and improving efficiency.

2. Prerequisites

Before we dive into the setup, ensure you have the following:

  • A GitHub repository where you want to set up the workflow.
  • A Slack workspace and a channel where you want to send notifications.
  • Slack app permissions to create incoming webhooks in your workspace.

3. Step 1: Create a Slack App and Webhook URL

To send notifications to Slack, you need to create a webhook URL through the Slack API.

  1. Create a Slack App:

    • Go to the Slack API page. Click on “Create an App.”
    • Choose “From scratch” and give your app a name, then select the Slack workspace where you want to install the app

    2. Create an Incoming Webhook:

    • Navigate to “Incoming Webhooks” under the “Features” section on the left sidebar.
    • Toggle the “Activate Incoming Webhooks” switch. Click on “Add New Webhook to Workspace.”
    • Choose the channel where you want the notifications to be sent, and click “Allow.”
    • Copy the Webhook URL provided. This URL will be used in your GitHub Actions workflow to send notifications.

4. Step 2: Set Up a GitHub Actions Workflow

Now that you have a Slack Webhook URL, you can create a GitHub Actions workflow to send notifications.

  1. Create a .github/workflows/ directory: If your repository doesn’t have this directory, create it in the root of your project.
  2. Create a new YAML file: Create a new file in the .github/workflows/ directory. For example, you can name it slack-notifications.yml.
  3. Basic Workflow Example: Here's a simple example that sends a Slack notification whenever code is pushed to the main branch.
name: Send Slack Notification

on:
  push:
    branches:
      - main

jobs:
  notify:
    runs-on: ubuntu-latest

    steps:
      - name: Send Slack Notification
        env:
          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
        run: |
          curl -X POST -H 'Content-type: application/json' --data '{"text":"A new push has been made to the main branch."}' $SLACK_WEBHOOK_URL

5. Step 3: Store Your Webhook URL as a Secret

To keep your Slack Webhook URL secure, store it as a GitHub Secret.

  1. Add the Secret to GitHub:
    • Go to your GitHub repository.
    • Navigate to Settings > Secrets and variables > Actions.
    • Click on “New repository secret.”
    • Name the secret SLACK_WEBHOOK_URL and paste your Webhook URL into the value field.
    • Click “Add secret.”

6. Step 4: Customize the Slack Notification

The example above sends a very basic message. However, Slack messages can be much more detailed and formatted using Block Kit.


Example of a Detailed Slack Notification:

name: Send Detailed Slack Notification

on:
  push:
    branches:
      - main

jobs:
  notify:
    runs-on: ubuntu-latest

    steps:
      - name: Send Detailed Slack Notification
        env:
          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
        run: |
          curl -X POST -H 'Content-type: application/json' --data '{
            "blocks": [
              {
                "type": "section",
                "text": {
                  "type": "mrkdwn",
                  "text": "*New Push to Main Branch*"
                }
              },
              {
                "type": "section",
                "fields": [
                  {
                    "type": "mrkdwn",
                    "text": "*Repository:*\n'${{ github.repository }}'"
                  },
                  {
                    "type": "mrkdwn",
                    "text": "*Branch:*\n'${{ github.ref }}'"
                  },
                  {
                    "type": "mrkdwn",
                    "text": "*Commit Message:*\n'${{ github.event.head_commit.message }}'"
                  },
                  {
                    "type": "mrkdwn",
                    "text": "*Committer:*\n'${{ github.event.head_commit.committer.name }}'"
                  }
                ]
              }
            ]
          }' $SLACK_WEBHOOK_URL

Explanation:

  • Blocks: This section allows you to use Slack’s Block Kit to create more sophisticated and visually appealing messages.


  • Text Fields: We use ${{ github.repository }}, ${{ github.ref }}, and other GitHub context variables to dynamically insert information into the Slack message.


This will send a detailed notification to your Slack channel every time there’s a push to the main branch, including information like the repository name, branch, commit message, and committer.

7. Step 5: Trigger Notifications on Specific Events

GitHub Actions can be triggered by various events beyond just a push to a branch. Some common triggers include:


  • Pull Requests:

    on:
      pull_request:
        branches:
          - main
    
    


Workflow Failures:

on:
  workflow_run:
    workflows: ["CI"]
    types:
      - completed


Scheduled Events:

on:
  schedule:
    - cron: '0 9 * * 1' # Every Monday at 9 AM


Example for Workflow Failure Notification: This example sends a notification only if a workflow fails.

name: Notify on Failure

on:
  workflow_run:
    workflows: ["CI"]
    types:
      - completed

jobs:
  notify_on_failure:
    if: ${{ failure() }}
    runs-on: ubuntu-latest

    steps:
      - name: Notify Slack on Failure
        env:
          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
        run: |
          curl -X POST -H 'Content-type: application/json' --data '{
            "text": ":x: *CI Workflow Failed*",
            "blocks": [
              {
                "type": "section",
                "text": {
                  "type": "mrkdwn",
                  "text": "*Workflow:* CI\n*Status:* Failed\n*Repository:* ${{ github.repository }}"
                }
              }
            ]
          }' $SLACK_WEBHOOK_URL

This sends a failure notification with details about the workflow and the repository, ensuring your team is immediately aware of any issues.

8. Handling Advanced Use Cases

You may want to send different notifications depending on the type of event or the result of the action. For instance, you might want to send one type of message for a successful build and another for a failure.


Example: Conditional Notifications:

name: Notify on Success or Failure

on:
  push:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout Code
        uses: actions/checkout@v2

      - name: Run Tests
        run: |
          echo "Running tests..."
          # Simulate a test failure
          exit 1

  notify:
    needs: build
    runs-on: ubuntu-latest

    steps:
      - name: Notify Slack
        env:
          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
        run: |
          if [ "${{ needs.build.result }}" == "success" ]; then
            curl -X POST -H 'Content-type: application/json' --data '{"text":"Build Succeeded!"}' $SLACK_WEBHOOK_URL;
          else
            curl -X POST -H 'Content-type: application/json' --data '{"text":"Build Failed!"}' $SLACK_WEBHOOK_URL;
          fi

In this example, the notification is sent based on whether the build was successful or failed.

9. Best Practices

To ensure that your Slack notifications from GitHub Actions are effective, follow these best practices:


  • Use Descriptive Messages: Clearly describe the event, including the repository, branch, and any other relevant details.


  • Leverage Slack Formatting: Use Block Kit to make your messages more readable and organized.


  • Control Frequency: Avoid overwhelming your Slack channel with too many notifications. Use conditions to only send important updates.


  • Test Your Workflow: Before rolling it out to the whole team, test your GitHub Actions and Slack notifications in a separate branch or repository.