Lab: AWS ECR Immutable Image Tag
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-east-1
), and Default output format (e.g.,json
).
- Provide AWS Access Key ID, Secret Access Key, Default region (e.g.,
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 an ECR repository with an immutable image tag policy:
aws ecr create-repository --repository-name immutable-repo --region us-east-1 --image-tag-mutability IMMUTABLE
-
Verify the repository creation:
aws ecr describe-repositories --repository-name immutable-repo --region us-east-1
-
Log in to your ECR registry:
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin ${ACCOUNT_ID}.dkr.ecr.us-east-1.amazonaws.com
-
Create a sample Dockerfile:
cat <<EOF > Dockerfile FROM alpine:latest RUN apk add --no-cache curl CMD ["sh"] EOF
-
Build the Docker image:
docker build -t immutable-repo .
-
Tag the Docker image for ECR:
docker tag immutable-repo:latest ${ACCOUNT_ID}.dkr.ecr.us-east-1.amazonaws.com/immutable-repo:1.0.0
-
Push the Docker image to ECR:
docker push ${ACCOUNT_ID}.dkr.ecr.us-east-1.amazonaws.com/immutable-repo:1.0.0
-
Try pushing another image with the same tag to test the immutability:
docker push ${ACCOUNT_ID}.dkr.ecr.us-east-1.amazonaws.com/immutable-repo:1.0.0
-
Now check for immutability.
-
Change the
CMD
or add/remove a line to create a new layer:sed -i 's/sh/bash/' Dockerfile
-
Rebuild the image with changes.
cat Dockerfile docker build --no-cache -t immutable-repo .
-
Tag and attempt to push the modified image.
docker tag immutable-repo:latest ${ACCOUNT_ID}.dkr.ecr.us-east-1.amazonaws.com/immutable-repo:1.0.0 docker push ${ACCOUNT_ID}.dkr.ecr.us-east-1.amazonaws.com/immutable-repo:1.0.0
There should be an error indicating that the tag is immutable.
The push should fail with an error.
tag invalid: The image tag '1.0.0' already exists in the 'immutable-repo' repository and cannot be overwritten because the repository is immutable.
Optional: View Repository in AWS Console
- Navigate to the Amazon ECR service in the AWS Management Console.
- Select your repository (
immutable-repo
). - Verify the images and the immutable tag policy.
Clean Up Resources
-
Delete the ECR repository and all its contents:
aws ecr delete-repository --repository-name immutable-repo --region us-east-1 --force
-
Remove the Docker image locally:
docker rmi ${ACCOUNT_ID}.dkr.ecr.us-east-1.amazonaws.com/immutable-repo:1.0.0
-
Delete the Dockerfile:
rm Dockerfile