Bird
Raised Fist0
AWScloud~5 mins

Creating a Lambda function in AWS - Step-by-Step CLI Walkthrough

Choose your learning style10 modes available
Introduction
Sometimes you want your code to run automatically when something happens, like a file upload or a timer. AWS Lambda lets you run your code without managing servers, so you only focus on your code and AWS handles the rest.
When you want to run a small piece of code in response to an event like a file upload or a message.
When you want to avoid managing servers and only pay for the time your code runs.
When you want to quickly deploy backend code for a web or mobile app without infrastructure setup.
When you want to automate tasks like image resizing or data processing triggered by other AWS services.
When you want to build a simple API backend without managing servers.
Config File - lambda_function.zip
lambda_function.zip
This is a zip file containing a single Python file named lambda_function.py with the following content:

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': 'Hello from Lambda!'
    }

This zip file is the deployment package for the Lambda function.

The lambda_function.py file contains the code AWS Lambda will run. The lambda_handler function is the entry point. AWS Lambda runs this function when triggered.

The zip file is uploaded to AWS Lambda to create the function.

Commands
This command creates a new Lambda function named 'my-lambda-function' using Python 3.9. It uses the specified IAM role for permissions, sets the handler to the lambda_handler function inside lambda_function.py, and uploads the code from the zip file.
Terminal
aws lambda create-function --function-name my-lambda-function --runtime python3.9 --role arn:aws:iam::123456789012:role/lambda-execution-role --handler lambda_function.lambda_handler --zip-file fileb://lambda_function.zip
Expected OutputExpected
{ "FunctionName": "my-lambda-function", "FunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:my-lambda-function", "Runtime": "python3.9", "Role": "arn:aws:iam::123456789012:role/lambda-execution-role", "Handler": "lambda_function.lambda_handler", "CodeSize": 123, "Description": "", "Timeout": 3, "MemorySize": 128, "LastModified": "2024-06-01T12:00:00.000+0000", "CodeSha256": "abc123def456ghi789jkl012mno345pqr678stu901vwx234yz567", "Version": "$LATEST", "TracingConfig": { "Mode": "PassThrough" }, "RevisionId": "1a2b3c4d-5678-90ab-cdef-EXAMPLE11111" }
→
--function-name - Sets the name of the Lambda function.
→
--runtime - Specifies the language runtime environment.
→
--role - Defines the IAM role that Lambda assumes when running the function.
→
--handler - Specifies the entry point function in the code.
→
--zip-file - Uploads the zipped code package.
This command runs the Lambda function named 'my-lambda-function' and saves the output to a file named output.txt to verify it works.
Terminal
aws lambda invoke --function-name my-lambda-function output.txt
Expected OutputExpected
{ "StatusCode": 200, "ExecutedVersion": "$LATEST" }
→
--function-name - Specifies which Lambda function to run.
This command shows the content of the output.txt file to see the Lambda function's response.
Terminal
cat output.txt
Expected OutputExpected
{"statusCode": 200, "body": "Hello from Lambda!"}
Key Concept

If you remember nothing else from this pattern, remember: AWS Lambda runs your code in response to events without needing servers, and you create it by uploading your code and setting a handler.

Common Mistakes
Using the wrong handler name in the create-function command.
Lambda won't find the entry point and will fail to run your code.
Make sure the handler flag matches the filename and function name exactly, like 'lambda_function.lambda_handler'.
Not assigning the correct IAM role with execution permissions.
Lambda will not have permission to run or access resources, causing errors.
Use an IAM role with the AWSLambdaBasicExecutionRole policy attached.
Uploading the code without zipping it properly.
Lambda expects a zip file; uploading a folder or wrong format causes deployment failure.
Zip your code files into a single archive and upload that zip file.
Summary
Create a deployment package by zipping your Lambda function code.
Use the AWS CLI create-function command to create the Lambda function with the right runtime, role, handler, and code.
Invoke the function using the AWS CLI to test it and check the output.

Practice

(1/5)
1. What is the main purpose of an AWS Lambda function?
easy
A. To run code without managing servers
B. To store large amounts of data
C. To create virtual machines
D. To manage user permissions

