简体   繁体   English

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

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

I have SAM project in template.yml我在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

then deploy like this然后像这样部署

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

It means I will set environment variables DBNAME=mydb and build image from Dockerfile.message .这意味着我将设置环境变量DBNAME=mydb并从Dockerfile.message构建图像。

It works well for now.目前效果很好。

However now I want to move this to cdk但是现在我想把它移到cdk

So, in cdk I first wrote this code所以,在cdk中我首先写了这段代码

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

However I want to set the dockerfile and environment variables .但是我想设置dockerfileenvironment variables

For example例如

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

Above code is not correct, however my idea is ok?上面的代码不正确,但是我的想法可以吗?

How can I indicate Dockerfile and environment variables ?我如何指示Dockerfileenvironment variables

As you can see in the DockerImageCode.fromImageAsset() docs , you can specify a relative path to the Dockerfile in the file parameter.正如您在DockerImageCode.fromImageAsset()文档中所见,您可以在file参数中指定 Dockerfile 的相对路径。

As for environment variables for the lambda itself, the docs for lambda.DockerImageFunction explain this as well.至于 lambda 本身的环境变量,lambda.DockerImageFunction lambda.DockerImageFunction文档也对此进行了解释。 You define the environment variable with the environment attribute:您使用environment属性定义环境变量:

environment?环境?

Type: { [string]: string } (optional, default: No environment variables.)类型:{ [string]: string }(可选,默认:无环境变量。)

Key-value pairs that Lambda caches and makes available for your Lambda functions. Lambda 缓存并可用于您的 Lambda 函数的键值对。

So it would look like this:所以它看起来像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM