0

I want to write a lambda function with Python, to enable S3 bucket default encryption, if the newly created bucket is not encryption enabled

Need to have following steps

  • Trigger Lambda function when new S3 bucket is created
  • If Default encryption is not enabled, it will enable automatically
  • SNS topic will be triggered and send email to administrator & bucket creator/owner

Following lambda function, I have created will encrypt any existing bucket periodically. I want to extend it to trigger at new bucket creation

import json

import boto3


def lambda_handler(event, context):
    s3 = boto3.client("s3")
    response = s3.list_buckets()
    buckets = [bucket['Name'] for bucket in response['Buckets']]
    status = 401
    unencrypted_buckets = []
    for bucket in buckets:
        try:
            s3.get_bucket_encryption(Bucket=bucket)
            print(f"Bucket {bucket} has already Encryption enabled")
        except s3.exceptions.ClientError:
            unencrypted_buckets.append(bucket)

    encryption_enabled_buckets = []
    for unencrypted_bucket in unencrypted_buckets:
        try:
            print(f"Bucket {unencrypted_bucket} has no Encryption enabled")
            s3.put_bucket_encryption(
                Bucket=unencrypted_bucket,
                ServerSideEncryptionConfiguration={
                    'Rules': [
                        {
                            'ApplyServerSideEncryptionByDefault':
                                {
                                    'SSEAlgorithm': 'AES256'
                                }
                        }
                    ]
                }
            )
            encryption_enabled_buckets.append(unencrypted_bucket)
            status = 200
        except s3.exceptions.ClientError:
            status = 500
            break

    return {
        'statusCode': status,
        'details': 'Default encryption enabled',
        'encryption enabling success': encryption_enabled_buckets,
        'encryption enabling failed': list(set(unencrypted_buckets) - set(encryption_enabled_buckets)) + list(
            set(encryption_enabled_buckets) - set(unencrypted_buckets))
    }

1 Answers1

2

You may not have to code this at all. Consider using AWS Config Rules for this, and other, compliance requirements.

See AWS Config managed rules:

AWS Config can send notifications via SNS and here is an example of How can I be notified when an AWS resource is non-compliant using AWS Config?

jarmod
  • 71,565
  • 16
  • 115
  • 122