Lab:AWS ECR Image Scanning for Vulnerabilities

Prerequisites

Configure AWS CLI

  • Configure AWS CLI with your credentials:
    aws configure
    
    • Provide AWS Access Key ID, Secret Access Key, Default region (e.g., us-west-2), and Default output format (e.g., json).

Hands on Lab

  • Change the directory.

    cd /workspaces/ecr_eks_security_masterclass_public/docker-lab
    
  • Fetch your AWS Account ID:

    ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
    
  • Create a new repository in Amazon ECR.

    aws ecr create-repository --repository-name k8svillage-ecr-repo --region us-west-2 --image-scanning-configuration scanOnPush=true
    
  • Verify the repository creation:

    aws ecr describe-repositories --repository-name k8svillage-ecr-repo --region us-west-2
    
  • Log in to your ECR registry.

    aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin ${ACCOUNT_ID}.dkr.ecr.us-west-2.amazonaws.com
    
  • Create a sample Dockerfile, for building image.

    cat <<EOF > Dockerfile
    FROM ubuntu:latest
    ENV DEBIAN_FRONTEND=noninteractive
    RUN apt-get update && apt-get install -y curl && apt-get clean
    CMD ["bash"]
    EOF
    
  • Build the Docker image:

    docker build -t k8svillage-ecr-repo .
    
  • Tag the Docker image for ECR:

    docker tag k8svillage-ecr-repo:latest ${ACCOUNT_ID}.dkr.ecr.us-west-2.amazonaws.com/k8svillage-ecr-repo:latest
    
  • Push the Docker image to ECR:

    docker push ${ACCOUNT_ID}.dkr.ecr.us-west-2.amazonaws.com/k8svillage-ecr-repo:latest
    
  • Retrieve image details dynamically, to verify the results.

    IMAGE_DIGEST=$(aws ecr describe-images --repository-name k8svillage-ecr-repo --region us-west-2 --query 'imageDetails[0].imageDigest' --output text)
    
  • Retrieve scan findings.

    aws ecr describe-image-scan-findings --repository-name k8svillage-ecr-repo --image-id imageDigest=${IMAGE_DIGEST} --region us-west-2
    

In case on error in the scan, try in the another region.

Optional: View Scan Results in AWS Console

  • Navigate to the Amazon ECR service in the AWS Management Console.
  • Select your repository, then select the image.
  • Click on Vulnerabilities to view detailed scan results.

Clean Up Resources

  • Delete the ECR repository:

    aws ecr delete-repository --repository-name k8svillage-ecr-repo --region us-west-2 --force
    
  • Remove the Docker image locally:

    docker rmi ${ACCOUNT_ID}.dkr.ecr.us-west-2.amazonaws.com/k8svillage-ecr-repo:latest
    
  • Delete the Dockerfile:

    rm Dockerfile
    

Note: In case of error StartImageScan seems to be disabled when Enhanced scanning is enabled, visit repost.aws