最近、私たちはしばしば、バックアップのためにいくつかのS3バケットを作成する必要があります。それぞれの新しいバケットは自動的にスペースとお金を節約するために古いデータを削除し、ライフサイクルを構成する必要があります。
豆は、自動化するために、簡単なラムダ関数を記述します。私たちはバケツを作成するたびに、彼はこのイベントを監視するためにCloudtrailた後、対応するAPIを呼び出すと、CloudWatchのに送信され、その後、CloudWatchのは、自動的にライフサイクルポリシーを作成するために私の関数を呼び出します。
ここでは、スクリーンショットの簡単な説明です。
新しいCloudWatchのルールを作成します。
ラムダ関数は、対応します
彼のデフォルトIAMはCloudWatchのへのアクセスを持って、私は政策S3を作成し、その後、彼IAMロールに割り当てられているので、このラムダ関数は、CloudWatchのとS3にアクセスすることができます。
ここではPythonのコードがあります
import logging
import boto3
from botocore.exceptions import ClientError
lifecycle_config_settings = {
'Rules': [
{'ID': 'Delete Rule',
'Filter': {'Prefix': ''},
'Status': 'Enabled',
'Expiration': { 'Days':100 }}
]}
def put_bucket_lifecycle_configuration(bucket_name, lifecycle_config):
"""Set the lifecycle configuration of an Amazon S3 bucket
:param bucket_name: string
:param lifecycle_config: dict of lifecycle configuration settings
:return: True if lifecycle configuration was set, otherwise False
"""
# Set the configuration
s3 = boto3.client('s3')
try:
s3.put_bucket_lifecycle_configuration(Bucket=bucket_name,
LifecycleConfiguration=lifecycle_config)
except ClientError as e:
return False
return True
def lambda_handler111(event, context):
# TODO implement
test_bucket_name = event.get('detail').get('requestParameters').get('bucketName')
print(event)
print(event.get('detail').get('requestParameters').get('bucketName'))
success = put_bucket_lifecycle_configuration(test_bucket_name,lifecycle_config_settings)
if success:
# logging.info('The lifecycle configuration was set for {test_bucket_name}')
print('The lifecycle configuration was set for {test_bucket_name}')
効果が実際に実行されているが、私は新しいバケツを作成し、彼は自動的にポリシーを追加し、この関数を呼び出します。
以下は、ログCloudWatchのです
これは、ライフサイクルポリシーの新しいバケツです