如何在 CDK 中制作 lambda 时设置 dockerfile 和环境变量

How to set the dockerfile and environment variables while making lambda in CDK

我在 template.yml

中有 SAM 项目
Globals:
  Function:
    Timeout: 30
    Environment:
      Variables:
        DBNAME: !Ref DBNAME

Resources:
  MessageFunction:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      Architectures:
        - x86_64
      Events:
        Message:
          Type: Api
          Properties:
            Path: /message
            Method: post
    Metadata:
      Dockerfile: Dockerfile.message
      DockerContext: ./botapp
      DockerTag: python3.9-v1

然后像这样部署

sam deploy --guided --parameter-overrides DBNAME=mydb

这意味着我将设置环境变量 DBNAME=mydb 并从 Dockerfile.message 构建图像。

目前效果很好。

不过现在我想把它移到 cdk

所以,在cdk中我先写了这段代码

const messageLambda = new lambda.DockerImageFunction(this, "BotLambda", {
  code: lambda.DockerImageCode.fromImageAsset("chatbot-sam/botapp"),
});

但是我想设置 dockerfileenvironment variables

例如

const messageLambda = new lambda.DockerImageFunction(this, "BotLambda", {
  code: lambda.DockerImageCode.fromImageAsset(
         "chatbot-sam/botapp",
         dockerfile: Dockerfile.message,
         enviroment_variables: { DBNAME:'mydb'}
       ),
});

上面的代码不正确,但是我的想法可以吗?

如何表示 Dockerfileenvironment variables

正如您在 the DockerImageCode.fromImageAsset() docs 中看到的,您可以在 file 参数中指定 Dockerfile 的相对路径。

至于 lambda 本身的环境变量,the docs for lambda.DockerImageFunction 也对此进行了解释。您使用 environment 属性定义环境变量:

environment?

Type: { [string]: string } (optional, default: No environment variables.)

Key-value pairs that Lambda caches and makes available for your Lambda functions.

所以它看起来像这样:

const messageLambda = new lambda.DockerImageFunction(this, "BotLambda", {
  code: lambda.DockerImageCode.fromImageAsset(
         "chatbot-sam/botapp",
         {
            file: "Dockerfile.message",
         }
       ),
  environment: { DBNAME:'mydb'}
});