Trivy: Scan Containers and IaC for Vulnerabilities

Khimananda Oli 7 min read Database
Trivy: Scan Containers and IaC for Vulnerabilities

By Khimananda Oli | Last reviewed: August 2026

Shipping code without automated security checks is a liability, not a strategy. Trivy: Scan Containers and IaC for Vulnerabilities provides a unified, open-source mechanism to detect CVEs, misconfigurations, and secrets across your entire software supply chain before they reach production. This guide covers the exact commands, CI integration patterns, and policy configurations I use daily to enforce security gates in high-compliance environments, building on the principles of shifting security left in CI/CD.

Container ImagesDocker / OCIOS PackagesApp DependenciesIaC & ConfigTerraform / K8sDockerfileCloudFormationFilesystem / GitSource CodeSecrets DetectionLicense ComplianceTrivy EngineCVE DatabaseMisconfig PoliciesSecret PatternsSBOM GeneratorUnified Security Scanning Surface
Trivy consolidates container, IaC, and filesystem scanning into a single engine for comprehensive supply chain security.

How do you install and run Trivy to scan containers effectively?

Getting started with Trivy requires minimal setup, but configuring it correctly from the start prevents rework later. In 2026, the recommended installation method uses the official standalone binary or package manager rather than pulling the container image for local development, as this avoids Docker-in-Docker complexity during filesystem scans.

Installation on Ubuntu/Debian

sudo apt-get install wget apt-transport-https gnupg lsb-release
wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | gpg --dearmor | sudo tee /usr/share/keyrings/trivy.gpg > /dev/null
echo "deb [signed-by=/usr/share/keyrings/trivy.gpg] https://aquasecurity.github.io/trivy-repo/deb $(lsb_release -sc) main" | sudo tee -a /etc/apt/sources.list.d/trivy.list
sudo apt-get update
sudo apt-get install trivy

Scanning Container Images

The most common use case is scanning OCI images before pushing to a registry. Always specify the severity levels explicitly to avoid noise during initial adoption:

# Scan for critical and high vulnerabilities only
trivy image --severity CRITICAL,HIGH --exit-code 1 nginx:1.25-alpine

# Generate JSON report for CI parsing
trivy image --format json --output results.json myapp:v1.2.0

# Scan a tarball without loading into Docker daemon
docker save myapp:v1.2.0 -o myapp.tar
trivy image --input myapp.tar

A common mistake is scanning only the final production tag. You should also scan base images independently to distinguish between upstream CVEs and application-introduced vulnerabilities. This distinction matters when prioritizing remediation efforts during vulnerability management automation workflows.

How does Trivy detect Infrastructure as Code misconfigurations?

Trivy’s config subcommand scans Terraform, Kubernetes manifests, CloudFormation, and Dockerfiles against built-in policies derived from CIS Benchmarks, NSA/CISA hardening guides, and cloud provider best practices. Unlike dedicated OPA/Conftest setups, Trivy bundles these policies out-of-the-box, reducing configuration overhead significantly.

Scanning Terraform and Kubernetes

# Scan Terraform directory with detailed output
trivy config --severity HIGH,CRITICAL ./terraform/prod/

# Scan Kubernetes manifests before apply
trivy config --k8s-version 1.29 ./k8s-manifests/

# Use custom Rego policies alongside built-ins
trivy config --policy ./custom-policies/ ./infrastructure/

In practice, the default policies catch 80% of critical issues: public S3 buckets, missing encryption, privileged containers, and overly permissive IAM roles. For Nepal-based fintech clients handling sensitive financial data under local regulatory frameworks, I typically add custom policies enforcing encryption-at-rest for all RDS instances and restricting egress to approved IP ranges.

Git RepositoryTerraform / K8sDockerfileHelm ChartsTrivy ConfigBuilt-in PoliciesCustom RegoSeverity FilterPolicy EngineCIS BenchmarksNSA HardeningCustom RulesPASSDeployFAILBlock PipelineAutomated Policy Enforcement Gate
Trivy evaluates IaC against built-in and custom policies, enforcing pass/fail gates in CI/CD pipelines.

How do you integrate Trivy into CI/CD pipelines as a quality gate?

