最近常常須要建立一些S3 Bucket用於備份。每一個新建的Bucket都應該配置lifecycle,自動刪除舊的數據,以便節約空間和開支。ide
豆子寫了一個簡單的Lambda函數來自動實現。每次當咱們建立一個Bucket的時候,他會調用對應的API,Cloudtrail監測到這個事件後,會發送給Cloudwatch, 而後Cloudwatch會自動調用個人函數來建立lifecycle policy。函數
下面是簡單的截圖說明。日誌
建立一個新的Cloudwatch Rulecode
對應的Lambda函數blog
他默認的IAM已經有權限訪問Cloudwatch, 我新建了一個S3的Policy,而後分配給他的IAM role,這樣這個lambda函數能夠訪問Cloudwatch和S3 的權限。事件
下面是Python代碼get
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}')
實際運行的效果,但我建立了一個新的Bucket的時候,他會自動調用這個函數,添加policy。string
下面是Cloudwatch的日誌it
這個是新建的Bucket的lifecycle policy自動化