Code me a gitlabci.yml and an accompanying bash script that has a job that connects to…
- User
Code me a gitlabci.yml and an accompanying bash script that has a job that connects to slack and sends a message if a build fails
- Assistant
Code me a gitlabci.yml and an accompanying bash script that has a job that connects to slack and sends a message if a build fails
Sure, I can help you with a sample .gitlab-ci.yml configuration and a Bash script to achieve this.
First, you need to set up an incoming webhook in Slack:
https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX. Keep this secure.Now, let's configure your .gitlab-ci.yml:
stages:
- build
variables:
SLACK_WEBHOOK: "Your webhook URL here"
after_script:
- if [ "$CI_PIPELINE_STATUS" = "failed" ]; then ./notify_slack.sh "Build FAILED in <$CI_PROJECT_URL/pipelines/$CI_PIPELINE_ID|pipeline> for project <$CI_PROJECT_URL|$CI_PROJECT_NAME> by $GITLAB_USER_NAME"; fi
build_job:
stage: build
script:
- echo "Building the project..."
# Replace the following line with your actual build commands
- exit 1 # Simulated build failure for demonstration purposes
rules:
- when: on_failure
Now, create a file called notify_slack.sh in the same directory as your .gitlab-ci.yml with the following content:
#!/bin/bash
# The first argument to this script is the message to be sent to Slack
MESSAGE=$1
# Your Slack webhook URL (it's best to keep this in a GitLab CI/CD variable for security)
WEBHOOK_URL=$SLACK_WEBHOOK
# Send the message to Slack
curl -sS --request POST --url "$WEBHOOK_URL" --header 'Content-type: application/json' --data "{'text':'$MESSAGE'}"
Make sure to replace "Your webhook URL here" with the actual Slack webhook URL in the .gitlab-ci.yml file, and also make sure it's set securely as a CI/CD variable rather than hardcoding it into the script. The --data in the curl command will transfer the message as a JSON payload to your Slack channel.
Lastly, set the script to be executable by running the following command in your repository:
chmod +x notify_slack.sh
Commit the .gitlab-ci.yml and notify_slack.sh to your repository. Now, if the build fails, the after_script directive will trigger the notify_slack.sh script and send a notification to your Slack workspace. Remember that the environment variables like $CI_PROJECT_URL and $CI_PIPELINE_ID are provided by GitLab for your convenience.
Please note that to keep your Slack webhook URL secret, it's recommended to set it as an environment variable in the GitLab CI/CD settings rather than putting it directly into your .gitlab-ci.yml or the script.