Skip to content
Advertisements

AWS ECR handy bash to add read-only access policies for cross-account access

AWS ECR is widely used service these days in aws environment to store docker images. In large organization, specially when there are multiple aws accounts and 1000+ Micro Services, your ECR repo can be located in one aws account while other aws account simply trying to use pre-built images. In this case you have to grant read-only access to those images for cross accounts.  Unfortunately aws doesn’t support adding policies to entire ECR region. This means you have to add policies one by one for each repo. Doing this is very hard and will required significant amount of time. To address this issue I created a simple bash script which will simplify this process.

First create policy.json file with following content,

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "read-only-cross-account-acccess",
            "Effect": "Allow",
            "Principal": {
                "AWS": [
                    "arn:aws:iam::#replace-me-with-aws-account-1#:root",
                    "arn:aws:iam::#replace-me-with-aws-account-2#:root"
                ]
            },
            "Action": [
                "ecr:GetDownloadUrlForLayer",
                "ecr:BatchGetImage",
                "ecr:BatchCheckLayerAvailability"
            ]
        }
    ]
}

Now find all ecr image repository and save it into file.

aws ecr describe-repositories --region us-east-1 | jq -r '.[] | .[] | .repositoryName' > repolist.txt

Finally use while loop to add permission.

while read repo; do echo  $repo; aws ecr set-repository-policy --repository-name $repo --region us-east-1 --policy-text file://policy.json; done < repolist.txt

And all set. Now you can access images from other accounts as well, considering you have granted ECR access to those user who is trying to access.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: