Trivy EP15 | Trivy Automation Script | Shell Script for Daily Security Scans | DevSecOps
This comprehensive chapter explores how to transition from running manual, ad-hoc Trivy container image scans to building a robust, automated shell script. By standardizing security checks, automating report generation with precise timestamps, and enabling dynamic user inputs, security engineers can streamline their daily DevSecOps workflows and maintain rigorous audit trails.
1. Why Do We Need Security Scan Automation?
In early development and exploration phases, security engineers frequently run manual commands such as trivy image <image-name>. While sufficient for quick checks, manual execution falls short in production and routine auditing environments due to several operational bottlenecks:
- Repetitive Toil: Running the same commands repeatedly wastes valuable engineering time and introduces human error.
- Lack of Persistent Audit Trails: Ad-hoc terminal outputs vanish when the session closes, making it difficult to submit compliance reports or track vulnerability trends over time.
- Inconsistent Filtering: Manual runs often output raw, unfiltered vulnerabilities (including low and medium severities), burying critical security risks under noise.
- Standardization Challenges: Different team members might scan images with different flags (
--severity,--format), leading to inconsistent reporting.
Real-Life Analogy: The Security Guard vs. The Automated CCTV System
Note: Manually running Trivy for every image is like having a security guard manually walk down every single hallway with a flashlight every hour. It works, but it is exhausting and prone to missed spots. Writing an automation shell script is like installing automated CCTV cameras that record logs, timestamp every event, and archive footage into a dedicated security vault automatically whenever triggered.
2. Core Architecture & Workflow Design
Before writing code, let us map out the workflow of our shell automation script. The script needs to handle directory creation, dynamic input collection, timestamp generation, vulnerability filtering, and report archiving.
3. Step-by-Step Evolution: From Hardcoded to Dynamic Scripting
Step 3.1: The Naive Hardcoded Approach (scan.sh)
Initially, we write a basic shell script with hardcoded variables to test our core Trivy command structure and directory creation logic.
#!/bin/bash
# Hardcoded image and directory variables
image="python:3.10-slim"
repo="trivy-reports"
# Create the reports directory if it does not exist
mkdir -p "$repo"
# Generate timestamp
date=$(date +%Y-%m-%d-%H-%M)
echo "Scanning image: $image at $date"
# Run Trivy scan (filtering high and critical vulnerabilities)
trivy image --severity HIGH,CRITICAL --format table "$image" > "$repo/trivy_report_${date}.txt"
echo "Scanning is completed. Report stored in $repo/trivy_report_${date}.txt"
Step 3.2: Upgrading to Dynamic User Input
Hardcoding the image name limits the script's reusability. We can improve this by using the read command to prompt the user interactively at runtime.
#!/bin/bash
# 1. Take user input dynamically for image name
read -p "Enter image name for scanning (e.g., python:3.10-slim): " image
# 2. Define repository storage directory
repo="trivy-reports"
mkdir -p "$repo"
# 3. Generate precise timestamp (Year-Month-Day-Hour-Minute)
date=$(date +%Y-%m-%d-%H-%M)
echo "--------------------------------------------------"
echo "Starting Trivy Security Scan for: $image"
echo "Timestamp: $date"
echo "--------------------------------------------------"
# 4. Execute Trivy Scan & Redirect Output to Report File
trivy image --severity HIGH,CRITICAL --format table "$image" > "$repo/trivy_report_${date}.txt"
echo "--------------------------------------------------"
echo "Scan completed successfully!"
echo "Report stored at: $repo/trivy_report_${date}.txt"
echo "--------------------------------------------------"
4. Script Execution & Permission Management
Writing the script is only half the battle; in Linux/Unix environments, execution permissions and path configurations dictate whether the script runs smoothly.
Granting Execution Permissions
By default, newly created text files do not have execution rights. We must modify file permissions using chmod:
# Give executable permissions to the script
chmod +x scan.sh
# Verify file permissions
ls -la scan.sh
-rwxr-xr-x 1 user staff 420 Oct 24 10:00 scan.sh
Running the Script and Verifying Output
Execute the script interactively in your terminal:
$./scan.sh
Enter image name for scanning (e.g., python:3.10-slim): python:3.10-slim
--------------------------------------------------
Starting Trivy Security Scan for: python:3.10-slim
Timestamp: 2023-10-24-14-35
--------------------------------------------------
--------------------------------------------------
Scan completed successfully!
Report stored at: trivy-reports/trivy_report_2023-10-24-14-35.txt
--------------------------------------------------
Checking the generated reports folder:
$ cd trivy-reports
$ ls -la
total 16
drwxr-xr-x 3 user staff 96 Oct 24 14:35 .
drwxr-xr-x 5 user staff 160 Oct 24 14:30 ..
-rw-r--r-- 1 user staff 1420 Oct 24 14:35 trivy_report_2023-10-24-14-35.txt
Reading the generated report directly from the terminal:
$ cat trivy_report_2023-10-24-14-35.txt
5. Technical Comparison: Scan Configurations & Output Formats
Trivy supports multiple report formats and scanning strategies depending on organizational compliance requirements.
6. Real-World Debugging & Common Pitfalls
When writing shell scripts that integrate CLI security tools like Trivy, developers frequently encounter specific gotchas:
- Syntax Errors in Date Formatting:
- Pitfall: Including spaces or incorrect format specifiers in
date +%Y-%m-%d-%H-%Mleads to shell syntax errors or invalid filenames. - Fix: Ensure no spaces surround the equal sign (
date=$(date +%Y-%m-%d-%H-%M)) and avoid colons (:) inside timestamps on Windows/restricted filesystems.
- Pitfall: Including spaces or incorrect format specifiers in
- Missing Execute Permissions (
Permission Denied):- Pitfall: Running
./scan.shimmediately after creation results in aPermission Deniederror. - Fix: Always run
chmod +x scan.sh.
- Pitfall: Running
- Trivy Database Initialization Delays:
- Pitfall: On the first run, Trivy downloads vulnerability databases (
vulnerability.db), which can cause timeouts or script delays. - Fix: Pre-pull the Trivy database in CI/CD pipelines or run a dummy scan once before executing automation scripts.
- Pitfall: On the first run, Trivy downloads vulnerability databases (
7. Take-Home Assignment & Next Steps
To build mastery over shell scripting and Trivy customization, complete the following practical assignment:
- HTML Report Generation: Modify
scan.shto generate an HTML report instead of a plain text.txtfile.- Hint: Review Trivy's built-in template options (e.g., using
--format template --template "@contrib/html.tpl").
- Hint: Review Trivy's built-in template options (e.g., using
- SBOM Scanning: Create a separate script (
sbom-scan.sh) that generates a CycloneDX SBOM report for a local filesystem or container image. - Repository Reference: Consult the course's accompanying Git repository where sample reference scripts (
html-scan.sh,scan.sh) are fully documented for troubleshooting.
Summary and Key Takeaways
- Automation Efficiency: Automating repetitive security tasks eliminates manual toil, reduces human error, and ensures consistent scanning protocols across teams.
- Dynamic Input Handling: Using shell
readcommands allows a single generic script (scan.sh) to scan any container image dynamically without code modifications. - Timestamped Auditing: Appending precise timestamps (
YYYY-MM-DD_HH-MM) to report filenames ensures historical tracking and compliance readiness. - Targeted Severity Filtering: Filtering scans using
--severity HIGH,CRITICALprevents alert fatigue by focusing engineering attention on actionable risks. - Directory Management: Utilizing
mkdir -pensures that storage repositories are automatically provisioned if they do not already exist. - Execution Privileges: Standard Linux security practices require explicit execution permissions (
chmod +x) before running custom shell scripts. - Extensibility: Shell scripts can easily be extended to output multiple formats (JSON, HTML, CycloneDX SBOM) to feed downstream DevSecOps dashboards and compliance pipelines.