AWS Lambda 自動化和 Python - 自動創(chuàng)建S3 Bucket lifecycle

發(fā)布時間:2024-04-19
云計算
最近經常需要創(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
上一個:河北uv光解活性炭凈化設備
下一個:win7刪除文件很慢解決辦法(win7系統(tǒng)文件清理)

巧做花園手工燈
度假區(qū)新型污水處理設備
不能計入開辦費的支出有哪些?
哪些人群不適合飲用黃山毛峰?
哪些遺囑是無效遺囑
如何處理有效建筑承包合同糾紛?
熟石膏粉水分測量儀應用和測試方法
徇私舞弊假釋罪既遂的刑事責任是什么?
無錫惠山污水管道疏通,馬桶疏通、下水道疏通快捷上門
蘋果筆記本裝win10教程圖解(蘋果筆記本安裝win10教程)
十八禁 网站在线观看免费视频_2020av天堂网_一 级 黄 色 片免费网站_绝顶高潮合集Videos