1

我正在使用 Serverless 框架和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
4

1 回答 1

2

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'),
  });

您可以通过以下方式实现相同的 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,否则将使用真正的存储桶。

同样在自述文件中,还有设置s3localaws 配置文件的说明,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 将读取离线模式的正确值

于 2021-03-26T04:30:02.333 回答