如何解决serverless-s3-local 写入真实的 S3 存储桶
我在开发过程中使用带有 serverless-s3-local 插件的无服务器框架来测试我的代码。但是,尽管处于离线模式,但正在写入真正的 S3 存储桶。如何在离线模式下更改我的配置以使用本地假 s3 存储桶?
相关 serverless.yml 部分:
plugins:
- serverless-stack-output
- serverless-plugin-include-dependencies
- serverless-layers
- serverless-deployment-bucket
- serverless-s3-local
- serverless-offline
custom:
#...
s3:
bucketName: test-s3-buck
host: localhost
serverless-offline:
ignoreJWTSignature: true
httpPort: 4000
noAuth: true
directory: /tmp
resources:
Resources:
#...
Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: ${self:custom.s3.bucketName}
端点调用 S3:
import boto3
def post(event,context):
s3_path = "/test.txt"
body = "test"
encoded_string = body.encode("utf-8")
s3 = boto3.resource("s3")
bucket_name = "test-s3-buck"
s3.Bucket(bucket_name).put_object(Key=s3_path,Body=encoded_string)
response = {
"statusCode": 200,"body": "Created."
}
return response
离线启动无服务器:
serverless offline start
解决方法
在 serverless-s3-local 中的自述文件中,我们有:
const S3 = new AWS.S3({
s3ForcePathStyle: true,accessKeyId: 'S3RVER',// This specific key is required when working offline
secretAccessKey: 'S3RVER',endpoint: new AWS.Endpoint('http://localhost:4569'),});
你可以实现the same with boto
:
import boto3
client = boto3.client(
's3',aws_access_key_id='S3RVER',aws_secret_access_key='S3RVER'
)
这意味着,当您运行 serverless offline start
时,您需要将 aws 访问密钥 ID 设置为 S3RVER
,将 aws 秘密访问密钥设置为 S3RVER
,否则将使用真正的存储桶.
也在自述文件中,有设置 s3local
aws 配置文件的说明,https://github.com/ar90n/serverless-s3-local#triggering-aws-events-offline
实现它的另一种方法是使用环境变量运行您的命令:
AWS_ACCESS_KEY_ID=S3RVER AWS_SECRET_ACCESS_KEY=S3RVER serverless offline start
这样,代码中的 aws-sdk 将读取离线模式的正确值
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。