0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ECS タスク定義ファミリーの古いリビジョンを削除

Last updated at Posted at 2024-06-07

issue

  • タスク定義のリビジョンが溜まりすぎている

対策

  • ライフサイクルがないようでまたもやLambda出動

Lambda

lambda_handler Python3.12
import json
import time
import boto3
import botocore

def list_all_task_definitions(ecs_client):
    paginator = ecs_client.get_paginator('list_task_definitions')
    task_definitions = []

    for page in paginator.paginate(status='ACTIVE'):
        task_definitions.extend(page['taskDefinitionArns'])

    return task_definitions

def list_task_definition_revisions(ecs_client, task_definition_family):
    paginator = ecs_client.get_paginator('list_task_definitions')
    revisions = []

    for page in paginator.paginate(familyPrefix=task_definition_family, status='ACTIVE', sort='ASC'):
        revisions.extend(page['taskDefinitionArns'])

    return revisions

def cleanup_old_revisions():
    """すべてのタスク定義ファミリーの古いリビジョンを削除する"""
    ecs_client = boto3.client('ecs')
    task_definitions = list_all_task_definitions(ecs_client)
    task_definition_families = set([arn.split('/')[-1].split(':')[0] for arn in task_definitions])

    for family in task_definition_families:
        revisions = list_task_definition_revisions(ecs_client, family)

        # 最新50個維持
        if len(revisions) > 50:
            revisions_to_delete = revisions[:-50]
            for i, revision in enumerate(revisions_to_delete):
                try:
                    print(f"Deregistering task definition: {revision}")
                    ecs_client.deregister_task_definition(taskDefinition=revision)
                except botocore.exceptions.ClientError as error:
                    if error.response['Error']['Code'] == 'ThrottlingException':
                        print("Throttling exception occurred. Waiting before retrying...")
                        time.sleep(2 ** (i // 30))  # 指数関数的バックオフ
                    else:
                        raise error

def lambda_handler(event, context):
    cleanup_old_revisions()
    return {
        'statusCode': 200,
        'body': json.dumps('Old revisions cleaned up successfully')
    }

EventBridge (CloudWatch Events)

定期実行

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?