AWS CloudFormation で ECR のライフサイクルを設定する

AWS ECR を使ってコンテナを更新していくと知らないうちにイメージが貯まっていきます。
Lifecycle Policy を設定すれば、古いイメージを自動で削除できます。

CloudFormation で設定する方法を見ると、 LifecyclePolicyTextString で設定すれば、 ECR の Lifecycle Policy を設定できます。

docs.aws.amazon.com

ですが、 Amazon ECR ライフサイクルポリシー を見ると分かるのですが、 JSON で設定するようになっています。

Lifecycle Policy の条件とその JSON は以下の様になります。

  • ルールの優先順位 : 1
  • イメージのステータス : タグ付けなし
  • 一致条件 : 次の数値を超えるイメージ数 10
{
  "rules": [
    {
      "action": {
        "type": "expire"
      },
      "selection": {
        "countType": "imageCountMoreThan",
        "countNumber": 10,
        "tagStatus": "untagged"
      },
      "description": "delete cycle",
      "rulePriority": 1
    }
  ]
}

YAML では > を使うと改行をスペースに置き換えられるのでそのまま JSON を書くことで String として扱うことができます。

        LifecyclePolicyText: >
          {
            "rules": [
              {
                "action": {
                  "type": "expire"
                },
                "selection": {
                  "countType": "imageCountMoreThan",
                  "countNumber": 10,
                  "tagStatus": "untagged"
                },
                "description": "delete cycle",
                "rulePriority": 1
              }
            ]
          }

試してみた CloudFormation のリソースを残しておきます。

Parameters:
  RepositoryName:
    Type: String
  ImageName:
    Type: String

Resources:
  Repository:
    Type: AWS::ECR::Repository
    Properties:
      RepositoryName: !Ref RepositoryName
      RepositoryPolicyText:
        Version: "2012-10-17"
        Statement:
          - Sid: AllowPushPull
            Effect: Allow
            Principal:
              AWS:
                - !Sub arn:aws:iam::${AWS::AccountId}:user/${ImageName}
            Action:
              - "ecr:*"
      LifecyclePolicy:
        LifecyclePolicyText: >
          {
            "rules": [
              {
                "action": {
                  "type": "expire"
                },
                "selection": {
                  "countType": "imageCountMoreThan",
                  "countNumber": 10,
                  "tagStatus": "untagged"
                },
                "description": "delete cycle",
                "rulePriority": 1
              }
            ]
          }
        RegistryId: !Ref AWS::AccountId

参考