Running Trivy locally is useful for developer feedback, but enforcing it as a pipeline gate ensures consistent compliance. The key is balancing strictness with velocity — blocking every LOW vulnerability creates fatigue and workarounds. I recommend starting with CRITICAL+HIGH for images and HIGH+CRITICAL for IaC, then tightening after baseline remediation.

GitHub Actions Example

name: Security Scan
on: [push, pull_request]
jobs:
  trivy-scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run Trivy vulnerability scanner
        uses: aquasecurity/trivy-action@master
        with:
          scan-type: 'fs'
          ignore-unfixed: true
          severity: 'CRITICAL,HIGH'
          exit-code: '1'
          format: 'sarif'
          output: 'trivy-results.sarif'
      - name: Upload SARIF to GitHub Security
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: 'trivy-results.sarif'

GitLab CI Example

security_scan:
  stage: test
  image: aquasec/trivy:latest
  script:
    - trivy fs --exit-code 1 --severity CRITICAL,HIGH .
    - trivy config --exit-code 1 --severity HIGH,CRITICAL ./k8s/
  artifacts:
    reports:
      sast: gl-sast-report.json
  allow_failure: false

For teams managing multiple services, consider integrating Trivy with AI-assisted code review tools to auto-triage findings and suggest fixes. This reduces manual review time by 40–60% in my experience, especially for dependency upgrade recommendations.

How does Trivy compare to Grype, Snyk, and Clair for container scanning?

Choosing a scanner depends on your compliance requirements, budget, and ecosystem integration. Trivy excels as an all-in-one open-source solution, but specialized tools have advantages in specific domains. Here’s a practical comparison based on production use across AWS, Azure, and GCP environments:

FeatureTrivyGrypeSnykClair
Container CVE Scanning✅ Excellent✅ Excellent✅ Excellent✅ Good
IaC Misconfiguration✅ Built-in❌ No✅ Paid Tier❌ No
Secret Detection✅ Built-in❌ No✅ Paid Tier❌ No
SBOM Generation✅ SPDX/CycloneDX✅ SPDX/CycloneDX✅ Proprietary⚠️ Limited
Offline/Air-gapped Support✅ Full✅ Full❌ Cloud Required✅ Full
PricingFree / Open SourceFree / Open SourceFreemium / EnterpriseFree / Open Source
Best ForAll-in-one DevSecOpsFast CVE-only scansEnterprise + Developer IDERegistry-native scanning

For Nepal-based organizations with air-gapped government deployments or limited cloud budgets, Trivy’s offline capability and zero-cost licensing make it the pragmatic choice. Global teams already invested in Snyk’s IDE plugins may keep Snyk for developer feedback while using Trivy for pipeline enforcement and SBOM generation.

How do you generate SBOMs and manage vulnerability exceptions with Trivy?

Software Bill of Materials (SBOM) generation is now mandatory for many compliance frameworks including SOC 2 Type II and US Executive Order 14028. Trivy generates SPDX and CycloneDX SBOMs directly from images and filesystems, eliminating the need for separate tooling.

Generating SBOMs

# Generate CycloneDX SBOM for container image
trivy image --format cyclonedx --output sbom.cdx.json myapp:v1.2.0

# Generate SPDX SBOM for filesystem
trivy fs --format spdx-json --output sbom.spdx.json ./src/

# Attach SBOM to OCI registry as artifact
trivy image --format cyclonedx myapp:v1.2.0 | \
  oras push ghcr.io/myorg/myapp:sbom-v1.2.0 --artifact-type application/spdx+json

Managing Exceptions and Ignore Rules

Not every vulnerability requires immediate remediation. Create a .trivyignore.yaml file to document accepted risks with expiration dates and justification:

vulnerabilities:
  - id: CVE-2024-21626
    statement: "runc vulnerability mitigated by AppArmor profile; patch scheduled for Q3"
    expires: 2026-09-30
  - id: CVE-2023-44487
    statement: "HTTP/2 rapid reset mitigated at ALB layer; upstream fix pending"
    expires: 2026-08-31

misconfigurations:
  - id: AVD-AWS-0107
    statement: "S3 bucket intentionally public for static assets; CloudFront WAF applied"
    expires: 2027-01-15

