> ## 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 Vulnerability Scan using Trivy

> This guide explains how to use Trivy for vulnerability scanning and integrate it into a Jenkins pipeline before pushing Docker images.

Before pushing your Docker image to a registry, it’s crucial to identify and remediate vulnerabilities. In this guide, we’ll walk through how to use **Trivy** for vulnerability scanning and integrate it into a Jenkins pipeline.

## What Is Trivy?

Trivy is an open-source, all-in-one security scanner from Aqua Security. It can analyze:

* Container images
* File systems
* Git repositories
* Kubernetes manifests
* Infrastructure as Code (IaC)

Trivy detects OS package vulnerabilities, software dependency issues, IaC misconfigurations, license risks, and exposed secrets.

<Frame>
  ![The image is a screenshot of a webpage from Aqua Security's documentation about Trivy, a security scanner. It lists the targets Trivy can scan, such as container images and filesystems, and the types of issues it can detect, like known vulnerabilities and sensitive information.](https://kodekloud.com/kk-media/image/upload/v1752870525/notes-assets/images/Certified-Jenkins-Engineer-Demo-Vulnerability-Scan-using-Trivy/trivy-security-scanner-documentation.jpg)
</Frame>

Learn more on the [official Trivy GitHub repository](https://github.com/aquasecurity/trivy).

## Installing Trivy

You can install Trivy via package managers, a standalone binary, or run it in Docker.

| Platform        | Method            | Command / Reference                                  |
| --------------- | ----------------- | ---------------------------------------------------- |
| macOS           | Homebrew          | `brew install trivy`                                 |
| Docker          | Container image   | See *Docker* block below                             |
| RPM-based Linux | YUM repository    | Add repo then `sudo yum install trivy`               |
| Manual / Source | Shell script & Go | Use Aquasecurity install script or build from source |

### Homebrew (macOS)

```bash theme={null}
brew install trivy
```

### Docker

```bash theme={null}
docker run --rm \
  -v /var/run/docker.sock:/var/run/docker.sock \
  -v $HOME/Library/Caches/:/root/.cache \
  aquasec/trivy image python:3.4-alpine
```

### RPM-Based Linux

```bash theme={null}
sudo tee /etc/yum.repos.d/trivy.repo <<EOF
[trivy]
name=Trivy repository
baseurl=https://aquasecurity.github.io/trivy-repo/releases/$releasever/
enabled=1
gpgcheck=1
gpgkey=https://aquasecurity.github.io/trivy-repo/rpm/public.key
EOF
sudo yum -y update
sudo yum -y install trivy
```

### Manual / From Source

```bash theme={null}
# Install via script
curl -sL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh

# Or build from GitHub
git clone --depth 1 --branch v0.55.2 https://github.com/aquasecurity/trivy
cd trivy
go install ./cmd/trivy
```

## Basic Usage

Scan a Docker image for vulnerabilities:

```bash theme={null}
trivy image python:3.4-alpine
```

Scan a local project directory for vulnerabilities and secrets:

```bash theme={null}
trivy fs --scanners vuln,secret,misconfig ./myproject
```

Get Trivy version and help:

```bash theme={null}
trivy -v           # e.g. Version: 0.55.2
trivy image --help # Image-scan options
```

<Callout icon="lightbulb" color="#1CB2FE">
  By default, Trivy exits with code `0` even if it finds non-critical issues. Use `--exit-code` to control build failures based on severity.
</Callout>

## Integrating Trivy into a Jenkins Pipeline

Add a **Trivy Vulnerability Scanner** stage immediately after your Docker build. Below is an example declarative pipeline:

```groovy theme={null}
pipeline {
  agent any
  stages {
    stage('Build Docker Image') {
      steps {
        // your build steps...
      }
    }

    stage('Trivy Vulnerability Scanner') {
      steps {
        // Medium/Low scan does not fail build
        sh '''
          trivy image siddharth67/solar-system:$GIT_COMMIT \
            --severity LOW,MEDIUM,HIGH \
            --exit-code 0 \
            --quiet \
            --format json -o trivy-image-medium.json

          # Critical scan fails on findings
          trivy image siddharth67/solar-system:$GIT_COMMIT \
            --severity CRITICAL \
            --exit-code 1 \
            --quiet \
            --format json -o trivy-image-critical.json
        '''
      }
      post {
        always {
          // Convert JSON to HTML and JUnit XML
          sh '''
            trivy convert --format template \
              --template "/usr/local/share/trivy/templates/html.tpl" \
              --output trivy-image-medium.html trivy-image-medium.json

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

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

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

          // Publish JUnit test reports
          junit allowEmptyResults: true, testResults: 'trivy-image-*.xml'

          // Publish HTML vulnerability reports
          publishHTML([
            allowMissing: true, alwaysLinkToLastBuild: true, keepAll: true,
            reportDir: '.', reportFiles: 'trivy-image-critical.html',
            reportName: 'Critical Vulnerabilities', useWrapperFileDirectly: true
          ])
          publishHTML([
            allowMissing: true, alwaysLinkToLastBuild: true, keepAll: true,
            reportDir: '.', reportFiles: 'trivy-image-medium.html',
            reportName: 'Medium/Low Vulnerabilities', useWrapperFileDirectly: true
          ])
        }
      }
    }

    stage('Push to Registry') {
      steps {
        // your push steps...
      }
    }
  }
}
```

<Callout icon="triangle-alert" color="#FF6B6B">
  The critical-scan stage uses `--exit-code 1`. Any CRITICAL vulnerability will fail the build immediately.
</Callout>

## Supported Reporting Formats

Trivy supports several output formats:

| Format   | Description                                              |
| -------- | -------------------------------------------------------- |
| Table    | Human-readable table view                                |
| JSON     | Machine-parsable data                                    |
| SARIF    | Static Analysis Results Interchange Format               |
| Template | Custom reports via Go templates (HTML, JUnit, CycloneDX) |

Templates are installed at:

```bash theme={null}
ls /usr/local/share/trivy/templates
# asff.tpl  gitlab-codequality.tpl  gitlab.tpl  html.tpl  junit.tpl
```

<Frame>
  ![The image shows a webpage from Trivy's documentation, detailing the reporting formats supported by Trivy, such as Table, JSON, and Template. The page includes a table listing supported scanners and a command example.](https://kodekloud.com/kk-media/image/upload/v1752870526/notes-assets/images/Certified-Jenkins-Engineer-Demo-Vulnerability-Scan-using-Trivy/trivy-reporting-formats-documentation.jpg)
</Frame>

To convert a JSON output into a CycloneDX SBOM:

```bash theme={null}
trivy image --format json -o result.json debian:11
trivy convert --format cyclonedx --output result.cdx result.json
```

## Reviewing Scan Results

After your Jenkins job completes, the workspace will contain:

<Frame>
  ![The image shows a Jenkins workspace interface displaying a list of files and folders with their names, sizes, and timestamps.](https://kodekloud.com/kk-media/image/upload/v1752870528/notes-assets/images/Certified-Jenkins-Engineer-Demo-Vulnerability-Scan-using-Trivy/jenkins-workspace-files-list.jpg)
</Frame>

* **trivy-image-medium.html** / **.json / .xml**
* **trivy-image-critical.html** / **.json / .xml**

In Jenkins’ **Test Results** view, Trivy’s JUnit entries appear alongside other CI tests:

<Frame>
  ![The image shows a test report from a CI/CD pipeline indicating that 57 tests have failed, with details of existing failures including various CVE vulnerabilities.](https://kodekloud.com/kk-media/image/upload/v1752870529/notes-assets/images/Certified-Jenkins-Engineer-Demo-Vulnerability-Scan-using-Trivy/ci-cd-pipeline-test-report-failures.jpg)
</Frame>

## Adjusting Severity Thresholds

To treat HIGH severity like MEDIUM (only fail on CRITICAL), include HIGH in the non-failing scan:

```groovy theme={null}
steps {
  sh '''
    trivy image siddharth67/solar-system:$GIT_COMMIT \
      --severity LOW,MEDIUM,HIGH \
      --exit-code 0 \
      --quiet \
      --format json -o trivy-image-medium.json

    trivy image siddharth67/solar-system:$GIT_COMMIT \
      --severity CRITICAL \
      --exit-code 1 \
      --quiet \
      --format json -o trivy-image-critical.json
  '''
}
```

## Summary

In this tutorial, you learned how to:

* Install Trivy on various platforms
* Execute basic vulnerability scans on images and filesystems
* Integrate Trivy into a Jenkins pipeline with pass/fail thresholds
* Convert JSON results to HTML, JUnit, or CycloneDX formats
* Publish and review vulnerability reports in Jenkins

Trivy also supports scanning IaC files, detecting sensitive data, and auditing software licenses. For advanced scenarios, visit the [official Trivy documentation](https://aquasecurity.github.io/trivy/).

## Links and References

* [Trivy GitHub Repository](https://github.com/aquasecurity/trivy)
* [Aqua Security Documentation](https://aquasecurity.github.io/)
* [Jenkins 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/certified-jenkins-engineer/module/e16e4b93-31c4-479b-96b8-f0d26cde31cd/lesson/a792f39b-46ff-45dd-9125-4da7b5e9b191" />
</CardGroup>
