I curious if there is a way to set one common lifecycle policy, that will be applied to all repositories in ECR?
Currently, as I understand there is no way to do it.
One approach that I'm thinking about is to use JSON definition of lifecycle policies and apply it to all repositories with AWS CLI (can be a bit automated). But this thing should be run every time as a new repository is created that adds complexity.
There is still no default ECR Lifecycle policy template or something. So, as you mentioned, you may use aws cli way, and assign this to execute from somewhere, like Lambda, or k8s job:
Get all repositories names:
repositories=($(aws ecr describe-repositories --profile=$profile --output text --query "repositories[*].repositoryName"))
Apply policy to each repository:
for repository in "${repositories[@]}";
do
aws ecr put-lifecycle-policy --profile=$profile --repository-name $repository --lifecycle-policy-text "file://policy.json"
done;
you can use Terraform for that
resource "aws_ecr_lifecycle_policy" "untagged_removal_policy" {
count = "${length(split(",",local.registries))}"
depends_on = [ "aws_ecr_repository.ecr_repositories" ]
repository = "${aws_ecr_repository.ecr_repositories.*.name[count.index]}"
policy = <<EOF
{
"rules": [
{
"rulePriority": 1,
"description": "Expire Docker images older than 7 days",
"selection": {
"tagStatus": "untagged",
"countType": "sinceImagePushed",
"countUnit": "days",
"countNumber": 7
},
"action": {
"type": "expire"
}
}
]
}
EOF
}
I'm using CloudFormation mapping to define one policy and then apply it on all repositories with one line:
Mappings:
ECRPolicy:
DevPolicy:
RemoveUntagged: |
{
"rules": [
{
"rulePriority": 1,
"description": "Expire images older than 3 days",
"selection": {
"tagStatus": "untagged",
"countType": "sinceImagePushed",
"countUnit": "days",
"countNumber": 3
},
"action": {
"type": "expire"
}
}
]
}
And for the repos it's just:
ECRRepository:
Type: AWS::ECR::Repository
Properties:
RepositoryName: !Sub ${ECRRepositoryName}-dev
RepositoryPolicyText:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- ecr:GetAuthorizationToken
- ecr:BatchCheckLayerAvailability
- ecr:GetDownloadUrlForLayer
- ecr:GetRepositoryPolicy
- ecr:DescribeRepositories
- ecr:ListImages
- ecr:DescribeImages
- ecr:BatchGetImage
Principal:
AWS:
- !Sub arn:aws:iam::${DevAccount}:root
Sid: AllowCrossAccountPull
LifecyclePolicy:
LifecyclePolicyText: !FindInMap [ECRPolicy, DevPolicy, RemoveUntagged]