Trivy Pocket Book — Uplatz
50 in-depth cards • Wide layout • Readable examples • 20-question interview Q&A included
1) What is Trivy?
Trivy is an all-in-one open-source security scanner by Aqua Security for vulnerabilities, misconfigurations, secrets, and SBOMs across filesystems, containers, Kubernetes, cloud, and IaC.
Targets: filesystems • images • repos • k8s • IaC • SBOM • AWS • rootfs
2) Installation
Available via Homebrew, apt/yum, script installer, Docker image, and GitHub releases. Bundles its own DB cache by default.
brew install aquasecurity/trivy/trivy
# or
docker run --rm -v $PWD:/work aquasec/trivy:latest --version
3) Scanners
Enable/disable scanners: vuln
, config
, secret
, license
, misconfig
, rbac
(via k8s), sbom
.
trivy image --scanners vuln,secret,config repo/app:1.2.3
4) Vulnerability DBs
Uses multiple sources (e.g., distro advisories, GitHub) and updates the cache automatically; can run offline with pre-fetched DB.
trivy image --download-db-only
trivy image --offline-scan app:tag
5) Output Formats
Text, table, JSON, SARIF, SPDX/CycloneDX SBOM; custom templates via Go templates.
trivy image app:tag --format sarif --output report.sarif
6) Severity & Policies
Filter by severity; fail builds with exit codes; ignore unfixed vulns or set policy thresholds.
trivy image app:tag --severity HIGH,CRITICAL --exit-code 1 --ignore-unfixed
7) Caching & Performance
Warm caches, mount Docker socket for direct image access, and prune layers to speed recurring scans.
TRIVY_CACHE_DIR=.trivycache trivy fs .
8) Basic Commands
Scan filesystems, images, repos, and Kubernetes clusters quickly with sensible defaults.
trivy fs .
trivy image repo/app:latest
trivy repo https://github.com/org/project
9) Ignore File
Suppress specific issues temporarily via .trivyignore
(with IDs or regex); always include reasons in PRs.
# .trivyignore
CVE-2024-12345
CWE-798 # hardcoded creds pattern (investigating)
10) Q&A — “Why Trivy?”
Answer: One tool covers vuln scanning, IaC misconfig, secrets detection, and SBOMs with minimal setup and fast defaults.
11) Image Vulnerability Scan
Scans OS packages and language deps; supports local daemon or remote registry images.
trivy image --vuln-type os,library repo/app:1.0.0
12) Base Image Suggestions
Trivy can suggest alternative base images with fewer CVEs (if metadata available); consider vendor-slim images.
trivy image --format json repo/app:1.0.0 | jq '.Results[].SuggestedFix'
13) SBOM Generation
Create SBOMs to track dependencies; feed into signing/attestations or vulnerability management.
trivy sbom --format cyclonedx --output sbom.json repo/app:1.0.0
14) From SBOM to Scan
Scan prebuilt SBOMs (offline or CI) to detect newly disclosed vulns without pulling the image again.
trivy sbom scan --format table sbom.json
15) RootFS Scanning
Scan mounted root filesystems/VMs to inventory packages and detect CVEs.
sudo trivy rootfs /mnt/disk
16) Registry Auth
Use env vars or Docker auth helpers to access private registries; avoid printing tokens in logs.
export TRIVY_USERNAME=ciuser TRIVY_PASSWORD=$REG_PASS
trivy image private.registry/app:tag
17) Ignore Unfixed vs Fixed Only
--ignore-unfixed
hides issues with no upstream fix; --ignore-policy
enforces custom logic via Rego.
trivy image app:tag --ignore-unfixed
trivy image app:tag --ignore-policy policy.rego
18) Templated Reports
Render custom HTML/Markdown/CSV with Go templates; attach artifacts to CI for review.
trivy image app:tag --format template --template @tpl/summarize.tpl --output out.html
19) Exit Codes & Gates
Use exit codes to block builds on high/critical; thresholds keep pipelines developer-friendly.
trivy image app:tag --severity HIGH,CRITICAL --exit-code 1 || echo "review required"
20) Q&A — “Alpine fixes everything?”
Answer: Alpine often reduces CVEs but musl vs glibc differences can break apps; vendor-supported slim images can be safer.
21) IaC Misconfig Scans
Scan Terraform, CloudFormation, ARM/Bicep, Kubernetes YAML, Helm charts.
trivy config iac/ --severity HIGH,CRITICAL
22) Kubernetes Cluster Scan
Scan live cluster for workload misconfigs and vulns in running images (needs kubeconfig).
trivy k8s cluster
trivy k8s --report summary all
23) RBAC & Pod Security
Detect risky permissions, privileged pods, hostPath, and missing resource limits.
trivy k8s --namespace prod --severity HIGH,CRITICAL
24) Helm & Kustomize
Scan rendered charts; integrate checks into deployment pipelines before applying manifests.
helm template charts/web | trivy config -
25) Secrets Scanner
Detect hardcoded credentials/API keys in git repos and filesystems; add allowlist patterns if needed.
trivy repo https://github.com/org/repo --scanners secret
26) Policy as Code (OPA/Rego)
Write custom policies to enforce org rules (e.g., deny 0.0.0.0/0 SGs); run with --policy
.
trivy config iac/ --policy policies/ --policy-namespace user
27) Baselines & Drift
Save baseline JSON and compare future scans to detect newly introduced risks only.
trivy fs . --format json --output base.json
28) Kubernetes Admission
Combine with admission controllers to block risky configs pre-deploy (e.g., Kyverno/Gatekeeper + Trivy results).
29) Shift-Left
Run Trivy in pre-commit hooks, IDE tasks, and PR checks; fix issues before merge.
# pre-commit config
- repo: local
hooks:
- id: trivy-fs
name: trivy fs
entry: trivy fs .
language: system
30) Q&A — “IaC vs runtime?”
Answer: Catch misconfig in code first; use live cluster scans to verify and detect drift/overrides.
31) GitHub Actions
Run Trivy on push/PR; upload SARIF to code scanning; fail on high/critical.
- uses: aquasecurity/trivy-action@master
with:
scan-type: 'image'
image-ref: 'ghcr.io/org/app:${{ github.sha }}'
format: 'sarif'
output: 'trivy.sarif'
severity: 'HIGH,CRITICAL'
32) Jenkins Pipeline
Use CLI step; archive JSON and HTML; gate on severity.
sh 'trivy image app:tag --format json --output trivy.json --severity HIGH,CRITICAL --exit-code 1'
33) GitLab CI
Inline job templates; artifacts for MR review; optional allow-failure for non-blocking stages.
trivy:
script: trivy image $IMAGE --format json --output trivy.json --exit-code 1
artifacts: { paths: [trivy.json] }
34) Bitbucket / Azure DevOps
Run in steps with container images; publish results to build summaries and PR comments.
35) Signing & Attestations
Pair Trivy with Cosign/SLSA: generate SBOM → sign image and attest SBOM/scan results.
trivy sbom --format spdx-json -o sbom.spdx.json repo/app:tag
cosign attest --predicate sbom.spdx.json --type spdxjson repo/app:tag
36) Policy Gates
Rego policies in CI to block deploys if severity threshold exceeded or controls violated.
trivy image app:tag --format json | conftest test -p policies -
37) Cloud Scans (AWS)
Scan AWS account resources (experimental modes evolve). Prefer IaC-first plus least-privilege cloud roles.
trivy aws --service s3
38) Offline CI
Mirror DB in a private cache; point builds to it for air-gapped environments.
trivy image --download-db-only --cache-dir .trivycache
39) Performance & Cost
Use shallow fetch for repos, cache Docker layers, skip low severity in PRs, run full scans nightly.
40) Q&A — “Block everything red?”
Answer: Block on HIGH/CRITICAL and reachable or fixable issues; warn on others to keep velocity.
41) Recipe: Dockerfile Hardening
Use multi-stage builds, drop root, pin versions, clean package caches, and copy only required artifacts.
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine
USER 10001
WORKDIR /app
COPY --from=build /app/dist ./dist
CMD ["node","dist/server.js"]
42) Recipe: K8s Admission Precheck
Render Helm → Trivy config scan → only apply if pass; wire into CD pipeline.
helm template charts/web | trivy config - --exit-code 1 || exit 1
kubectl apply -f k8s/
43) Recipe: Monorepo Paths
Scan only changed dirs in PRs to speed feedback loops.
CHANGED=$(git diff --name-only origin/main... | cut -d/ -f1 | sort -u)
for d in $CHANGED; do trivy fs "$d"; done
44) Recipe: HTML Report
Generate a friendly HTML summary for managers/auditors.
trivy image app:tag --format template --template @tpl/summary-html.tpl -o trivy.html
45) Common Pitfalls
Scanning only at release, ignoring lockfiles, permanent ignores, not enabling monitor/scheduled scans, scanning images never deployed.
46) Developer UX Tips
IDE helpers, pre-commit hooks, PR comments with minimal actionable fixes, and auto-created issues for owners.
47) Secrets Hygiene
Use secret managers, forbid committing .env with tokens, and add allowlists only for false positives with expiry.
48) Compliance Mapping
Map misconfig checks to CIS/NIST; export SBOM + scan reports for audit evidence; track MTTR and remediation SLAs.
49) 30-Day Rollout
Week1: IDE + fs scans • Week2: image/PR gates (high+) • Week3: IaC + k8s • Week4: SBOM/signing + dashboards.
50) Interview Q&A — 20 Practical Questions (Expanded)
1) What does Trivy scan? Filesystems, container images, SBOMs, git repos, Kubernetes, IaC, AWS/rootfs, secrets.
2) Difference: fs vs image? fs scans local directories; image inspects layers and OS/library deps inside images.
3) How to fail CI? Use --severity
+ --exit-code
; often HIGH/CRITICAL in PRs, full in nightly.
4) Why lockfiles matter? They pin versions so SCA is accurate for transitives; scanning only package.json can miss reality.
5) What is --ignore-unfixed
? Hides issues with no known fix to reduce noise; track them in reports.
6) Custom policy usage? Rego with --policy
to encode org rules (e.g., deny privileged pods).
7) Reachability? Trivy focuses on presence/versions; reachability is approximated via IaC/K8s context; combine with runtime data for prioritization.
8) SBOM formats? SPDX, CycloneDX (JSON), used for compliance and later vulnerability correlation.
9) Reduce false positives? Pin versions, scan lockfiles, use .trivyignore
with expiry, and templates highlighting fixable items.
10) Alpine vs Debian Slim? Alpine smaller but musl; Debian/Ubuntu slim often more compatible; choose based on app libs.
11) Private registry auth? Env vars or Docker login; set CI secrets; never echo tokens.
12) Offline scanning? Pre-download DB and set --offline-scan
; mirror cache in artifact store.
13) K8s scan depth? Resources + image refs; combine with trivy image
on those refs for CVEs.
14) IaC vs config? trivy config
evaluates IaC templates before deploy; catch risky settings pre-merge.
15) Attestations? Sign images and attach SBOM/scan attestations (Cosign) so runtime policy can enforce “only scanned & signed.”
16) Speeding scans? Cache DB, reuse layers, scan only changed paths, skip low severities on PRs.
17) Governance? Severity gates, policy packs, ignore expiries, dashboards for MTTR and aging.
18) Typical pipeline order? Build → unit test → trivy fs → image build → trivy image → trivy sbom → sign/attest → deploy (if pass).
19) Secrets detection limits? Pattern/entropy-based; add allowlists, avoid real secrets in tests; rotate on hits.
20) Biggest gotcha? Scanning artifacts not used in prod; prioritize runtime-referenced images and namespaces.