> ## 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.

# Demo Create Shared Library for Trivy Scan

> This tutorial guides you in creating a Jenkins Shared Library for running Trivy vulnerability scans in CI/CD pipelines.

In this tutorial, you’ll build a reusable Jenkins Shared Library to run [Trivy](https://github.com/aquasecurity/trivy) scans in your CI/CD pipelines. By isolating scanning logic in a library, you’ll eliminate duplication and enable versioned updates via Git feature branches.

## Prerequisites

| Requirement                 | Description                                           |
| --------------------------- | ----------------------------------------------------- |
| Jenkins Shared Library Repo | A Git repository to host your `vars/` functions       |
| Trivy CLI                   | Installed on your Jenkins agents or build environment |

## 1. Clone the Shared Library Repository

Start by cloning your existing shared-library project:

```bash theme={null}
git clone http://64.227.187.25:5555/dasher-org/shared-libraries.git
cd shared-libraries
ls
# You should see:
# vars
```

## 2. Create a Feature Branch

Work on a dedicated branch to isolate your changes:

```bash theme={null}
git checkout -b feature/trivy-scan
```

## 3. Review the Hardcoded Trivy Stage

In many pipelines, you’ll find a stage like this in the application’s `Jenkinsfile`:

```groovy theme={null}
stage('Trivy Vulnerability Scanner') {
  steps {
    sh '''
      trivy image my-org/app:$GIT_COMMIT \
        --severity LOW,MEDIUM,HIGH \
        --exit-code 0 \
        --quiet \
        --format json -o trivy-medium.json

      trivy image my-org/app:$GIT_COMMIT \
        --severity CRITICAL \
        --exit-code 1 \
        --quiet \
        --format json -o trivy-critical.json
    '''
  }
  post {
    always {
      // report conversion steps...
    }
  }
}
```

<Callout icon="triangle-alert" color="#FF6B6B">
  Hardcoding scanner commands in every `Jenkinsfile` is hard to maintain. Any change in flags or output formats would need updates in all pipelines.
</Callout>

## 4. Create the `TrivyScan.groovy` in `vars/`

Inside your shared-library’s `vars/` folder, add a new file:

```bash theme={null}
cd vars
touch TrivyScan.groovy
```

## 5. Define the `vulnerability` Function

Open `vars/TrivyScan.groovy` and add a method that accepts the Docker image name:

```groovy theme={null}
def vulnerability(String imageName) {
    sh """
      echo "🔒 Scanning image: ${imageName}"
      trivy image ${imageName} \
        --severity LOW,MEDIUM,HIGH \
        --exit-code 0 \
        --quiet \
        --format json -o trivy-medium.json

      trivy image ${imageName} \
        --severity CRITICAL \
        --exit-code 1 \
        --quiet \
        --format json -o trivy-critical.json
    """
}
```

<Callout icon="lightbulb" color="#1CB2FE">
  We use triple-double-quotes (`"""…"""`) in Groovy to allow `${imageName}` interpolation inside the shell script block.
</Callout>

## 6. Add the `reportsConverter` Function

Extend the same file with report conversion logic:

```groovy theme={null}
def reportsConverter() {
    sh '''
      trivy convert \
        --format template --template "@usr/local/share/trivy/templates/html.tpl" \
        --output trivy-medium.html trivy-medium.json

      trivy convert \
        --format template --template "@usr/local/share/trivy/templates/html.tpl" \
        --output trivy-critical.html trivy-critical.json

      trivy convert \
        --format template --template "@usr/local/share/trivy/templates/junit.tpl" \
        --output trivy-medium.xml trivy-medium.json

      trivy convert \
        --format template --template "@usr/local/share/trivy/templates/junit.tpl" \
        --output trivy-critical.xml trivy-critical.json
    '''
}
```

## 7. Commit and Push Your Changes

Save, commit, and push the new shared-library logic:

```bash theme={null}
git add vars/TrivyScan.groovy
git commit -m "feat: add TrivyScan shared library (vulnerability + reportsConverter)"
git push --set-upstream origin feature/trivy-scan
```

## 8. Consume the Shared Library in a Pipeline

In your application’s `Jenkinsfile`, load the library and call the functions:

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

pipeline {
  agent any
  stages {
    stage('Security Checks') {
      steps {
        TrivyScan.vulnerability("my-org/app:${env.GIT_COMMIT}")
        TrivyScan.reportsConverter()
      }
    }
  }
}
```

Now your security scan is centralized, versioned, and easy to update!

## References

* [Jenkins Shared Library Documentation][jenkins-shared-library]
* [Trivy – A Simple and Comprehensive Vulnerability Scanner][trivy-docs]
* [Jenkins Pipeline Syntax][jenkins-pipeline]

[jenkins-shared-library]: https://www.jenkins.io/doc/book/pipeline/shared-libraries/

[trivy-docs]: https://github.com/aquasecurity/trivy

[jenkins-pipeline]: https://www.jenkins.io/doc/book/pipeline/

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/certified-jenkins-engineer/module/b0fefde6-7fea-44da-9509-27007d27869f/lesson/41e1b0c6-546b-4077-a721-248cb87bc549" />
</CardGroup>
