Scan container images used by pods running in a Kubernetes namespace
Source: Dev.to
Script
#!/bin/bash
namespace="kubernetes-dashboard"
# Create a directory for the scan results
mkdir -p "$namespace"
# Get a list of all the images used by Pods in the Namespace
images=($(kubectl get pods -n "$namespace" -o jsonpath='{.items[*].spec.containers[*].image}' | sort | uniq))
# Loop through the images and scan each one
for image in "${images[@]}"; do
echo "Scanning image: $image"
# Scan the image with --scanners vuln to skip scanning for secrets (faster)
trivy image --severity HIGH,CRITICAL "$image" \
--scanners vuln --quiet --format json \
--output "$namespace/$(basename "$image").json"
done
Usage
bash scan_images.sh
The script scans all images in the kubernetes-dashboard namespace and saves the Trivy scan results as JSON files in a directory named after the namespace. Adjust the namespace variable or remove it to scan images across the entire cluster.