Managing permissions for multiple Amazon ECR repositories can be tedious and error-prone, especially in accounts with many repositories. Currently, ECR does not support applying a resource-based IAM policy to all repositories at once.
Objective
The goal is to streamline the process of applying a standard repository policy—such as enabling cross-account access—to all ECR repositories within your AWS account. The solution utilizes a shell script that: Lists all ECR repositories using the AWS CLI. Iteratively applies a predefined policy to each repository.
Script to Set Repository Policy
#!/bin/bash
# Fetch and iterate over all ECR repository names
for i in $(aws ecr describe-repositories --output text | awk '{print $6}')
do
echo "Setting policy on repository $i"
aws ecr set-repository-policy --repository-name $i --policy-text file://policy.json
done
Notes:
- This script must be run on a Linux system with AWS CLI installed and configured.
- The user or role running this script must have the IAM permissions such as ecr:DescribeRepositories and ecr:SetRepositoryPolicy
- Save your desired repository policy as policy.json in the same directory from where you run the script.
Example Policy (Cross-Account Access)
Here’s a sample policy.json that grants a specific external AWS account access to push and pull images from your ECR repositories:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowPushPull",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::account-id:root"
},
"Action": [
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
"ecr:BatchCheckLayerAvailability",
"ecr:PutImage",
"ecr:InitiateLayerUpload",
"ecr:UploadLayerPart",
"ecr:CompleteLayerUpload"
]
}
]
}
Replace "account-id" with the actual AWS account number you wish to grant access to.
Note : Always test the script in a non-production environment before applying it broadly.