这是我的 template.yaml 文件和我正在运行的 python 脚本。
模板.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: An example SAM template for a Python Lambda function
Resources:
MyS3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: MyS3Bucket
LambdaFunction:
Type: AWS::Serverless::Function
Properties:
Handler: lambda_function.lambda_handler
Runtime: python3.9
Timeout: 10
Policies:
- S3ReadPolicy:
BucketName: !Ref MyS3Bucket
Environment:
Variables:
S3_BUCKET: !Ref MyS3Bucket
Outputs:
LambdaFunctionArn:
Description: "ARN of the Lambda Function"
Value: !GetAtt LambdaFunction.Arn
lambda_function.py
import boto3
s3 = boto3.client('s3')
def lambda_handler(event, context):
# Upload a file to S3 bucket
file_content = b"Your file content here"
s3.put_object(Bucket='MyS3Bucket', Key='example.txt', Body=file_content)
return {
'statusCode': 200,
'body': 'File uploaded successfully!'
}
我使用
sam local start-lambda
启动 SAM 并使用 sam local invoke LambdaFunction
调用 lambda。
但这会引发错误
"An error occurred (AccessDenied) when calling the PutObject operation: Access Denied"
。
我可以仅使用 SAM 创建 S3 存储桶并将文件上传到该 S3 存储桶吗?
我不需要使用像 localstack
这样的第三方应用程序来执行此操作。
有哪些解决方法。请帮忙。
我使用 sam local
start-lambda
启动 SAM 并使用 sam local invoke LambdaFunction 来调用 lambda。
但这会引发错误
"An error occurred (AccessDenied) when calling the PutObject operation: Access Denied"
。
您仅将 S3ReadPolicy 分配给 Lambda 函数。因此,该函数缺少权限 s3:PutObject 。
还添加 S3WritePolicy:https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-policy-template-list.html#s3-write-policy