I set up a Cloudwatch Event CreateBucket
that triggers this automatic policy generating script:
import json
s3 = boto3.client('s3')
def lambda_handler(event, context):
# Get bucket name from the S3 event
bucket_name = event['Records'][0]['s3']['bucket']['name']
# Create a bucket policy
bucket_policy =json.dumps({
"Version": "2012-10-17",
"Statement": [
{
"Sid": "MustBeEncryptedAtRest",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:PutObject",
"Resource": [
"arn:aws:s3:::{bucket_name}",
"arn:aws:s3:::{bucket_name}/*"
],
"Condition": {
"StringNotEquals": {
"s3:x-amz-server-side-encryption": [
"aws:kms"
]
}
}
},
{
"Sid": "MustBeEncryptedInTransit",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:*",
"Resource": [
"arn:aws:s3:::{bucket_name}",
"arn:aws:s3:::{bucket_name}/*"
],
"Condition": {
"Bool": {
"aws:SecureTransport": "false"
}
}
} ] })
# Set the new policy
s3.put_bucket_policy(Bucket=bucket_name, Policy=bucket_policy)
This lambda function should run and place this policy in the created bucket. However, it isnt running properly and testing through lambda interface give me this error:
"stackTrace": [
[
"/var/task/lambda_function.py",
9,
"lambda_handler",
"bucket_name = event['Records'][0]['s3']['bucket']['name']"
]
],
"errorType": "KeyError",
"errorMessage": "'Records'"
}
I need that policy to be attached to a new bucket everytime, no matter the name, but cant seem to figure out why it isnt working
EDIT::
File "/var/task/lambda_function.py", line 10, in lambda_handler
bucket_name = event['details']['requestParameters']['bucketName']
KeyError: 'details'```
Is the new error i get.