Creating a Lambda function in CDK: A guide to configuring the Dockerfile and setting environment variables

I am currently working on a SAM project using template.yml. Here is a snippet of the configuration:

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

To deploy this configuration, use the following command:

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

This will set the environment variable DBNAME=mydb and build the image from Dockerfile.message.

The process works well at the moment.

However, I now want to migrate this setup to CDK.

In my initial attempt with CDK, I wrote this code:

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

But I need to specify the dockerfile and environment variables.

For example:

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

Although the above code is not correct, is my idea clear?

How can I configure the Dockerfile and environment variables in CDK?

Answer №1

Check out the documentation for DockerImageCode.fromImageAsset() to see how you can specify a relative path to the Dockerfile in the file parameter.

When it comes to defining environment variables for the lambda function itself, refer to the documentation for lambda.DockerImageFunction. It explains that you use the environment attribute to define key-value pairs for Lambda functions:

environment?

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

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

Here's an example of how it would look like in your code:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In TypeScript, the error "Property does not exist on type 'any[]'" indicates that a specific property is not recognized on

Working on my project using Textscript in Next Js has been mostly smooth sailing, but I keep encountering warnings in my script that say 'Property does not exist on type any[ ]'. The red line under the name, image, and price properties is a sourc ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...

Tips for avoiding the return of JSON in AWS Lambda and AWS SAM when utilizing express.static

I have been working on building a serverless website using AWS Lambda and the SMA CLI tool from AWS. My main goal is to test making real requests to the API. Currently, I am facing an issue with serving assets using the express.static function. Whenever I ...

Substitute terms in a sentence according to the guidelines

Looking to transform strings based on specific rules? "Hello {{firstName}}, this is {{senderName}}." Consider the following rules: rules = { firstName: "Alex", senderName: "Tracy" } The expected output would be: "Hello Alex, this is Tracy." If yo ...

Retrieve the input type corresponding to the name and return it as a string using string template literals

type ExtractKeyType<T extends string, K extends number> = `${T}.${K}`; type PathImpl<T, Key extends keyof T> = Key extends string ? T[Key] extends readonly unknown[] ? ExtractKeyType<Key, 0 | 1> : T[Key] extends Record<str ...

Utilizing PropTypes in React with TypeScript

I've encountered issues while trying to integrate PropTypes with Typescript: Previously, without typescript, I had successfully used: class TodoFilterItem extends Component { constructor (props) { super(props); Followed by: TodoFilterItem.prop ...

"Encountering a 'ng not found' issue while constructing an Angular application with a

Yesterday, I encountered a strange issue while working on an Angular project and deploying it using Docker. Everything was running smoothly until suddenly I hit a roadblock - I couldn't build the Docker image anymore. Here's my Dockerfile: # Stag ...

unable to reinstall due to removal of global typing

After globally installing Moment typing with the command typings install dt~moment --save --global Checking the installed typings using typings list shows: ├── <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93fffcf7f2e0 ...

Events bound to JSX elements created in an array map are not being triggered by React

My current task involves working on a compact react + typescript (1.6) application designed for editing slideshows. The functionality of the app is straightforward. A sidebar on the left displays all existing slides, and upon clicking, a canvas appears on ...

Is there a way to determine if a string is empty, even if it contains hard returns?

I am currently working on a function that checks if a string is empty or not, but it seems to be missing the detection of new lines. export const isStrEmpty = function(text: string): boolean { return !text || text.match(/^ *$/) !== null; }; I attempted ...

Encountering an error in Chrome where the property 'command' is undefined

Currently utilizing typescript and encountered an error in the chrome console: Error found in event handler for (unknown): TypeError: Unable to access property 'command' as it is undefined at chrome-extension://somethingsomethingsometh ...

Adding a component to a page in Angular 4: A step-by-step guide

Currently engaged in a project that involves creating a mobile application design within a web application. I'm wondering how to display my Component object on a page using ViewChild? I have a list of PageComponents, below is the PageComponent class ...

Having trouble adjusting the appearance of the dropdown menu in Angular Material's Select component

I've been attempting to adjust the style of the overlay panel within an Angular Material's MdSelect component in order to change the default max-width property of 280px. I have tried various methods, such as using '!important' to overr ...

The Freemode feature in SwiperJS is not functioning properly when used with React TypeScript

Having a slight issue with SwiperJS. Using version 10.1.0 and the following code : import { Swiper, SwiperSlide } from "swiper/react"; import "swiper/css"; export default function Discover() { return ( <> ...

What steps can be taken to address the InvalidPipeArgument error when working with dates?

When attempting to format a date in a specific way using the pipe date, I encountered an error: Uncaught Error: InvalidPipeArgument: 'Unable to convert "25/01/2019" into a date' for pipe 'e' at Xe (main.fc4242d58c261cf678ad.js:1) ...

Using Nightwatch within Docker is only compatible with PhantomJS

I've been conducting a series of tests using nightwatch.js within a Docker container. Oddly enough, the tests run flawlessly when I use Phantomjs. However, when I switch to Chrome or Firefox, an unexpected "connection reset" error occurs. The founda ...

The property functions normally outside the promise, but is undefined when within the promise context

I am currently working on filtering an array based on another array of different objects but with the same key field. Although I have made some progress, I keep encountering errors that I am unable to resolve. @Component({ selector: 'equipment&ap ...

Framer Motion's "repeatType" property triggering a TypeError

Every time I try to add the repeatType property in my transition, I encounter an error related to the variants prop: index.d.ts(2779, 5): The expected type comes from property 'variants' which is declared here on type 'IntrinsicAttributes ...

Having difficulty building a react.js application using Visual Studio 2019

Currently, I am following a helpful tutorial on creating a react.js application using visual studio. At this stage, the tutorial instructs me to open the command prompt and enter the following command: webpack app.tsx --config webpack-config.js (I have ...

Please refrain from using the scale command in Docker as it has been deprecated. Instead, utilize the up command with the --scale

I'm looking to start up 5 Chrome and 5 Firefox browsers in a Docker container. When I use the command below, I encounter the following error message: The scale command is deprecated. Use the up command with the --scale flag instead. ERROR: No such ser ...