Sending custom Slack notification from GitLab at each Job or Stage

Sending custom notification for Slack channel after completion of each job
stages:
- build
- test
- deploy
build:
image: < image >
script: < build script >
variables:
- ENVIRONMENTNAME: "dev"
after_script:
- if [ ${CI_JOB_STATUS} == "success" ]; then EXIT_STATUS=0; else EXIT_STATUS=1; fi
- source ./slackscript.sh; share_slack_update_build

test:
image: < image >
script: < test script >
variables:
- ENVIRONMENTNAME: "dev"
after_script:
- if [ ${CI_JOB_STATUS} == "success" ]; then EXIT_STATUS=0; else EXIT_STATUS=1; fi
- source ./slackscript.sh; share_slack_update_test
deploy:
image: < image >
script: < test script >
variables:
- ENVIRONMENTNAME: "dev"
after_script:
- if [ ${CI_JOB_STATUS} == "success" ]; then EXIT_STATUS=0; else EXIT_STATUS=1; fi
- source ./slackscript.sh; share_slack_update_deploy
#!/bin/bashset -euo pipefailFAILURE=1
SUCCESS=0
SLACKWEBHOOKURL="https://hooks.slack.com/services/XXXXXX/YYYYYYY/aabbcc"function print_slack_summary_build() {local slack_msg_header
local slack_msg_body
local slack_channel
# Populate header and define slack channelsslack_msg_header=":x: *Build to ${ENVIRONMENTNAME} failed*"if [[ "${EXIT_STATUS}" == "${SUCCESS}" ]]; then
slack_msg_header=":heavy_check_mark: *Build to ${ENVIRONMENTNAME} succeeded*"
#slack_channel="$CHANNEL_TEST"
fi
cat <<-SLACK
{
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "${slack_msg_header}"
}
},
{
"type": "divider"
},
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*Stage:*\nBuild"
},
{
"type": "mrkdwn",
"text": "*Pushed By:*\n${GITLAB_USER_NAME}"
},
{
"type": "mrkdwn",
"text": "*Job URL:*\nGITLAB_REPO_URL/${CI_JOB_ID}"
},
{
"type": "mrkdwn",
"text": "*Commit URL:*\nGITLAB_REPO_URL$(git rev-parse HEAD)"
},
{
"type": "mrkdwn",
"text": "*Commit Branch:*\n${CI_COMMIT_REF_NAME}"
}
]
},
{
"type": "divider"
}
]
}
SLACK
}
function share_slack_update_build() {local slack_webhookslack_webhook="$SLACKWEBHOOKURL"curl -X POST \
--data-urlencode "payload=$(print_slack_summary_build)" \
"${slack_webhook}"
}
Template in Slack Application

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store