云計算
最近經常需要創(chuàng)建一些s3 bucket用于備份。每個新建的bucket都應該配置lifecycle,自動刪除舊的數(shù)據(jù),以便節(jié)約空間和開支。
豆子寫了一個簡單的lambda函數(shù)來自動實現(xiàn)。每次當我們創(chuàng)建一個bucket的時候,他會調用對應的api,cloudtrail監(jiān)測到這個事件后,會發(fā)送給cloudwatch, 然后cloudwatch會自動調用我的函數(shù)來創(chuàng)建lifecycle policy。
下面是簡單的截圖說明。
創(chuàng)建一個新的cloudwatch rule
對應的lambda函數(shù)
他默認的iam已經有權限訪問cloudwatch, 我新建了一個s3的policy,然后分配給他的iam role,這樣這個lambda函數(shù)可以訪問cloudwatch和s3 的權限。
下面是python代碼
import loggingimport boto3from botocore.exceptions import clienterrorlifecycle_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 truedef 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}\\\')實際運行的效果,但我創(chuàng)建了一個新的bucket的時候,他會自動調用這個函數(shù),添加policy。
下面是cloudwatch的日志
這個是新建的bucket的lifecycle policy