如何使用 CloudFormation 定义 ECR 生命周期策略

How to define an ECR Lifecycle Policy with CloudFormation

为了限制存储库中的图像数量,我想定义一个生命周期策略。由于所有堆栈都是使用 CloudFormation 定义的,因此我也想定义此策略。

例如,我的保单可以是 "keep only the most recent 8 images, no matter if tagged or not"。

解决方案很简单,但由于我找不到任何示例或类似问题(ECR 不是主流,我知道),让我post在这里提供我找到的简单解决方案,它只需要将策略作为 JSON 插入到 CloudFormation 定义中:

MyRepository:
  Type: AWS::ECR::Repository
  Properties:
    LifecyclePolicy:
      LifecyclePolicyText: |
        {
          "rules": [
          {
            "rulePriority": 1,
            "description": "Only keep 8 images",
            "selection": {
              "tagStatus": "any",
              "countType": "imageCountMoreThan",
              "countNumber": 8
            },
            "action": { "type": "expire" }
          }]
        }

当然这很简单,但这是我一直在寻找的起点

您还可以定义对您的 PolicyText 的引用,然后在您的 parameters.json 上对您的保单进行字符串化。

看起来像这样:

template.yml

Parameters:    
  lifecyclePolicyText:
    Description: Lifecycle policy content (JSON), the policy content the pre-fixes for the microservices and the kind of policy (CountMoreThan).  
    Type: String
  repositoryName:
    Description: ECR Repository Name to which we will apply the lifecycle policies. 
    Type: String
  registryId:
    Description: AWS account identification number (12 digits)
    Type: String
    Default: xxxxx
Resources:
  Repository:
    Type: AWS::ECR::Repository
    Properties:
      LifecyclePolicy:
        LifecyclePolicyText: !Ref lifecyclePolicyText
        RegistryId: !Ref registryId
      RepositoryName: !Ref repositoryName
Outputs:    
  Arn:
    Value: !GetAtt Repository.Arn

parameters.json

[
    {
      "ParameterKey": "lifecyclePolicyText",
      "ParameterValue": "{'rules':[{'rulePriority':1,'description':'Only keep 8 images','selection':{'tagStatus':'any','countType':'imageCountMoreThan','countNumber':8},'action':{'type':'expire'}}]}"
    }, 
    {
      "ParameterKey": "repositoryName",
      "ParameterValue": "xxxx"
    }
  ]