AWS Lambda 自動化和 Python - 自動創建S3 Bucket lifecycle

最近經常需要創建一些S3 Bucket用於備份。每個新建的Bucket都應該配置lifecycle,自動刪除舊的數據,以便節約空間和開支。

豆子寫了一個簡單的Lambda函數來自動實現。每次當我們創建一個Bucket的時候,他會調用對應的API,Cloudtrail監測到這個事件後,會發送給Cloudwatch, 然後Cloudwatch會自動調用我的函數來創建lifecycle policy。

下面是簡單的截圖說明。

創建一個新的Cloudwatch Rule

AWS Lambda 自動化和 Python - 自動創建S3 Bucket lifecycle

對應的Lambda函數

AWS Lambda 自動化和 Python - 自動創建S3 Bucket lifecycle

他默認的IAM已經有權限訪問Cloudwatch, 我新建了一個S3的Policy,然後分配給他的IAM role,這樣這個lambda函數可以訪問Cloudwatch和S3 的權限。

AWS Lambda 自動化和 Python - 自動創建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}')

實際運行的效果,當我創建了一個新的Bucket的時候,他會自動調用這個函數,添加policy。

下面是Cloudwatch的日誌

AWS Lambda 自動化和 Python - 自動創建S3 Bucket lifecycle

這個是新建的Bucket的lifecycle policy

AWS Lambda 自動化和 Python - 自動創建S3 Bucket lifecycle

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章