Using CASC to set up Slack messaging in Jenkins
Recently, I modified our Jenkins server so it’s able to send Slack messages to various channels to notify us of successful and failing builds on our projects. There are tons of tutorials on how to do this through the UI, but I struggled to find one that explained how to do it through Jenkins Configuration-as-Code (JCasC). In this tutorial, I’ll walk you through the steps you can take to get Slack messaging working for a Jenkins server using JCasC.
Note: this tutorial assumes that you have a working Jenkins server that is set up using JCasC. We also use CDK to manage our AWS resources, but the Slack messaging functionality here should work with any setup - you’ll just need to know how to inject secrets into your project. Our JCasC config section of the repo looks like this:
Set up Jenkins CI on Slack
- Log in to the Slack instance that you want to connect to Jenkins
- Click “Add Apps” (bottom-left, under Apps)
- Search for “Jenkins”
- Click “Add” on Jenkins CI app
- You’ll be asked to configure Jenkins CI. For the channel, select any - you can override the channels Jenkins messages in the pipelines themselves
- Copy the token generated here - you’ll need it later
Install Slack Plugin on Jenkins
- Locate the plugins.txt file in your Jenkins repo
- Add “slack” to the file - this references this plugin that allows us to send Slack messages from Jenkins
Configure Slack Plugin
If you’re not using CDK, this section might be a bit different for you. Essentially, you’ll want to store the token as a secret and import it into your Jenkins setup to be used in jenkins.yaml (as shown in step 6).
- Log in to AWS with the account where your CDK stack is created
- Navigate to Secrets Manager
- Create a new secret, with key “tokenID”. The value should be the token value you copied from Slack earlier. Name the secret jenkins-slack-token
- Copy the ARN of the secret
- In your CDK stack definition (or equivalent), update the container to add the SLACK_TOKEN secret retrieval from AWS Secrets Manager
6. In your jenkins.yaml, add the following sections:
Now the Slack plugin is all set up, and you’ll be able to use it to send messages from your pipelines!
Sending Slack Messages from a Pipeline
Send a slack message from a pipeline by adding this post section to an existing pipeline, and modifying the channel name, message and colours as you wish:
This will send Slack messages after a pipeline finishes executing, with different messages on success or failure. There are three inbuilt colours: good - green, warning - yellow and danger - red. You can also provide a hex code here to display a custom colour.
The messages look like this in Slack: