This template manages an ECR lifecycle policy to keep the last 30 images tagged with a prefix 'v'.

Terraform Template

resource "aws_ecr_lifecycle_policy" "example" {
  policy = <<-EOF
    {
     "rules": [
     {
     "rulePriority": 1,
     "description": "Keep last 30 images",
     "selection": {
     "tagStatus": "tagged",
     "tagPrefixList": ["v"],
     "countType": "imageCountMoreThan",
     "countNumber": 30
     },
     "action": {
     "type": "expire"
     }
     }
     ]
    }
    
  EOF
  repository = aws_ecr_repository.example.name
}

resource "aws_ecr_repository" "example" {
  name = "example-repo"
}