เลเยอร์และตัวแปรสภาพแวดล้อมของ Lambda
ทำให้การปรับใช้และจัดการโค้ดเป็นกระบวนการที่ง่ายขึ้นด้วย Lambda Layers สำหรับส่วนพึ่งพา และตัวแปรสภาพแวดล้อมสำหรับการกำหนดค่า
เลเยอร์และตัวแปรสภาพแวดล้อมของ 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 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What are Lambda Layers?
AWS Lambda Layers help you manage common dependencies and custom runtimes more efficiently. Think of them as shared libraries for your functions.
Instead of bundling all your code and dependencies with every function deployment, you can package reusable components into a Layer.
Why Use Lambda Layers?
Layers offer several benefits for your serverless applications:
- Smaller Deployment Packages: Keep your function code lean by separating dependencies.
- Code Reusability: Share common code (e.g., utility functions, database connectors) across multiple Lambda functions.
- Faster Deployments: Smaller packages upload quicker.
- Easier Updates: Update a dependency once in a layer, and all functions using it benefit.
How Layers are Structured
A Lambda Layer is essentially a .zip file archive containing library code, custom runtimes, or other dependencies.
When you attach a layer to a function, Lambda extracts its content to the /opt directory in the function's execution environment. Your function code can then import modules from /opt.
Imagining a Simple Layer
Let's say you have a common logging utility or a specific SDK version you want to use. Instead of including it in every Lambda function's deployment package, you'd put it in a layer.
The layer's ZIP file structure might look like this for Python:
python/mylogger.pyYour Lambda function would then simply import it as import mylogger.
Attaching a Layer to Lambda
You can attach up to 5 layers to a single Lambda function. This is typically done through the AWS Management Console, AWS CLI, or Infrastructure as Code tools like SAM or CloudFormation.
When attaching, you specify the Layer ARN (Amazon Resource Name) which uniquely identifies the layer and its specific version.
Layer Demo: Shared Utility
Imagine we have a layer containing a utils.py with a greet function. Here's how a Lambda function would use it. (We simulate the layer's presence for this runnable demo):
import json
# In a real Lambda, 'utils' would be imported
# from a layer mounted at /opt/python/utils.py
# For this demo, we simulate the 'utils' module.
class Utils:
@staticmethod
def greet(name):
return f"Hello, {name} from Layer!"
utils = Utils() # Make it available as 'utils'
def lambda_handler(event, context):
name = event.get('name', 'World')
message = utils.greet(name)
return {
'statusCode': 200,
'body': json.dumps(message)
}
if __name__ == "__main__":
# Simulate a test event
test_event = {'name': 'Coddy'}
result = lambda_handler(test_event, None)
print(result['body'])
test_event_default = {}
result_default = lambda_handler(test_event_default, None)
print(result_default['body'])What are Env Variables?
Environment variables allow you to pass configuration settings to your Lambda function without changing its underlying code.
They are key-value pairs that are available to your function's code at runtime. This is ideal for settings that vary between environments (e.g., development, test, production) or for non-sensitive configuration data.
Setting Env Variables in Lambda
You can define environment variables when you create or update your Lambda function. This is typically done via:
- AWS Management Console: Under the function's "Configuration" tab, then "Environment variables".
- AWS CLI: Using the
--environment "Variables={KEY=VALUE}"parameter. - Infrastructure as Code: For example, in a SAM template, under the function's
Environment: Variables:section.
Important: For highly sensitive data like database passwords or API keys, always use AWS Secrets Manager instead of environment variables.
Env Variables Demo: Config
Let's say you have an environment variable named GREETING_PREFIX set to "Welcome". Your Lambda function can easily access its value using the os module in Python:
import os
import json
def lambda_handler(event, context):
# Access environment variables
# os.environ.get('KEY', 'default_value')
prefix = os.environ.get('GREETING_PREFIX', 'Hello')
name = event.get('name', 'User')
message = f"{prefix}, {name}!"
return {
'statusCode': 200,
'body': json.dumps(message)
}
if __name__ == "__main__":
# Simulate setting an environment variable locally
os.environ['GREETING_PREFIX'] = 'Hola'
test_event = {'name': 'Amigo'}
result = lambda_handler(test_event, None)
print(result['body'])
# Clean up and test default behavior
del os.environ['GREETING_PREFIX']
test_event_default = {'name': 'World'}
result_default = lambda_handler(test_event_default, None)
print(result_default['body'])Check Your Knowledge
Which of the following are valid reasons to use AWS Lambda Layers?
Recap: Layers & Env Vars
Today, you learned about two powerful tools for managing your Lambda functions more effectively:
- Lambda Layers: Used for packaging shared code, libraries, and dependencies, which reduces deployment package size and promotes code reusability across functions.
- Environment Variables: Used for passing configuration settings to your function at runtime, making your code more flexible and easier to manage across different deployment environments.
Mastering these features will help you build more organized, efficient, and maintainable 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 Layers สำหรับส่วนพึ่งพา และตัวแปรสภาพแวดล้อมสำหรับการกำหนดค่า คุณปฏิบัติ 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 ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การเรียกใช้ Lambda แบบไม่พร้อมกัน
- เลเยอร์และตัวแปรสภาพแวดล้อมของ Lambda
- API Gateway สำหรับปลายทาง Lambda
- Step Functions สำหรับการประสานงาน Lambda