溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2020-08-04 10:35:34 來源:網(wǎng)絡(luò) 閱讀:552 作者:beanxyz 欄目:云計算

最近經(jīng)常需要創(chuàng)建一些S3 Bucket用于備份。每個新建的Bucket都應(yīng)該配置lifecycle,自動刪除舊的數(shù)據(jù),以便節(jié)約空間和開支。

豆子寫了一個簡單的Lambda函數(shù)來自動實現(xiàn)。每次當(dāng)我們創(chuàng)建一個Bucket的時候,他會調(diào)用對應(yīng)的API,Cloudtrail監(jiān)測到這個事件后,會發(fā)送給Cloudwatch, 然后Cloudwatch會自動調(diào)用我的函數(shù)來創(chuàng)建lifecycle policy。

下面是簡單的截圖說明。

創(chuàng)建一個新的Cloudwatch Rule

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

對應(yīng)的Lambda函數(shù)

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

他默認(rèn)的IAM已經(jīng)有權(quán)限訪問Cloudwatch, 我新建了一個S3的Policy,然后分配給他的IAM role,這樣這個lambda函數(shù)可以訪問Cloudwatch和S3 的權(quán)限。

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

下面是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}')

實際運(yùn)行的效果,但我創(chuàng)建了一個新的Bucket的時候,他會自動調(diào)用這個函數(shù),添加policy。

下面是Cloudwatch的日志

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

這個是新建的Bucket的lifecycle policy

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

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI