网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

AWSLambda自动化和Python-自动创建S3Bucketlifecycle

最近经常需要创建一些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


文章名称:AWSLambda自动化和Python-自动创建S3Bucketlifecycle
文章位置:http://bjjierui.cn/article/jisgsc.html

其他资讯