我设置了CreateBucket触发此自动策略生成脚本的 Cloudwatch 事件:
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)
此 lambda 函数应运行并将此策略放置在创建的存储桶中。但是,它运行不正常,通过 lambda 接口进行测试给了我这个错误:
"stackTrace": [
[
"/var/task/lambda_function.py",
9,
"lambda_handler",
"bucket_name = event['Records'][0]['s3']['bucket']['name']"
]
],
"errorType": "KeyError",
"errorMessage": "'Records'"
}
无论名称如何,我每次都需要将该策略附加到一个新存储桶,但似乎无法弄清楚它为什么不起作用
编辑::
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.