Movatterモバイル変換


[0]ホーム

URL:


Create your first Lambda function - AWS Lambda
DocumentationAWS LambdaDeveloper Guide
PrerequisitesCreate the functionInvoke the functionClean upNext steps

Create your first Lambda function

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.

Prerequisites

If you do not have an AWS account, complete the following steps to create one.

To sign up for an AWS account
  1. Openhttps://portal.aws.amazon.com/billing/signup.

  2. 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.

Secure your AWS account root user
  1. 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.

  2. 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.

Create a user with administrative access
  1. Enable IAM Identity Center.

    For instructions, seeEnabling AWS IAM Identity Center in theAWS IAM Identity Center User Guide.

  2. 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.

Sign in as the user with administrative access
  • 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.

Assign access to additional users
  1. 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.

  2. 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.

Create a Lambda function with the console

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.

To create a Hello world Lambda function with the console
  1. Open theFunctions page of the Lambda console.

  2. ChooseCreate function.

  3. SelectAuthor from scratch.

  4. In theBasic information pane, forFunction name, entermyLambdaFunction.

  5. ForRuntime, choose eitherNode.js 22 orPython 3.13.

  6. 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.

Node.js
Understanding your function 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.

Python
To modify the code in the console
  1. 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.

    Diagram showing the console code editor and the lambda_function.py file in the file explorer
  2. 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
  3. In theDEPLOY section, chooseDeploy to update your function's code:

    Deploy button in the Lambda console code editor
Understanding your function 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.

Invoke the Lambda function using the console code editor

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".

To create the test event
  1. In theTEST EVENTS section of the console code editor, chooseCreate test event.

    Create test event button in the Lambda console code editor
  2. ForEvent Name, entermyTestEvent.

  3. In theEvent JSON section, replace the default JSON with the following:

    { "length": 6, "width": 7}
  4. 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:

Run test event button in the Lambda console code editor

When your function finishes running, the response and function logs are displayed in theOUTPUT tab. You should see results similar to the following:

Node.js
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
Python
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.

To view your function's invocation records in CloudWatch Logs
  1. Open theLog groups page of the CloudWatch console.

  2. Choose the log group for your function (/aws/lambda/myLambdaFunction). This is the log group name that your function printed to the console.

  3. Scroll down and choose theLog stream for the function invocations you want to look at.

    List of log streams for a Lambda function.

    You should see output similar to the following:

    Node.js
    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
    Python
    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

Clean up

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.

To delete the Lambda function
  1. Open theFunctions page of the Lambda console.

  2. Select the function that you created.

  3. ChooseActions,Delete.

  4. Typeconfirm in the text input field and chooseDelete.

To delete the log group
  1. Open theLog groups page of the CloudWatch console.

  2. Select the function's log group (/aws/lambda/myLambdaFunction).

  3. ChooseActions,Delete log group(s).

  4. In theDelete log group(s) dialog box, chooseDelete.

To delete the execution role
  1. Open theRoles page of the AWS Identity and Access Management (IAM) console.

  2. Select the function's execution role (for example,myLambdaFunction-role-31exxmpl).

  3. ChooseDelete.

  4. In theDelete role dialog box, enter the role name, and then chooseDelete.

Additional resources and next steps

Now that you’ve created and tested a simple Lambda function using the console, take these next steps:

Designing an application
Example apps and patterns

[8]
ページ先頭

©2009-2025 Movatter.jp