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;
Using Terraform for_each:
locals {
repositories = toset(["foo", "bar", "baz"])
}
resource "aws_ecr_repository" "myrepository" {
for_each = local.repositories
name = each.value
}
resource "aws_ecr_lifecycle_policy" "untagged_removal_policy" {
for_each = local.repositories
repository = aws_ecr_repository.myrepository[each.value].name
policy = jsonencode(
{
"rules": [
{
"rulePriority": 1,
"description": "Expire untagged images after 7 days",
"selection": {
"tagStatus": "untagged",
"countType": "sinceImagePushed",
"countUnit": "days",
"countNumber": 7
},
"action": {
"type": "expire"
}
}
]})
}
To output the repository names and URLs, use for:
output "myrepositories" {
value = {
for repo in aws_ecr_repository.myrepository : repo.name => repo.repository_url
}
description = "Object mapping from repository name (string) to repository URL (string)"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With