DEV Community

Jeg
Jeg

Posted on

Scan container images used by pods running in a Kubernetes namespace

Below is a shell script that will scan all the images in the kubernetes-dashboard namespace and save the results to JSON files:

cat << 'EOF' > scan_images.sh

#!/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 to speed up the scan (for demonstration purposes)
    trivy image --severity HIGH,CRITICAL $image --scanners vuln --quiet --format json --output $namespace/$(basename $image).json
done
Enter fullscreen mode Exit fullscreen mode

EOF

The script uses a kubectl command to get a list of all the images used by Pods in the kubernetes-dashboard Namespace.

The script could be modified to scan all the images in the cluster but only one Namespace is considered to reduce the amount of time.

bash scan_images.sh

The results are saved to JSON files.

Top comments (0)