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