> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Create a Shared Library for Slack Notification

> How to create a Jenkins Shared Library to centralize and reuse Slack notification logic across pipelines for consistent, maintainable notifications.

In this lesson you'll centralize Slack notification logic into a Jenkins Shared Library so it can be reused across multiple pipelines. Moving custom Groovy notification code out of individual Jenkinsfiles and into a shared library improves maintainability, reduces duplication, and makes it easier to apply consistent notification behavior across projects.

Why use a Shared Library?

* Reuse the same notification logic across many repositories and jobs.
* Keep Jenkinsfiles small and focused on pipeline structure.
* Update notification behavior in one place rather than across dozens of Jenkinsfiles.

Example: inline notification function you might have inside a Jenkinsfile

```groovy theme={null}
// Example inline function in a Jenkinsfile
def slackNotificationMethod(String buildStatus = 'STARTED') {
    def color

    if (buildStatus == 'SUCCESS') {
        color = '#47ec05'
    } else if (buildStatus == 'UNSTABLE') {
        color = '#d5ee0d'
    } else {
        color = '#ec2805'
    }

    def msg = "${buildStatus}: ${env.JOB_NAME} #${env.BUILD_NUMBER}:\n${env.BUILD_URL}"

    slackSend(color: color, message: msg)
}
```

That works for a single repository. To reuse the function across many pipelines, create a Shared Library repository and expose the logic as a global step under `vars/`.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/XTR6jhnagwAdsrpZ/images/Advanced-Jenkins/Shared-Libraries-in-Jenkins/Create-a-Shared-Library-for-Slack-Notification/gitea-new-repository-form-owner-dropdown.jpg?fit=max&auto=format&n=XTR6jhnagwAdsrpZ&q=85&s=d8bf1f1ce19be59010dd4ff708ceb2b1" alt="A dark-themed web screenshot of a &#x22;New Repository&#x22; form in a Git hosting UI (Gitea), showing an open Owner dropdown with options like &#x22;gitea-admin&#x22; and &#x22;dasher-org.&#x22; The form includes fields for repository name, visibility, description, .gitignore and license." width="1920" height="1080" data-path="images/Advanced-Jenkins/Shared-Libraries-in-Jenkins/Create-a-Shared-Library-for-Slack-Notification/gitea-new-repository-form-owner-dropdown.jpg" />
</Frame>

Create a new Git repository in your organization (for example, `shared-libraries`). Initialize it and push an initial commit:

```bash theme={null}
# Initialize and push a new repository
touch README.md
git init
git checkout -b main
git add README.md
git commit -m "first commit"
git remote add origin http://64.227.187.25:5555/dasher-org/shared-libraries.git
git push -u origin main
```

Always consult the official Jenkins documentation for Shared Libraries for configuration details and the expected directory layout:

