How to Deploy AWS Lambda Function Quickly and Easily
To deploy a
AWS Lambda function, package your code and dependencies into a ZIP file, then use the aws lambda create-function or aws lambda update-function-code command with the AWS CLI. You must specify the function name, runtime, handler, role, and the ZIP file location.Syntax
Use the AWS CLI commands to deploy your Lambda function. The main commands are:
aws lambda create-function: Creates a new Lambda function.aws lambda update-function-code: Updates the code of an existing Lambda function.
Key parameters include:
--function-name: Name of your Lambda function.--runtime: The runtime environment (e.g., python3.9, nodejs18.x).--role: The ARN of the IAM role that Lambda assumes.--handler: The entry point in your code (e.g.,index.handler).--zip-file: The path to your zipped deployment package.
bash
aws lambda create-function \ --function-name MyLambdaFunction \ --runtime python3.9 \ --role arn:aws:iam::123456789012:role/lambda-execution-role \ --handler index.handler \ --zip-file fileb://function.zip
Example
This example shows how to deploy a simple Python Lambda function using AWS CLI. First, create a file index.py with a handler function, then zip it and deploy.
bash
# index.py
def handler(event, context):
return {'statusCode': 200, 'body': 'Hello from Lambda!'}
# Commands to deploy
zip function.zip index.py
aws lambda create-function \
--function-name HelloLambda \
--runtime python3.9 \
--role arn:aws:iam::123456789012:role/lambda-execution-role \
--handler index.handler \
--zip-file fileb://function.zipOutput
Created function HelloLambda with ARN arn:aws:lambda:region:123456789012:function:HelloLambda
Common Pitfalls
Common mistakes when deploying Lambda functions include:
- Not packaging dependencies with your code if needed.
- Using incorrect handler names that don't match your code.
- Not assigning the correct IAM role with necessary permissions.
- Uploading the ZIP file incorrectly (must use
fileb://prefix). - Trying to create a function that already exists instead of updating it.
bash
Wrong: aws lambda create-function --function-name MyFunc --zip-file file://function.zip Right: aws lambda create-function --function-name MyFunc --zip-file fileb://function.zip
Quick Reference
Remember these quick tips when deploying Lambda functions:
- Use
create-functiononly once; useupdate-function-codeto change code later. - Always zip your code and dependencies before uploading.
- Ensure your IAM role has
lambda.amazonaws.comtrust and necessary permissions. - Match the handler string exactly to your code entry point.
Key Takeaways
Package your Lambda code and dependencies into a ZIP file before deployment.
Use AWS CLI commands
create-function to deploy and update-function-code to update.Specify correct runtime, handler, and IAM role ARN when deploying.
Use
fileb:// prefix to upload ZIP files with AWS CLI.Check IAM role permissions and handler names to avoid deployment errors.