简体   繁体   中英

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

I have SAM project in template.yml

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 .

It works well for now.

However now I want to move this to cdk

So, in cdk I first wrote this code

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

However I want to set the dockerfile and environment 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 ?

As you can see in the DockerImageCode.fromImageAsset() docs , you can specify a relative path to the Dockerfile in the file parameter.

As for environment variables for the lambda itself, the docs for lambda.DockerImageFunction explain this as well. You define the environment variable with the environment attribute:

environment?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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