Serverless Backend with AWS Lambda & API Gateway · บทเรียน

ตัวแปรสภาพแวดล้อมและเลเยอร์

จัดการการกำหนดค่าและส่วนที่ต้องพึ่งพาอย่างมีประสิทธิภาพด้วยตัวแปรสภาพแวดล้อมและเลเยอร์ของ Lambda สำหรับโค้ดที่ใช้ร่วมกัน

บทเรียน 2 จาก 411 ขั้นตอน

ตัวแปรสภาพแวดล้อมและเลเยอร์ เป็นบทเรียน Serverless Backend with AWS Lambda & API Gateway ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Serverless Backend with AWS Lambda & API Gateway และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Serverless Backend with AWS Lambda & API Gateway มีบทเรียนทั้งหมด 4 บทเรียน

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

Configuring Lambda Functions

When building serverless applications, you often need to configure your Lambda functions. This includes settings that change between development, testing, and production environments.

Think about database connection strings, API endpoints, or feature flags. Hardcoding these values is a bad practice!

What are Environment Variables?

Environment variables are key-value pairs that you define for your Lambda function. Your function's code can then access these variables at runtime.

  • They provide a simple way to change your function's behavior without modifying its code.
  • Each function has its own set of environment variables.

Setting Environment Variables

You can set environment variables directly in the AWS Management Console when configuring your Lambda function. They can also be defined using Infrastructure as Code tools like AWS SAM or CloudFormation.

Important: While convenient, avoid storing sensitive information like database passwords directly in environment variables. Use AWS Secrets Manager for that!

Accessing Env Vars in Python

In Python, you can access environment variables using the os module, specifically os.environ.get(). This method allows you to provide a default value if the variable isn't set.

Try running this example:

import os

def lambda_handler(event, context):
    # Get GREETING_MESSAGE env var, default to 'Hello'
    greeting = os.environ.get('GREETING_MESSAGE', 'Hello')
    
    # Get 'name' from the event, default to 'World'
    name = event.get('name', 'World') 
    
    message = f"{greeting}, {name}!"
    print(message)
    
    return {
        'statusCode': 200,
        'body': message
    }

# --- Local testing simulation ---
if __name__ == '__main__':
    # Simulate setting an environment variable locally
    os.environ['GREETING_MESSAGE'] = 'Hola'
    
    # Simulate a Lambda event
    test_event = {'name': 'CoddyKit User'}
    
    print("\nRunning lambda_handler locally...")
    result = lambda_handler(test_event, None)
    print(f"Local Lambda response: {result}")
    
    # Clean up simulated env var
    del os.environ['GREETING_MESSAGE']

Env Var Best Practices

Using environment variables wisely can greatly improve your function's maintainability:

  • Non-sensitive config: Use for API keys (for non-critical services), log levels, feature flags.
  • Integration with Secrets Manager: For truly sensitive data (e.g., database credentials), store them in AWS Secrets Manager and retrieve them at runtime using your function's IAM role.
  • Separate environments: Easily switch configs for dev, staging, and production.

Introducing Lambda Layers

As your serverless applications grow, you might find multiple Lambda functions needing the same libraries, dependencies, or utility code.

Lambda Layers solve this by allowing you to package and share common components across multiple functions.

Benefits of Lambda Layers

Layers offer several advantages for managing your Lambda functions:

  • Smaller deployment packages: Your function code only contains your business logic, not large libraries.
  • Code reusability: Share common functions, helper modules, or SDKs across many Lambdas.
  • Faster deployments: Only upload your small function code, not entire dependency sets.
  • Consistent dependencies: Ensure all functions use the same version of a library.

How Lambda Layers Work

When you attach a layer to a Lambda function, AWS extracts its contents into the /opt directory in the function's execution environment.

Your function code can then import modules or use binaries from this /opt directory as if they were part of its own deployment package.

Using a Shared Layer (Python)

Once a layer is attached, your Python function can simply import modules from it. For example, if your layer contains my_utilities.py at python/my_utilities.py, you can import it like any other module:

from my_utilities import format_message import json def lambda_handler(event, context): user_name = event.get('name', 'Guest') # Assuming format_message is in our layer response_message = format_message(user_name) return { 'statusCode': 200, 'body': json.dumps({'message': response_message}) }

This code isn't runnable on its own as the layer isn't defined here, but it shows how you'd import from it.

from my_utilities import format_message
import json

def lambda_handler(event, context):
    user_name = event.get('name', 'Guest')
    # Assuming format_message is in our layer
    response_message = format_message(user_name)
    
    return {
        'statusCode': 200,
        'body': json.dumps({'message': response_message})
    }

Quick Check: Env Vars & Layers

Let's test your understanding of Lambda environment variables and layers.

Recap: Env Vars & Layers

In this lesson, we learned how to manage Lambda function configurations and dependencies effectively:

  • Environment Variables: Key-value pairs for non-sensitive configuration, accessed via os.environ in Python.
  • Lambda Layers: Mechanisms for packaging and sharing common code, libraries, and dependencies across multiple functions.
  • Layers lead to smaller deployment packages, improved reusability, and faster deployments.

Next up: Dive into logging and monitoring your Lambda functions with CloudWatch!

เริ่มต้นได้ฟรี

เรียนรู้ Serverless Backend with AWS Lambda & API Gateway ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
12
บทเรียน
48

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

บทเรียน “ตัวแปรสภาพแวดล้อมและเลเยอร์” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ตัวแปรสภาพแวดล้อมและเลเยอร์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Serverless Backend with AWS Lambda & API Gateway ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Serverless Backend with AWS Lambda & API Gateway มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ตัวแปรสภาพแวดล้อมและเลเยอร์”

จัดการการกำหนดค่าและส่วนที่ต้องพึ่งพาอย่างมีประสิทธิภาพด้วยตัวแปรสภาพแวดล้อมและเลเยอร์ของ Lambda สำหรับโค้ดที่ใช้ร่วมกัน คุณปฏิบัติ Serverless Backend with AWS Lambda & API Gateway ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Serverless Backend with AWS Lambda & API Gateway หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Serverless Backend with AWS Lambda & API Gateway บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “ตัวแปรสภาพแวดล้อมและเลเยอร์” ใช้เวลานานแค่ไหน

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

ฉันเขียนและรันโค้ดในบทเรียน Serverless Backend with AWS Lambda & API Gateway นี้ได้ไหม

ได้ บทเรียน Serverless Backend with AWS Lambda & API Gateway ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

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

  1. รันไทม์และตัวจัดการของ Lambda
  2. ตัวแปรสภาพแวดล้อมและเลเยอร์
  3. การบันทึกและการเฝ้าติดตามด้วย CloudWatch
  4. การจัดการข้อผิดพลาด การลองใหม่ และคิวจดหมายตาย
← กลับไปที่ Serverless Backend with AWS Lambda & API Gateway