在 localstack 上 运行 与在 AWS Lambda 上相比,boto3 资源需要更多参数

boto3 resource requires more parameters when running on localstack vs when on AWS Lambda

问题

我在 AWS 上部署的 Lambdas 之前使用 boto3 clients/resources 只有服务名称,但是部署在 Localstack 中的 Lambdas 仅在 region_nameaws_access_key_idaws_secret_key_id 时有效, 和 endpoint_url.

如何消除对它的需求?

我试过的

我试过在没有额外参数的情况下在 Localstack 中部署 Lambda,但出现如下错误:

Exception: ('Unable to get handler function from lambda code.', NoRegionError('You must specify a region.',))

botocore.exceptions.ClientError: An error occurred (UnrecognizedClientException) when calling the Scan operation: The security token included in the request is invalid.

我想要的

理想情况(就像我目前在 AWS 上的 Lambda 一样):

dynamodb = boto3.client('dynamodb')

当前的解决方法(部署到 Localstack 时):

dynamodb = boto3.client('dynamodb', region_name='eu-west-2', 
                        aws_access_key_id="", aws_secret_access_key="",
                        endpoint_url='http://localhost:4569')

不,你不能阻止在 localstack 中使用它们。

区域、aws_access_key_id、端点等总是需要的——它似乎不在 Lambda 控制台上,只是因为当您在 Lambda 上 运行 时,Lambda 环境被注入许多默认值,所以即使您不提供这些变量,它仍然有效。

但是,如果您不想在代码中指定这些值,您仍然可以在 运行 localstack 时在环境变量中指定它们:

https://github.com/localstack/localstack#configurations

您需要传入以下环境变量:

SERVICES=lambda:4569
DEFAULT_REGION=eu-west-2

要放入与 IAM 访问密钥相关的环境变量,请使用这个不错的 lil 实用程序:https://github.com/jaymecd/aws-profile/blob/master/aws-profile

通过所有这些努力(不是很多,但仍然有一些),您可以 "remove the need of specifying those in your code" -- 但是,您仍然只是将它们移动到环境变量。

一个好处是,这样本地看起来与您生产中的代码更加一致。