Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set one lifecycle policy for all repositories in ECR

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.

like image 885
Alex Avatar asked Apr 25 '18 09:04

Alex


2 Answers

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:

  1. Get all repositories names:

    repositories=($(aws ecr describe-repositories --profile=$profile --output text --query "repositories[*].repositoryName"))
    
  2. 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;
    
like image 87
Vadim Yangunaev Avatar answered Oct 17 '22 07:10

Vadim Yangunaev


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)"
}
like image 2
hertzsprung Avatar answered Oct 17 '22 07:10

hertzsprung