* Jenkins Shared Libraries documentation: [https://www.jenkins.io/doc/book/pipeline/shared-libraries/](https://www.jenkins.io/doc/book/pipeline/shared-libraries/)

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/XTR6jhnagwAdsrpZ/images/Advanced-Jenkins/Shared-Libraries-in-Jenkins/Create-a-Shared-Library-for-Slack-Notification/jenkins-shared-libraries-pipeline-doc-dark.jpg?fit=max&auto=format&n=XTR6jhnagwAdsrpZ&q=85&s=703c256f7b26cb1e7e0824a76a7ace3e" alt="A screenshot of the Jenkins documentation page showing the &#x22;Extending with Shared Libraries&#x22; section from the Pipeline User Handbook, with a left navigation menu and a Table of Contents on the right. The page uses a dark theme and displays explanatory text about shared libraries for Jenkins Pipelines." width="1920" height="1080" data-path="images/Advanced-Jenkins/Shared-Libraries-in-Jenkins/Create-a-Shared-Library-for-Slack-Notification/jenkins-shared-libraries-pipeline-doc-dark.jpg" />
</Frame>

Shared libraries use a specific layout. A minimal structure looks like this:

```text theme={null}
(root)
+- src                      # Groovy source files (compiled classes)
|   +- org
|   |   +- foo
|   |   |   +- Bar.groovy   # for org.foo.Bar class
+- vars
|   +- foo.groovy           # for global 'foo' variable/step
|   +- foo.txt              # help for 'foo' variable
+- resources                # resource files (for classes to load)
|   +- org
|   |   +- foo
|   |   |   +- bar.json     # static helper data for org.foo.Bar
```

Directory purpose at a glance:

| Directory   | Purpose                                        | Example                              |
| ----------- | ---------------------------------------------- | ------------------------------------ |
| `src`       | Compiled Groovy classes, organized by package  | `src/org/foo/Bar.groovy`             |
| `vars`      | Global step scripts (each file exposes a step) | `vars/foo.groovy` and `vars/foo.txt` |
| `resources` | Static files that your classes may load        | `resources/org/foo/bar.json`         |

To create a step-style global function (so you can call it like a built-in step such as `sh` or `git`), add a Groovy file under `vars/` and define a `call` method.

Create the file `vars/slackNotification.groovy` in your `shared-libraries` repository.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/XTR6jhnagwAdsrpZ/images/Advanced-Jenkins/Shared-Libraries-in-Jenkins/Create-a-Shared-Library-for-Slack-Notification/dasher-shared-libraries-slacknotification-code.jpg?fit=max&auto=format&n=XTR6jhnagwAdsrpZ&q=85&s=ca123244f16dc604110b3704a153b0c0" alt="A dark-themed repository webpage (dasher-org / shared-libraries) showing a code view with a filename input containing &#x22;slackNotification&#x22; and a &#x22;New File&#x22; button. Browser tabs and the address bar are visible at the top." width="1920" height="1080" data-path="images/Advanced-Jenkins/Shared-Libraries-in-Jenkins/Create-a-Shared-Library-for-Slack-Notification/dasher-shared-libraries-slacknotification-code.jpg" />
</Frame>

Example implementation for `vars/slackNotification.groovy`. This exposes a `slackNotification(...)` step that your pipelines can call directly:

```groovy theme={null}
// vars/slackNotification.groovy
def call(String buildStatus = 'STARTED') {
    def color
    if (buildStatus == 'SUCCESS') {
        color = '#47ec05'
    } else if (buildStatus == 'UNSTABLE') {
        color = '#d5ee0d'
    } else {
        color = '#ec2805'
    }

    def msg = "${buildStatus}: ${env.JOB_NAME} #${env.BUILD_NUMBER}:\n${env.BUILD_URL}"

    slackSend(color: color, message: msg)
}
```

<Callout icon="lightbulb" color="#1CB2FE">
  Define `call` in `vars/<name>.groovy` to allow invoking the library step directly as `<name>(...)` from a Pipeline (this mirrors built-in steps like `sh` or `git`).
</Callout>

After committing the repository and pushing the file, make the Shared Library available to Jenkins.

Option 1 — Configure as a Global Pipeline Library

* In Jenkins: Manage Jenkins → Configure System → Global Pipeline Libraries
* Add your `shared-libraries` repository with a name (for example, `shared-libraries`) so it can be referenced by name from any pipeline.

Option 2 — Use `@Library` annotation per-repository

* Add `@Library('<library-name>') _` at the top of a Jenkinsfile to import the library for that pipeline.

Example usage in a Jenkinsfile (after the shared library is configured):

```groovy theme={null}
@Library('shared-libraries') _

pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
                // build steps ...
            }
        }
    }

    post {
        success {
            script {
                // call the shared library step
                slackNotification('SUCCESS')
            }
        }
        unstable {
            script {
                slackNotification('UNSTABLE')
            }
        }
        failure {
            script {
                slackNotification('FAILURE')
            }
        }
    }
}
```

Next steps and references

* Review the Jenkins documentation on Shared Libraries to learn about loading strategies, caching, and versioning: [https://www.jenkins.io/doc/book/pipeline/shared-libraries/](https://www.jenkins.io/doc/book/pipeline/shared-libraries/)
* Consider adding a `vars/slackNotification.txt` file to document usage/help for the step.
* If your notification logic requires credentials or tokens (e.g., Slack webhook), use Jenkins Credentials and refer to them securely from your library code.

Further reading and references

* Jenkins Shared Libraries — [https://www.jenkins.io/doc/book/pipeline/shared-libraries/](https://www.jenkins.io/doc/book/pipeline/shared-libraries/)
* Jenkins Pipeline Syntax — [https://www.jenkins.io/doc/book/pipeline/syntax/](https://www.jenkins.io/doc/book/pipeline/syntax/)

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/advanced-jenkins/module/7e7be52f-69f5-496b-8a46-322d6b8df0ce/lesson/7cd4292e-6460-4a27-9271-c70d332a22f0" />
</CardGroup>