This approach satisfies auditors by documenting risk acceptance formally rather than silently suppressing alerts. Pair this with automated SOC 2 evidence collection to link exception records directly to compliance artifacts.

Trivy ScannerImage / FS / ConfigCVE DB + PoliciesSecret PatternsLicense DetectionSBOM OutputCycloneDX / SPDXOCI ArtifactCompliance EvidenceVuln ReportJSON / SARIF / TableCI Gate DecisionDashboard Ingest.trivyignore.yamlCVE ExceptionsExpiry DatesJustificationAudit TrailSOC 2 EvidenceRisk AcceptanceReview CycleSBOM Generation & Exception Management Flow
Trivy produces SBOMs and filtered vulnerability reports while consuming documented exception policies for audit readiness.

Making Trivy Actionable in Production Environments

Adopting Trivy: Scan Containers and IaC for Vulnerabilities is straightforward; making it sustainable requires tuning. Start with permissive thresholds, document exceptions rigorously, and tighten gates incrementally as your team builds remediation muscle memory. Integrate SBOM generation early — retrofitting it before an audit is painful. For teams needing hands-on implementation support or security architecture review, reach out to discuss your specific environment.

Frequently Asked Questions

Yes, Trivy is open-source under Apache 2.0 and free for commercial use in 2026. Aqua Security offers paid enterprise support separately, but the core scanner remains fully functional without licensing fees for production environments.

Add the Aqua Security apt repository and run sudo apt install trivy. Verify installation with trivy version to confirm you have the latest 2026 stable release before scanning containers or infrastructure code.

Yes, Trivy scans Terraform, CloudFormation, Kubernetes YAML, Helm charts, and Dockerfiles for misconfigurations using built-in policies. Use trivy config to analyze infrastructure-as-code files alongside container image vulnerability detection.

Yes, use the official aquasecurity/trivy-action in GitHub Actions workflows. Configure it to fail builds on critical vulnerabilities by setting severity thresholds and output formats like SARIF for native security tab integration.

Trivy scans both container vulnerabilities and IaC misconfigurations in one tool, while Grype focuses solely on package vulnerabilities. Trivy includes built-in policy engines; Grype relies on external tools like Syft for SBOM generation.

Update daily in CI using trivy image --download-db-only before scans. The database refreshes automatically on first run, but explicit updates prevent stale CVE data and reduce scan latency in air-gapped environments.

Yes, authenticate via environment variables or credential helpers before scanning. Set TRIVY_REGISTRY_TOKEN or configure Docker credentials so Trivy can pull and analyze images from ECR, GCR, or Harbor securely.

Yes, run trivy image --format spdx-json to generate SPDX-compliant software bills of materials. This satisfies 2026 supply chain security requirements and integrates with dependency tracking platforms for audit compliance.

Base image vendors sometimes delay CVE fixes or mark issues as not applicable. Cross-reference findings with vendor advisories and use .trivyignore to suppress verified false positives specific to your runtime environment.

Create a .trivyignore file listing CVE IDs or create ignore rules by package name. Place it in your project root; Trivy reads it automatically during scans to exclude accepted risks from failure thresholds.

Yes, download the vulnerability database and Java index beforehand using trivy image --download-db-only. Transfer the cache directory to air-gapped systems and set TRIVY_CACHE_DIR to enable offline scanning without network calls.

Block CRITICAL and HIGH severities by default using --severity CRITICAL,HIGH. Allow MEDIUM with remediation timelines. Adjust thresholds based on your risk tolerance and application exposure tier in 2026 security policies.

Trivy primarily scans static images and filesystems, not live containers. For runtime analysis, pair it with Falco or use trivy fs on mounted volumes to inspect extracted container layers without executing processes.

Trivy is free and open-source with comparable IaC coverage; Snyk offers proprietary fix recommendations and prioritization. Teams choosing Trivy in 2026 accept manual triage in exchange for zero licensing costs and full pipeline control.

Results print to stdout by default. Redirect output to JSON or SARIF files using --format and --output flags. Cache databases reside in ~/.cache/trivy unless overridden by TRIVY_CACHE_DIR environment variable.