Solution

  1. Step 1: Understand Lambda's role

    AWS Lambda lets you run code without needing to manage servers or infrastructure.
  2. Step 2: Compare options

    The incorrect options describe other AWS services such as user permissions (IAM), data storage (S3), and virtual machines (EC2).
  3. Final Answer:

    To run code without managing servers -> Option A
  4. Quick Check:

    Lambda = serverless code execution [OK]
Hint: Lambda runs code without servers [OK]
Common Mistakes:
  • Confusing Lambda with storage services
  • Thinking Lambda manages servers
  • Mixing Lambda with user management
2. Which of the following is the correct way to specify the handler when creating a Lambda function in AWS?
easy
A. handler.index
B. index.handler
C. lambda.handler
D. handler.lambda

Solution

  1. Step 1: Understand handler format

    The handler is specified as filename.functionname. Commonly, the file is index and function is handler.
  2. Step 2: Match options

    Only index.handler matches the correct format; others reverse or misuse parts.
  3. Final Answer:

    index.handler -> Option B
  4. Quick Check:

    Handler = filename.function [OK]
Hint: Handler format is filename.functionname [OK]
Common Mistakes:
  • Swapping filename and function name
  • Using invalid handler names
  • Confusing handler with runtime
3. Given this AWS Lambda function code snippet in Python:
def handler(event, context):
    return event.get('key', 'default')

What will be the output if the event is {}?
medium
A. "default"
B. None
C. Error
D. "key"

Solution

  1. Step 1: Analyze the handler function

    The function returns the value of 'key' from event, or 'default' if 'key' is missing.
  2. Step 2: Check the event input

    The event is an empty dictionary, so 'key' is not present, so it returns 'default'.
  3. Final Answer:

    "default" -> Option A
  4. Quick Check:

    Missing key returns default [OK]
Hint: Missing dict key returns default value [OK]
Common Mistakes:
  • Assuming missing key returns None
  • Expecting an error on missing key
  • Confusing key name with value
4. You created a Lambda function but it fails with a permissions error when invoked. What is the most likely cause?
medium
A. The deployment package is too large
B. The handler name is incorrect
C. The runtime is not supported
D. The Lambda execution role lacks necessary permissions

Solution

  1. Step 1: Understand permissions in Lambda

    Lambda functions need an IAM role with permissions to run and access resources.
  2. Step 2: Identify cause of permissions error

    A permissions error usually means the execution role is missing required permissions.
  3. Final Answer:

    The Lambda execution role lacks necessary permissions -> Option D
  4. Quick Check:

    Permissions error = missing IAM role rights [OK]
Hint: Check IAM role permissions for Lambda [OK]
Common Mistakes:
  • Blaming handler name for permissions error
  • Ignoring IAM role setup
  • Assuming runtime causes permissions error
5. You want to create a Lambda function that processes images uploaded to an S3 bucket. Which combination of settings is required to ensure the Lambda runs automatically when a new image is uploaded?
hard
A. Set Lambda runtime to Node.js and upload images directly to Lambda
B. Manually invoke Lambda after uploading images to S3
C. Set S3 event trigger on bucket for 'ObjectCreated' and assign Lambda execution role with S3 read permissions
D. Create an EC2 instance to monitor S3 and call Lambda

Solution

  1. Step 1: Configure S3 event trigger

    To run Lambda automatically on uploads, configure S3 to trigger Lambda on 'ObjectCreated' events.
  2. Step 2: Assign correct IAM role permissions

    Lambda needs an execution role with permissions to read from S3 to process images.
  3. Final Answer:

    Set S3 event trigger on bucket for 'ObjectCreated' and assign Lambda execution role with S3 read permissions -> Option C
  4. Quick Check:

    S3 trigger + IAM role = automatic Lambda run [OK]
Hint: Use S3 event triggers with proper IAM role [OK]
Common Mistakes:
  • Thinking manual invocation is automatic
  • Confusing runtime with event triggers
  • Using EC2 unnecessarily for Lambda triggers
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard