Recently, we often need to create some S3 Bucket for backup. Each new Bucket should be configured lifecycle, automatically delete old data in order to save space and money.
Beans write a simple Lambda functions to automate. Every time we create a Bucket, he would call the corresponding API, after Cloudtrail to monitor this event, will be sent to Cloudwatch, then Cloudwatch will automatically call my function to create lifecycle policy.
Here is a brief description of the screenshot.
Create a new Cloudwatch Rule
Lambda function corresponding
His default IAM has access to Cloudwatch, I created a Policy S3, and then assigned to him IAM role, so this lambda function can access Cloudwatch and S3.
Here is the Python code
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}')
The effect of actually running, but I created a new Bucket, he will automatically call this function, add the policy.
The following is a log Cloudwatch
This is a new Bucket of lifecycle policy