I follow this doc to set the same policy for all ECR repos
This script simply lists those repos to a file and set the policy one by one as in JSON file.
I usually set the policy based on count so that count of images is maintained
blog link
create a file policy.json
<policy.json>
{
"rules": [
{
"rulePriority": 1,
"description": "Expire images more than 5",
"selection": {
"tagStatus": "any",
"countType": "imageCountMoreThan",
"countNumber": 5
},
"action": {
"type": "expire"
}
}
]}
Note : This Script would list all ECR repo and set the same policy(policy.json). Here I set the image count to 5, So there would be a max of 5 ECR images in the repo.
#!/bin/bash
# An anilaugustinechalissery initiative ;)
read -p "Enter the aws profile name please: " profile
export AWS_PROFILE=$profile
echo "aws profile is "$AWS_PROFILE
aws ecr describe-repositories --output yaml --query
'repositories[*].repositoryName[]' | awk '{print $2}' >
repolist.txt
echo "Repo list "
echo "========================================="
cat repolist.txt
echo "========================================="
echo "to cancel Ctrl + z in 10s"
sleep 10s
for i in $(cat repolist.txt)
do
echo "Setting lifecycle policy for "$i
aws ecr put-lifecycle-policy --repository-name $i --lifecycle-policy-text "file://policy.json"
done