AWS Lambda의 모든 것: 초보자를 위한 완벽한 가이드 2/2 - Console에서 람다 함수 생성, 트리거 설정 및 요금 계산
Written by Hyojung Yoon
Hello! Today, we will continue to delve deeper into AWS Lambda. Especially in this part, we will practice creating Lambda functions and setting Lambda triggers using the AWS Console.
We will also understand the pricing policy of AWS Lambda and learn how to calculate actual costs.
Let’s begin!
Start AWS Lambda
Writing Lambda Function Code
Setting Lambda Trigger
AWS Lambda Pricing
Start AWS Lambda
1. Creating Lambda Functions in the Console
You can create your first function using the AWS Console. Select Lambda within the AWS Console.
Press the [ Create function ] button to create a Lambda function.
You will be presented with three options at the top.
Create from scratch: Start building a function from the ground up
Use a blueprint: Utilize AWS-provided templates that can be customized with sample code.
Container image: Specifically for Docker containers.
After making your selection, add a new function name and choose the desired runtime¹.
¹Runtime: Options for the programming language you want to write your Lambda in, such as Node.js, Python, Go, etc.
Permissions specify the rights that will be granted to the Lambda function.
Click [ Change default execution role ] to create a new role with the standard Lambda permissions.
2. Writing Lambda Function Code
Review the function you created, here named hjLambda.
Scroll down to the function code section. Here, you can select a template or design your own.
Configuring Lambda Functions
myHandler = The name of the Lambda function
Lambda executes this handler method when the function is invoked, passing three arguments: event, context, and callback."
event: Contains information from the caller, with all details about the event that triggered Lambda.
context: Contains information about indirect calls to the Lambda function, the execution environment, and runtime.
callback: Needed to send asynchronous responses, calling the callback function with results (or errors) after all operations inside the Lambda function are done, which AWS then processes as a response to the HTTP request.
3. Executing Lambda Functions
Before running the Lambda function, we will first perform a test.
Select [ Configure test events ] from the test dropdown menu, which opens a code editor for test event configuration.
Select create new event, and enter an event name like MyEvent.
Keep the event visibility settings private as default.
From the template list, select hello-world and then click [ Save ].
Click the [ Test ] button and check the console for successful execution.
In the execution result tab, confirm if the execution was successful.
The function log section displays logs created by the Lambda function execution and key information reported in the log output.
If the test went well, click the [ Deploy ] button to make it executable.
4. Setting Lambda Trigger
1) Lambda Trigger + S3
We will implement logic using an AWS Lambda function to copy files from one Amazon S3 bucket to another.
Step 1: Create the source and destination Amazon S3 buckets.
Open the Amazon S3 console and select create bucket. Create both the source and destination buckets.
Here, the name of the source bucket is set to [ hjtestbucket ] and the destination bucket to
[ hjtestbucket02 ].
Step 2: Create a Lambda Function
Open the functions page in the Lambda console and create a function.
Select the runtime dropdown and choose Python 3.9, then create a Lambda function like the one shown in the picture.
Select the code tab and paste the following JSON code.
import boto3
import botocore
import json
import os
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
s3 = boto3.resource('s3')
def lambda_handler(event, context):
logger.info("New files uploaded to the source bucket.")
key = event['Records'][0]['s3']['object']['key']
source_bucket = event['Records'][0]['s3']['bucket']['name']
destination_bucket = "destination_bucket"
source = {'Bucket': source_bucket, 'Key': key}
try:
response = s3.meta.client.copy(source, destination_bucket, key)
logger.info("File copied to the destination bucket successfully!")
except botocore.exceptions.ClientError as error:
logger.error("There was an error copying the file to the destination bucket")
print('Error Message: {}'.format(error))
except botocore.exceptions.ParamValidationError as error:
logger.error("Missing required parameters while calling the API.")
print('Error Message: {}'.format(error))
After pasting the code, select [ Deploy ].
Step 3: Create an Amazon S3 Trigger for the Lambda Function
Open the function page in the Lambda console and select [ Add trigger ] from the function overview.
Select S3 from the trigger configuration dropdown.
Enter the name of the source bucket and select All object create events for the event type.
Acknowledge that using the same S3 bucket for both input and output is not recommended, then select Add.
Step 4: Provide AWS IAM Permissions for the Lambda Function's Execution Role
Like the following resource-based policy, add IAM permissions to the Lambda function's execution role to copy files to the destination S3 bucket.
Open the functions page in the Lambda console and click the role name under configuration - execution role.
In the IAM console, select [ Add permissions ] and then [ Create inline policy ].
Choose the [ JSON ] option and paste the JSON policy document below.
※ Note
Replace destination-s3-bucket with your S3 destination bucket and source-s3-bucket with your S3 source bucket.
Change the /* at the end of the resource ARN to the prefix value needed for your environment to restrict permissions.
It is best to grant only the minimum permissions necessary to perform the action. For more details, refer to Granting least privilege.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "putObject",
"Effect": "Allow",
"Action": [
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::destination-s3-bucket/*"
]
},
{
"Sid": "getObject",
"Effect": "Allow",
"Action": [
"s3:GetObject"
],
"Resource": [
"arn:aws:s3:::source-s3-bucket/*"
]
}
]
}
Select [ Create policy ] to save the new policy.
Step 5: Check if the Lambda Function is Executing Properly
Now, to check if the Lambda trigger is working correctly, upload a file to the original S3 bucket.
Click [ Upload ] and check the upload status.
Go into the destination S3 bucket and verify that the file has been copied.
If the same file is stored, you can tell the function is working properly.
AWS Lambda Pricing
1. Lambda Pricing Policy
Lambda costs are determined by three main factors: the number of requests, execution time, and memory size.
Lambda offers 1 million free requests and 400,000 GB-seconds of free computing time per month, which allows small projects or those in the testing phase to use Lambda without additional costs.
Free Tier Usage Limits | |
Request Count | 1 million requests free per month |
Computing Time | 400,000GB-seconds free per month |
Storage | First 512MB(0.5G) free of charge |
2. Calculating Lambda Prices
You can easily calculate Lambda prices using the AWS pricing calculator website.
Let's calculate the AWS Lambda fees for 3,000,000 executions per month, each running for 1 second, with 512MB of memory (0.5 GB).
Scroll down to [ Show Details ] to see how the pricing is determined.
※ Interpreting Lambda Pricing Calculation
Here is the interpretation of the above calculation.
Total Usage(GB-sec) = 3,000,000 x 1 x 0.5 = 1,500,000 GB-sec
Subtracting the free tier allowance of 400,000 GB-seconds,
Payable Usage(GB-sec) = 3,000,000 x 1 x 0.5 = 1,500,000 GB-sec
The cost of GB-seconds for AWS Lambda is $0.0000166667 per GB-second.
Execution Time Cost = 1,100,000 x 0,0000166667 = $18.33
After excluding the free tier of 1,000,000 requests,
Payable Usage(Request Count) = 3,000,000 - 1,000,000 = 2,000,000
The cost per request is $0.20 per million, with 2,000,000 executions per month.
Request Cost = 2,000,000/1,000,000 x 0.20 = $0.40
Temporary storage allows each Lambda function to use 512MB (=0.5GB) of storage at no additional cost.
Additional Storage Cost = 0.5GB - 0.5GB = 0.00
Therefore, the total cost considering the free tier is about $18.73.
Total = $0.40(Request Cost) + $18.33(Execution Time Cost) = $18.73
This calculation only considers the base costs, so additional costs may occur. Prices are subject to change, so it's best to check the latest information on the AWS official website.
Conclusion
Through this guide, you have learned how to create Lambda functions in the AWS console. Additionally, this series has introduced you to Lambda’s pricing policy and calculation methods, providing you with the basic steps needed to apply this knowledge to real business scenarios.
I hope this experience will be beneficial as you design a variety of cloud services utilizing AWS Lambda.
Comments