Skip to content

Instantly share code, notes, and snippets.

@puneetpunj
Created August 14, 2023 03:57
Show Gist options
  • Select an option

  • Save puneetpunj/385979ee454d41a4c4a5c5ce644bd6ce to your computer and use it in GitHub Desktop.

Select an option

Save puneetpunj/385979ee454d41a4c4a5c5ce644bd6ce to your computer and use it in GitHub Desktop.
AWSTemplateFormatVersion: '2010-09-09'
Resources:
S3LifecycleFunction:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
import boto3
def put_lifecycle_policy(region: str, bucket: str, policy):
s3 = boto3.client('s3', region_name=region)
try:
response = s3.put_bucket_lifecycle_configuration(Bucket=bucket, LifecycleConfiguration=policy)
except Exception as e:
print(str(e))
return response
def lambda_handler(event, context):
policy = {
'Rules': [{'ID': 'delete-multipart-objects-after-7-days',
'Filter': {'Prefix': ''}, 'Status': 'Enabled',
'AbortIncompleteMultipartUpload': {'DaysAfterInitiation': 7}}]}
bucket_name = event['detail']['requestParameters']['bucketName']
region_name = event['detail']['awsRegion']
print(f'applying policy for bucket {bucket_name}')
return put_lifecycle_policy(region_name, bucket_name, policy)
Handler: index.lambda_handler
Timeout: 300
Runtime: python3.8
FunctionName: add-mpu-s3--lifecycle-policy-for-new-buckets
Role: !GetAtt LambdaRole.Arn
LambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Path: /
Policies:
- PolicyName: 's3-lifecycle'
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- "s3:PutLifecycleConfiguration"
Resource: arn:aws:s3:::*
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: arn:aws:logs:*:*:log-group:/aws/lambda/*
S3LifecycleCreationEventRule:
Type: AWS::Events::Rule
Properties:
EventPattern:
source:
- aws.s3
detail-type:
- AWS API Call via CloudTrail
detail:
eventSource:
- s3.amazonaws.com
eventName:
- CreateBucket
State: ENABLED
Targets:
- Arn: !GetAtt S3LifecycleFunction.Arn
Id: TargetFunctionV1
EventInvokePermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt S3LifecycleFunction.Arn
Principal: events.amazonaws.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment