To get started with Lambda, use the Lambda console to create a function. In a few minutes, you can create and deploy a function and test it in the console.
As you carry out the tutorial, you'll learn some fundamental Lambda concepts, like how to pass arguments to your function using the Lambdaevent object. You'll also learn how to return log outputs from your function, and how to view your function's invocation logs in Amazon CloudWatch Logs.
To keep things simple, you create your function using either the Python or Node.js runtime. With these interpreted languages, you can edit function code directly in the console's built-in code editor. With compiled languages like Java and C#, you must create a deployment package on your local build machine and upload it to Lambda. To learn about deploying functions to Lambda using other runtimes, see the links in theAdditional resources and next steps section.
To learn how to buildserverless solutions, check out theServerless Developer Guide.
If you do not have an AWS account, complete the following steps to create one.
Follow the online instructions.
Part of the sign-up procedure involves receiving a phone call or text message and entering a verification code on the phone keypad.
When you sign up for an AWS account, anAWS account root user is created. The root user has access to all AWS services and resources in the account. As a security best practice, assign administrative access to a user, and use only the root user to performtasks that require root user access.
AWS sends you a confirmation email after the sign-up process iscomplete. At any time, you can view your current account activity and manage your account bygoing tohttps://aws.amazon.com/ and choosingMy Account.
After you sign up for an AWS account, secure your AWS account root user, enable AWS IAM Identity Center, and create an administrative user so that you don't use the root user for everyday tasks.
Sign in to theAWS Management Console as the account owner by choosingRoot user and entering your AWS account email address. On the next page, enter your password.
For help signing in by using root user, seeSigning in as the root user in theAWS Sign-In User Guide.
Turn on multi-factor authentication (MFA) for your root user.
For instructions, seeEnable a virtual MFA device for your AWS account root user (console) in theIAM User Guide.
Enable IAM Identity Center.
For instructions, seeEnabling AWS IAM Identity Center in theAWS IAM Identity Center User Guide.
In IAM Identity Center, grant administrative access to a user.
For a tutorial about using the IAM Identity Center directory as your identity source, see Configure user access with the default IAM Identity Center directory in theAWS IAM Identity Center User Guide.
To sign in with your IAM Identity Center user, use the sign-in URL that was sent to your email address when you created the IAM Identity Center user.
For help signing in using an IAM Identity Center user, seeSigning in to the AWS access portal in theAWS Sign-In User Guide.
In IAM Identity Center, create a permission set that follows the best practice of applying least-privilege permissions.
For instructions, see Create a permission set in theAWS IAM Identity Center User Guide.
Assign users to a group, and then assign single sign-on access to the group.
For instructions, see Add groups in theAWS IAM Identity Center User Guide.
In this example, your function takes a JSON object containing two integer values labeled"length"
and"width"
. The function multiplies these values to calculate an area and returns this as a JSON string.
Your function also prints the calculated area, along with the name of its CloudWatch log group. Later in the tutorial, you’ll learn to useCloudWatch Logs to view records of your functions’ invocation.
Open theFunctions page of the Lambda console.
ChooseCreate function.
SelectAuthor from scratch.
In theBasic information pane, forFunction name, enter
.myLambdaFunction
ForRuntime, choose eitherNode.js 22 orPython 3.13.
Leavearchitecture set tox86_64, and then chooseCreate function.
In addition to a simple function that returns the messageHello from Lambda!
, Lambda also creates anexecution role for your function. An execution role is an AWS Identity and Access Management (IAM) role that grants a Lambda function permission to access AWS services and resources. For your function, the role that Lambda creates grants basic permissions to write to CloudWatch Logs.
Use the console's built-in code editor to replace the Hello world code that Lambda created with your own function code.
Choose theCode tab.
In the console's built-in code editor, you should see the function code that Lambda created. If you don't see theindex.mjs tab in the code editor, selectindex.mjs in the file explorer as shown on the following diagram.
Paste the following code into theindex.mjs tab, replacing the code that Lambda created.
export const handler = async (event, context) =>{ const length = event.length; const width = event.width; let area = calculateArea(length, width); console.log(`The area is ${area}`); console.log('CloudWatch log group: ', context.logGroupName); let data ={ "area": area, }; return JSON.stringify(data); function calculateArea(length, width){ return length * width; }};
In theDEPLOY section, chooseDeploy to update your function's code:
Before you move to the next step, let's take a moment to look at the function code and understand some key Lambda concepts.
The Lambda handler:
Your Lambda function contains a Node.js function namedhandler
. A Lambda function in Node.js can contain more than one Node.js function, but thehandler function is always the entry point to your code. When your function is invoked, Lambda runs this method.
When you created your Hello world function using the console, Lambda automatically set the name of the handler method for your function tohandler
. Be sure not to edit the name of this Node.js function. If you do, Lambda won’t be able to run your code when you invoke your function.
To learn more about the Lambda handler in Node.js, seeDefine Lambda function handler in Node.js.
The Lambda event object:
The functionhandler
takes two arguments,event
andcontext
. Anevent in Lambda is a JSON formatted document that contains data for your function to process.
If your function is invoked by another AWS service, the event object contains information about the event that caused the invocation. For example, if your function is invoked when an object is uploaded to an Amazon Simple Storage Service (Amazon S3) bucket, the event contains the name of the bucket and the object key.
In this example, you’ll create an event in the console by entering a JSON formatted document with two key-value pairs.
The Lambda context object:
The second argument that your function takes iscontext
. Lambda passes thecontext object to your function automatically. The context object contains information about the function invocation and execution environment.
You can use the context object to output information about your function's invocation for monitoring purposes. In this example, your function uses thelogGroupName
parameter to output the name of its CloudWatch log group.
To learn more about the Lambda context object in Node.js, seeUsing the Lambda context object to retrieve Node.js function information.
Logging in Lambda:
With Node.js, you can use console methods likeconsole.log
andconsole.error
to send information to your function's log. The example code usesconsole.log
statements to output the calculated area and the name of the function's CloudWatch Logs group. You can also use any logging library that writes tostdout
orstderr
.
To learn more, seeLog and monitor Node.js Lambda functions. To learn about logging in other runtimes, see the 'Building with' pages for the runtimes you're interested in.
Choose theCode tab.
In the console's built-in code editor, you should see the function code that Lambda created. If you don't see thelambda_function.py tab in the code editor, selectlambda_function.py in the file explorer as shown on the following diagram.
Paste the following code into thelambda_function.py tab, replacing the code that Lambda created.
import jsonimport logginglogger = logging.getLogger()logger.setLevel(logging.INFO)def lambda_handler(event, context): # Get the length and width parameters from the event object. The # runtime converts the event object to a Python dictionary length = event['length'] width = event['width'] area = calculate_area(length, width) print(f"The area is{area}") logger.info(f"CloudWatch logs group:{context.log_group_name}") # return the calculated area as a JSON string data ={"area": area} return json.dumps(data) def calculate_area(length, width): return length*width
In theDEPLOY section, chooseDeploy to update your function's code:
Before you move to the next step, let's take a moment to look at the function code and understand some key Lambda concepts.
The Lambda handler:
Your Lambda function contains a Python function namedlambda_handler
. A Lambda function in Python can contain more than one Python function, but thehandler function is always the entry point to your code. When your function is invoked, Lambda runs this method.
When you created your Hello world function using the console, Lambda automatically set the name of the handler method for your function tolambda_handler
. Be sure not to edit the name of this Python function. If you do, Lambda won’t be able to run your code when you invoke your function.
To learn more about the Lambda handler in Python, seeDefine Lambda function handler in Python.
The Lambda event object:
The functionlambda_handler
takes two arguments,event
andcontext
. Anevent in Lambda is a JSON formatted document that contains data for your function to process.
If your function is invoked by another AWS service, the event object contains information about the event that caused the invocation. For example, if your function is invoked when an object is uploaded to an Amazon Simple Storage Service (Amazon S3) bucket, the event contains the name of the bucket and the object key.
In this example, you’ll create an event in the console by entering a JSON formatted document with two key-value pairs.
The Lambda context object:
The second argument that your function takes iscontext
. Lambda passes thecontext object to your function automatically. The context object contains information about the function invocation and execution environment.
You can use the context object to output information about your function's invocation for monitoring purposes. In this example, your function uses thelog_group_name
parameter to output the name of its CloudWatch log group.
To learn more about the Lambda context object in Python, seeUsing the Lambda context object to retrieve Python function information.
Logging in Lambda:
With Python, you can use either aprint
statement or a Python logging library to send information to your function's log. To illustrate the difference in what's captured, the example code uses both methods. In a production application, we recommend that you use a logging library.
To learn more, seeLog and monitor Python Lambda functions. To learn about logging in other runtimes, see the 'Building with' pages for the runtimes you're interested in.
To invoke your function using the Lambda console code editor, create a test event to send to your function. The event is a JSON formatted document containing two key-value pairs with the keys"length"
and"width"
.
In theTEST EVENTS section of the console code editor, chooseCreate test event.
ForEvent Name, entermyTestEvent
.
In theEvent JSON section, replace the default JSON with the following:
{ "length": 6, "width": 7}
ChooseSave.
To test your function and view invocation records
In theTEST EVENTS section of the console code editor, choose the run icon next to your test event:
When your function finishes running, the response and function logs are displayed in theOUTPUT tab. You should see results similar to the following:
Status: SucceededTest Event Name: myTestEventResponse"{\"area\":42}"Function LogsSTART RequestId: 5c012b0a-18f7-4805-b2f6-40912935034a Version: $LATEST2024-08-31T23:39:45.313Z5c012b0a-18f7-4805-b2f6-40912935034aINFOThe area is 422024-08-31T23:39:45.331Z5c012b0a-18f7-4805-b2f6-40912935034aINFOCloudWatch log group: /aws/lambda/myLambdaFunctionEND RequestId: 5c012b0a-18f7-4805-b2f6-40912935034aREPORT RequestId: 5c012b0a-18f7-4805-b2f6-40912935034aDuration: 20.67 msBilled Duration: 21 msMemory Size: 128 MBMax Memory Used: 66 MBInit Duration: 163.87 msRequest ID5c012b0a-18f7-4805-b2f6-40912935034a
Status: SucceededTest Event Name: myTestEventResponse"{\"area\": 42}"Function LogsSTART RequestId: 2d0b1579-46fb-4bf7-a6e1-8e08840eae5b Version: $LATESTThe area is 42[INFO]2024-08-31T23:43:26.428Z2d0b1579-46fb-4bf7-a6e1-8e08840eae5bCloudWatch logs group: /aws/lambda/myLambdaFunctionEND RequestId: 2d0b1579-46fb-4bf7-a6e1-8e08840eae5bREPORT RequestId: 2d0b1579-46fb-4bf7-a6e1-8e08840eae5bDuration: 1.42 msBilled Duration: 2 msMemory Size: 128 MBMax Memory Used: 39 MBInit Duration: 123.74 msRequest ID2d0b1579-46fb-4bf7-a6e1-8e08840eae5b
When you invoke your function outside of the Lambda console, you must use CloudWatch Logs to view your function's execution results.
Open theLog groups page of the CloudWatch console.
Choose the log group for your function (/aws/lambda/myLambdaFunction
). This is the log group name that your function printed to the console.
Scroll down and choose theLog stream for the function invocations you want to look at.
You should see output similar to the following:
INIT_START Runtime Version: nodejs:22.v13 Runtime Version ARN: arn:aws:lambda:us-west-2::runtime:e3aaabf6b92ef8755eaae2f4bfdcb7eb8c4536a5e044900570a42bdba7b869d9START RequestId: aba6c0fc-cf99-49d7-a77d-26d805dacd20 Version: $LATEST2024-08-23T22:04:15.809Z 5c012b0a-18f7-4805-b2f6-40912935034a INFOThe area is 422024-08-23T22:04:15.810Z aba6c0fc-cf99-49d7-a77d-26d805dacd20 INFO CloudWatch log group: /aws/lambda/myLambdaFunctionEND RequestId: aba6c0fc-cf99-49d7-a77d-26d805dacd20REPORT RequestId: aba6c0fc-cf99-49d7-a77d-26d805dacd20 Duration: 17.77 ms Billed Duration: 18 ms Memory Size: 128 MB Max Memory Used: 67 MB Init Duration: 178.85 ms
INIT_START Runtime Version: python:3.13.v16 Runtime Version ARN: arn:aws:lambda:us-west-2::runtime:ca202755c87b9ec2b58856efb7374b4f7b655a0ea3deb1d5acc9aee9e297b072START RequestId: 9d4096ee-acb3-4c25-be10-8a210f0a9d8e Version: $LATESTThe area is 42[INFO]2024-09-01T00:05:22.464Z9315ab6b-354a-486e-884a-2fb2972b7d84CloudWatch logs group: /aws/lambda/myLambdaFunctionEND RequestId: 9d4096ee-acb3-4c25-be10-8a210f0a9d8e REPORT RequestId: 9d4096ee-acb3-4c25-be10-8a210f0a9d8e Duration: 1.15 ms Billed Duration: 2 ms Memory Size: 128 MB Max Memory Used: 40 MB
When you're finished working with the example function, delete it. You can also delete the log group that stores the function's logs, and theexecution role that the console created.
Open theFunctions page of the Lambda console.
Select the function that you created.
ChooseActions,Delete.
Typeconfirm
in the text input field and chooseDelete.
Open theLog groups page of the CloudWatch console.
Select the function's log group (/aws/lambda/myLambdaFunction
).
ChooseActions,Delete log group(s).
In theDelete log group(s) dialog box, chooseDelete.
Open theRoles page of the AWS Identity and Access Management (IAM) console.
Select the function's execution role (for example,myLambdaFunction-role-
).31exxmpl
ChooseDelete.
In theDelete role dialog box, enter the role name, and then chooseDelete.
Now that you’ve created and tested a simple Lambda function using the console, take these next steps:
Learn to add dependencies to your function and deploy it using a .zip deployment package. Choose your preferred language from the following links.
Deploy transpiled TypeScript code in Lambda with .zip file archives
Build and deploy C# Lambda functions with .zip file archives
To learn how to invoke a Lambda function using another AWS service, seeTutorial: Using an Amazon S3 trigger to invoke a Lambda function.
Choose one of the following tutorials for more complex examples of using Lambda with other AWS services.
Tutorial: Using Lambda with API Gateway: Create an Amazon API Gateway REST API that invokes a Lambda function.
Using a Lambda function to access an Amazon RDS database: Use a Lambda function to write data to an Amazon Relational Database Service (Amazon RDS) database through RDS Proxy.
Using an Amazon S3 trigger to create thumbnail images: Use a Lambda function to create a thumbnail every time an image file is uploaded to an Amazon S3 bucket.