Trivy EP18: Trivy Automation Project | Production-Ready DevSecOps Image Scanning (Final Wrap-Up)
This chapter marks the conclusion of the Trivy security scanner series, focusing on a production-ready batch automation script. We build a robust Bash automation framework that processes multiple Docker images from an input list, validates dependencies, automatically downloads required HTML templates, filters vulnerabilities by severity (HIGH,CRITICAL), and generates clean individual HTML audit reports for compliance teams.
1. Why Do We Need Batch Automation in DevSecOps?
In enterprise environments, security engineers rarely scan a single container image manually. When auditing dozens or hundreds of microservices, manual command-line execution becomes impractical, prone to human error, and difficult to track.
- The Status Quo Challenge: Running
trivy image <image_name>repeatedly for every container image wastes time and leads to inconsistent reporting formats across teams. - The Audit Requirement: Compliance and security audit teams require discrete, human-readable audit reports (such as HTML files) for every deployed artifact.
- The Solution: A centralized Bash automation script (
trivy image scan.sh) driven by a simple text inventory file (scan_image.txt) that scales image scanning effortlessly with a single command.
2. Core Project Architecture & Directory Structure
The automation project resides within repository directory number 10 and consists of three core components working in unison: an input list of container images, a customizable HTML reporting template, and the primary execution engine.
3. Tooling Prerequisites & Environment Setup
Before executing the batch script, the underlying host operating system must have a few essential CLI utilities installed.
Prerequisite Matrix
Note: While tested primarily on macOS, this shell script runs seamlessly on standard Linux distributions (Ubuntu, CentOS, RHEL) configured with the standard toolchain.
4. Input File Design (scan_image.txt)
The input file decouples target configuration from execution logic. Instead of hardcoding image names into the script, engineers simply maintain a flat text file where each line represents a target Docker image.
alpine:latest
node:16-alpine
python:3.9-slim
nginx:latest
ubuntu:20.04
redis:alpine
postgres:13
golang:1.18
- Flexibility: You can add, remove, or modify target images without altering a single line of the core scanning script.
- Scale: The automation handles any arbitrary number of images sequentially without manual intervention.
5. Step-by-Step Script Anatomy (trivy_image_scan.sh)
The Bash script is structured defensively to ensure robustness, checking for prerequisites, validating file dependencies, managing templates, and handling output directories dynamically.
Core Workflow Execution Flow
Detailed Script Implementation Breakdown
#!/bin/bash
# Configuration & Directories
INPUT_FILE="scan_image.txt"
TEMPLATE_FILE="html.tpl"
REPORT_DIR="report"
# 1. Prerequisite Check
for cmd in trivy wget docker; do
if ! command -v "$cmd" &> /dev/null; then
echo "Error: Required tool '$cmd' is not installed." >&2
exit 1
fi
done
# 2. Validate Input File
if [ ! -f "$INPUT_FILE" ]; then
echo "Error: Input file $INPUT_FILE not found!" >&2
exit 1
fi
# 3. Ensure HTML Template Exists (Download if missing)
if [ ! -f "$TEMPLATE_FILE" ]; then
echo "Template $TEMPLATE_FILE not found. Downloading via wget..."
wget https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/html.tpl -O "$TEMPLATE_FILE"
fi
# 4. Create Report Directory
mkdir -p "$REPORT_DIR"
# 5. Iterate and Scan Each Image
while IFS= read -r image; do
# Skip empty lines or comments
[[ -z "$image" \vert \vert "$image" =~ ^# ]] && continue
# Sanitize image name for filename (e.g., node:16-alpine -> node_16-alpine.html)
sanitized_name=$(echo "$image" | tr '/' '_' | tr ':' '_')
output_file="$REPORT_DIR/${sanitized_name}.html"
echo "--------------------------------------------------"
echo "Scanning image: $image"
echo "Generating report: $output_file"
echo "--------------------------------------------------"
# Execute Trivy scan with HIGH and CRITICAL severity filters
trivy image \
--severity HIGH,CRITICAL \
--format template \
--template "@$TEMPLATE_FILE" \
"$image" \
> "$output_file"
done < "$INPUT_FILE"
echo "=================================================="
echo "Report generated successfully!"
echo "All scans are completed successfully in '$REPORT_DIR/'."
echo "=================================================="
6. Real-World Execution & Output Verification
To execute the automation project, open your terminal within repository directory 10, clean up any previous scan artifacts, and run the shell script.
Command-Line Execution
# Clean up old reports if necessary
rm -rf report/*
# Execute the batch scanner script
bash trivy_image_scan.sh
During execution, watch the terminal output as Trivy inspects each image sequentially. The script dynamically creates individual HTML reports inside the report/ directory.
7. Inspecting Generated HTML Audit Reports
Once the script completes execution, audit teams can inspect the generated HTML reports directly in any web browser.
-
Clean Image Example (
alpine:latest):BASHopen report/alpine_latest.htmlResult: Displays a clean security dashboard indicating zero vulnerabilities present in the minimal Alpine base image.
-
Vulnerable Image Example (
node:16-alpine):BASHopen report/node_16-alpine.htmlResult: Displays a detailed breakdown restricted strictly to
HIGHandCRITICALseverity issues, listing CVE identifiers, package names, fixed versions, and vulnerability descriptions ready for the development team to patch.
8. Summary and Key Takeaways
- Batch Automation Efficiency: Automating multi-image scans eliminates repetitive manual CLI tasks, reducing human error and saving operational time.
- Decoupled Configuration: Using an external inventory file (
scan_image.txt) allows security teams to manage target images independently of execution scripts. - Defensive Shell Scripting: Production scripts must validate dependencies (
trivy,wget,docker), check file existence, and gracefully handle missing templates. - Dynamic Template Management: The script automatically provisions required custom HTML reporting templates (
html.tpl) if they are absent from the local working directory. - Targeted Severity Filtering: Filtering scans using
--severity HIGH,CRITICALensures audit reports focus exclusively on actionable, high-risk security flaws. - Compliance Ready: Generating standardized individual HTML files per image enables seamless handoff to internal audit and compliance teams.
- Series Conclusion: This automation capstone wraps up the comprehensive Trivy security scanner course, equipping engineers with enterprise-grade DevSecOps image scanning capabilities.