Notify via Discord when a Jenkins job or pipeline has finished.

Tiempo de lectura: 3 minutos

Reading time: 3 minutes

Today I’m going to show you how we can send a notification to Discord when a Jenkins job is finished.

First, we install the Discord Notifier plugin: https://plugins.jenkins.io/discord-notifier/

We search for it in Manage Jenkins > Available Plugins > Discord Notifier

We install it by clicking on Install Without restart.

Now we go to the Job where we want to use it and select Add post-build action:

And select Discord Notifier:

Now we add the Discord webhook. To do this, we select the channel where we want to send the notification:

We click on Settings > Integrations > Webhooks

New webhook:

We add a name and copy the URL of the created webhook.

We add it in the installed plugin and click Save.

And now Jenkins will notify us when a deployment is done.

If we want to add it to a pipeline, we need to add the following code to the pipeline (we add it after stages):

post {
        success {
            discordSend description: "Jenkins Pipeline Build", footer: "Deployment completed successfully", link: env.BUILD_URL, result: currentBuild.currentResult, title: JOB_NAME, webhookURL: "Webhook URL"
        }
        
        failure {
            discordSend description: "Jenkins Pipeline Error", footer: "Deployment failed", link: env.BUILD_URL, result: currentBuild.currentResult, title: JOB_NAME, webhookURL: "Webhook URL"
        }
    }

In webhook URL, we indicate the URL of the created Discord webhook.

We can also hide the webhook URL using Jenkins:

We go to Manage Jenkins > Manage credentials

We click on Global:

We add a new credential of type Secret Text:

In secret, we add the webhook URL, and in ID, the name we will use to retrieve it in our Jenkinsfile.

We save it. Now, to retrieve this variable in the Jenkinsfile, we put the following:

  environment {
        DISCORD_WEBHOOK = credentials('WEBHOOK')
    }

And we use it by calling this environment variable:

post {
        success {
            discordSend description: "Jenkins Pipeline Build", footer: "Deployment completed successfully", link: env.BUILD_URL, result: currentBuild.currentResult, title: JOB_NAME, webhookURL: "$DISCORD_WEBHOOK"
        }
        
        failure {
            discordSend description: "Jenkins Pipeline Error", footer: "Deployment failed", link: env.BUILD_URL, result: currentBuild.currentResult, title: JOB_NAME, webhookURL: "$DISCORD_WEBHOOK"
        }
    }

Leave a Comment