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

  1. Log in to the Slack instance that you want to connect to Jenkins
  2. Click “Add Apps” (bottom-left, under Apps)
  3. Search for “Jenkins”
  4. Click “Add” on Jenkins CI app
  5. You’ll be asked to configure Jenkins CI. For the channel, select any - you can override the channels Jenkins messages in the pipelines themselves
  6. Copy the token generated here - you’ll need it later

Install Slack Plugin on Jenkins

  1. Locate the plugins.txt file in your Jenkins repo
  2. 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).

  1. Log in to AWS with the account where your CDK stack is created
  2. Navigate to Secrets Manager
  3. 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
  4. Copy the ARN of the secret
  5. 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:

Written by Dulcie Jackson (Full Stack Developer). Read more in Insights by Dulcie or check our their socials ,