Skip to content

Instantly share code, notes, and snippets.

@MitchyBAwesome
Last active September 11, 2020 04:36
Show Gist options
  • Save MitchyBAwesome/aa3d3e274b1ca14abd9c68baae9a67d3 to your computer and use it in GitHub Desktop.
Save MitchyBAwesome/aa3d3e274b1ca14abd9c68baae9a67d3 to your computer and use it in GitHub Desktop.
Simple example of creating a repo, setting a policy, pushing an image and trying to delete it ...

Create a directory

mkdir policy-test
cd policy-test

Create a repository

aws ecr create-repository --repository-name {REPO}

Check which ID you're calling as (use this to update the policy in the next step)

aws sts get-caller-identity

Create your policy

cat <<EOF | >> my-policy.json
{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "DenyDelete",
            "Effect": "Deny",
            "Principal": {
            "AWS": "arn:aws:iam::{ACCOUNT_ID}:user/{USER}"
    },
            "Action": [
                "ecr:BatchDeleteImage",
                "ecr:DeleteRepository"
            ]
        }
    ]
}
EOF

Attach your policy

aws ecr set-repository-policy --repository-name {REPO} --policy-text file://my-policy.json

Create a Dockerfile for a basic image

cat <<EOF | >> Dockerfile
FROM busybox:latest
MAINTAINER Mitch Beaumont (mitch@example.com)
EOF

Login to ECR

aws ecr get-login --no-include-email

Build your image

docker build . -t policy-test

Update your image tag

docker tag policy-test:latest ${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/${REPO}:latest

Push your image

docker push ${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/${REPO}:latest

Try to delete your image

aws ecr batch-delete-image --repository-name {REPO} --image-ids imageTag=latest

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment