【问题标题】:serverless-s3-local writing to real S3 bucketserverless-s3-local 写入真实 S3 存储桶
【发布时间】:2021-03-26 12:30:02
【问题描述】:

我在开发过程中使用带有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

【问题讨论】:

    标签: amazon-s3 serverless-framework serverless-framework-offline


    【解决方案1】:

    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 withboto:

    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 将读取离线模式的正确值

    【讨论】:

      猜你喜欢
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 2022-01-23
      • 2022-01-24
      • 2020-07-29
      相关资源
      最近更新 更多