0Pricing
AWS for Backend Developers (EC2, S3, RDS, Lambda) · บทเรียน

สร้างฟังก์ชัน Lambda แรกของคุณ

เขียนและปรับใช้ฟังก์ชัน Lambda อย่างง่าย พร้อมกำหนดรันไทม์ หน่วยความจำ และบทบาทการทำงาน

สร้างฟังก์ชัน Lambda แรกของคุณ เป็นบทเรียน AWS for Backend Developers (EC2, S3, RDS, Lambda) ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AWS for Backend Developers (EC2, S3, RDS, Lambda) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AWS for Backend Developers (EC2, S3, RDS, Lambda) มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Your First Lambda Function

Time to build your first serverless function! In this lesson, we'll write a simple AWS Lambda function that runs your code without managing servers.

We'll cover its basic structure, how to choose a runtime, and essential configurations like memory and execution roles. Get ready to deploy!

The Core: Your Lambda Handler

Every Lambda function needs a 'handler' function. This is the entry point where AWS Lambda starts executing your code. It typically receives two arguments:

  • event: Contains the data that triggered the invocation.
  • context: Provides runtime information about the invocation, function, and execution environment.

Think of the handler as the 'main' method for your serverless code.

Pick Your Language: Lambda Runtimes

AWS Lambda supports many programming languages, called 'runtimes.' You choose the one your function code is written in. The runtime determines the execution environment and how your handler is called.

  • Python: Great for scripting, data processing, and machine learning.
  • Node.js: Ideal for real-time applications, APIs, and microservices.
  • Java: Good for enterprise applications, high performance, and existing JVM ecosystems.
  • Go, C#, Ruby, Custom Runtimes: More options for diverse needs and specific use cases.

Hello Lambda: A Basic Python Example

Let's write a very simple Python Lambda function. This function will take an input name from the event and return a greeting. Try running it to see the output!

import json

def lambda_handler(event, context):
    # event is a dictionary containing invocation data
    # context provides runtime info (e.g., function name, memory limit)

    # We expect 'name' in the event payload
    name = event.get('name', 'World')
    message = f"Hello, {name}!"

    # Lambda functions often return a dictionary, which AWS converts to JSON
    return {
        'statusCode': 200,
        'body': json.dumps(message)
    }

# --- Local Test Simulation ---
if __name__ == "__main__":
    # Simulate an event payload
    test_event = {"name": "CoddyKit User"}
    
    # Simulate a dummy context object
    class Context:
        def __init__(self):
            self.function_name = "my-test-function"
            self.memory_limit_in_mb = 128
            self.invoked_function_arn = "arn:aws:lambda:us-east-1:123456789012:function:my-test-function"
            self.aws_request_id = "test-request-id-123"

    test_context = Context()

    # Call the handler
    response = lambda_handler(test_event, test_context)
    
    # Print the response for local verification
    print(f"Status Code: {response['statusCode']}")
    print(f"Body: {json.loads(response['body'])}")

    # Test without a name
    test_event_no_name = {}
    response_no_name = lambda_handler(test_event_no_name, test_context)
    print(f"\nStatus Code (no name): {response_no_name['statusCode']}")
    print(f"Body (no name): {json.loads(response_no_name['body'])}")

Your Function's Input: The Event

The event object is a Python dictionary (or JSON object in other runtimes) that contains the data passed to your function. This data comes from the service that triggered your Lambda.

  • If triggered by an API Gateway: It contains HTTP method, headers, body.
  • If triggered by S3: It contains details about the S3 bucket and object.
  • If invoked directly: It contains whatever JSON payload you passed.

Your function processes this input to perform its task.

Runtime Details: The Context

The context object provides information about the invocation, function, and execution environment. It's useful for logging and making runtime decisions.

  • function_name: The name of your Lambda function.
  • aws_request_id: A unique ID for the invocation.
  • memory_limit_in_mb: The memory allocated to the function.
  • get_remaining_time_in_millis(): How much time is left before the function times out.

You can use this for advanced error handling or logging within your function.

Permissions with IAM Execution Roles

A Lambda function needs permission to interact with other AWS services. This is managed by an IAM Role, specifically called the "execution role."

  • The role defines what actions your Lambda can perform (e.g., write logs to CloudWatch, read from S3).
  • You attach policies to this role, specifying permissions.
  • Without the correct permissions, your function will fail when trying to access other AWS resources.

Always follow the principle of least privilege, granting only the necessary permissions.

Fine-Tuning: Memory & Timeout

When you create a Lambda function, you configure several settings that impact its performance and cost:

  • Memory: Defines the RAM allocated (e.g., 128MB to 10GB). More memory often means more CPU power too.
  • Timeout: The maximum time your function can run (e.g., 3 seconds to 15 minutes). If it exceeds this, Lambda stops it.
  • Environment Variables: Key-value pairs accessible to your code, great for configuration without changing code.

Choosing appropriate settings is crucial for efficiency and cost optimization.

Getting Your Function Live

Once your code is ready, you deploy it to AWS Lambda. Here's a high-level overview:

  1. Package your code: Zip your code and any dependencies into a deployment package.
  2. Upload: Use the AWS Console, AWS CLI, or an Infrastructure as Code (IaC) tool like AWS SAM or CloudFormation.
  3. Test: Invoke your function directly from the Lambda console with test events, or trigger it via an integrated service like API Gateway or S3.

The console provides a quick way to get started and test your function immediately.

Quick Check: Lambda Handler

Consider the basic structure of a Python Lambda handler:

def lambda_handler(event, context):
    # ... your code ...
    return response

What is the primary purpose of the event parameter?

Recap: Your First Serverless Step

Great job! You've learned the fundamentals of building a Lambda function:

  • Every Lambda needs a handler function as its entry point.
  • You choose a runtime (like Python) for your code.
  • The event object carries input data, and context provides runtime info.
  • An IAM execution role grants your function necessary permissions.
  • You configure settings like memory and timeout for performance and cost.

This is your foundation for building powerful serverless applications!

คำถามที่พบบ่อย

บทเรียน “สร้างฟังก์ชัน Lambda แรกของคุณ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “สร้างฟังก์ชัน Lambda แรกของคุณ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AWS for Backend Developers (EC2, S3, RDS, Lambda) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AWS for Backend Developers (EC2, S3, RDS, Lambda) มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “สร้างฟังก์ชัน Lambda แรกของคุณ”

เขียนและปรับใช้ฟังก์ชัน Lambda อย่างง่าย พร้อมกำหนดรันไทม์ หน่วยความจำ และบทบาทการทำงาน คุณปฏิบัติ AWS for Backend Developers (EC2, S3, RDS, Lambda) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AWS for Backend Developers (EC2, S3, RDS, Lambda) หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน AWS for Backend Developers (EC2, S3, RDS, Lambda) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “สร้างฟังก์ชัน Lambda แรกของคุณ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน AWS for Backend Developers (EC2, S3, RDS, Lambda) นี้ได้ไหม

ได้ บทเรียน AWS for Backend Developers (EC2, S3, RDS, Lambda) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. AWS Lambda คืออะไร
  2. สร้างฟังก์ชัน Lambda แรกของคุณ
  3. ทริกเกอร์และการผสานรวมของ Lambda
  4. การตรวจสอบและแก้ไขข้อบกพร่องของฟังก์ชัน Lambda
← กลับไปที่ AWS for Backend Developers (EC2, S3, RDS, Lambda)