Bird
Raised Fist0
AWScloud~5 mins

Lambda function concept in AWS - Commands & Configuration

Choose your learning style10 modes available
Introduction
Sometimes you want to run small pieces of code without managing servers. AWS Lambda lets you do this by running your code only when needed and charging you only for the time it runs.
When you want to run code in response to events like file uploads or button clicks without setting up servers.
When you need to run small tasks that start quickly and finish fast.
When you want to save money by paying only for the exact time your code runs.
When you want to build parts of an app that automatically scale with demand.
When you want to connect different cloud services with simple code snippets.
Config File - lambda_function.py
lambda_function.py
def lambda_handler(event, context):
    message = 'Hello, ' + event.get('name', 'World') + '!'
    return {
        'statusCode': 200,
        'body': message
    }

This is a simple AWS Lambda function written in Python.

lambda_handler is the entry point AWS Lambda uses to run your code.

event contains input data, here it looks for a 'name' key.

context provides runtime info but is not used here.

The function returns a greeting message with a status code.

Commands
This command creates a new Lambda function named 'helloFunction' using Python 3.9. It specifies the execution role and the handler function inside the code package zipped as 'function.zip'.
Terminal
aws lambda create-function --function-name helloFunction --runtime python3.9 --role arn:aws:iam::123456789012:role/lambda-execution-role --handler lambda_function.lambda_handler --zip-file fileb://function.zip
Expected OutputExpected
{ "FunctionName": "helloFunction", "FunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:helloFunction", "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": "abc123def456ghi789", "Version": "$LATEST", "TracingConfig": { "Mode": "PassThrough" }, "RevisionId": "xyz987uvw654" }
→
--function-name - Sets the name of the Lambda function.
→
--runtime - Specifies the language runtime environment.
→
--handler - Defines the entry point function in your code.
This command runs the Lambda function 'helloFunction' with input data where name is 'Alice'. The output is saved to 'response.json'.
Terminal
aws lambda invoke --function-name helloFunction --payload '{"name": "Alice"}' response.json
Expected OutputExpected
{ "StatusCode": 200 }
→
--payload - Sends input data to the Lambda function.
This command shows the output returned by the Lambda function stored in 'response.json'.
Terminal
cat response.json
Expected OutputExpected
{ "statusCode": 200, "body": "Hello, Alice!" }
Key Concept

If you remember nothing else from this pattern, remember: AWS Lambda runs your code only when triggered, so you don't need to manage servers or pay for idle time.

Common Mistakes
Using the wrong handler name in the create-function command.
AWS Lambda won't find the entry point and the function will fail to run.
Make sure the handler matches the filename and function name exactly, like 'lambda_function.lambda_handler'.
Not packaging the code correctly into a zip file before deployment.
AWS Lambda requires a zip file with your code; missing or wrong packaging causes deployment errors.
Zip your code file(s) properly and reference the zip file in the create-function command.
Not providing the correct IAM role ARN with necessary permissions.
Lambda needs permission to run; without the right role, the function creation or execution will fail.
Use an IAM role with the AWSLambdaBasicExecutionRole policy attached and provide its ARN.
Summary
Create a Lambda function by packaging your code and specifying runtime, handler, and execution role.
Invoke the Lambda function with input data to run your code on demand.
Check the output saved in a file to see the function's response.

Practice

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

Solution

  1. Step 1: Understand Lambda's role

    AWS Lambda runs your code without needing you to manage servers.
  2. Step 2: Compare options

    Options A, C, and D describe other AWS services, not Lambda.
  3. Final Answer:

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

    Lambda = serverless code execution [OK]
Hint: Lambda runs code without servers, not storage or VMs [OK]
Common Mistakes:
  • Confusing Lambda with storage services
  • Thinking Lambda creates virtual machines
  • Assuming Lambda manages user permissions
2. Which of the following is the correct way to define a simple AWS Lambda function handler in Python?
easy
A. lambda handler(event): print('Hello World')
B. function handler(event) { return 'Hello World'; }
C. def handler(event, context): return 'Hello World'
D. def handler(): print('Hello World')

Solution

  1. Step 1: Identify correct Python Lambda handler syntax

    Lambda handlers in Python must accept two parameters: event and context.
  2. Step 2: Check each option

    def handler(event, context): return 'Hello World' correctly defines a Python function with event and context parameters and returns a string. function handler(event) { return 'Hello World'; } is JavaScript syntax. lambda handler(event): print('Hello World') misuses lambda keyword. def handler(): print('Hello World') lacks required parameters.
  3. Final Answer:

    def handler(event, context): return 'Hello World' -> Option C
  4. Quick Check:

    Python Lambda handler needs event and context [OK]
Hint: Python Lambda handlers always have (event, context) parameters [OK]
Common Mistakes:
  • Using JavaScript syntax in Python Lambda
  • Omitting event or context parameters
  • Misusing lambda keyword for handler
3. Given this AWS Lambda Python code:
def handler(event, context):
    name = event.get('name', 'Guest')
    return f"Hello, {name}!"

What will be the output if the event is {}?
medium
A. "Hello, Guest!"
B. "Hello, None!"
C. Error: 'name' key missing
D. "Hello, !"

Solution

  1. Step 1: Analyze event input and code behavior

    The event is an empty dictionary, so event.get('name', 'Guest') returns the default 'Guest'.
  2. Step 2: Determine return value

    The function returns the string "Hello, Guest!" because 'name' is not in event.
  3. Final Answer:

    "Hello, Guest!" -> Option A
  4. Quick Check:

    Missing key uses default value 'Guest' [OK]
Hint: event.get with default returns default if key missing [OK]
Common Mistakes:
  • Assuming missing key causes error
  • Thinking None is returned instead of default
  • Ignoring default value in get()
4. You wrote this AWS Lambda function in Python:
def handler(event, context):
    return event['message']

When triggered with event {}, it throws a KeyError. How can you fix it?
medium
A. Use event.get('message', 'No message') instead of event['message']
B. Remove the return statement
C. Add a print statement before return
D. Change function name to lambda_handler

Solution

  1. Step 1: Identify cause of KeyError

    Accessing event['message'] when 'message' key is missing causes KeyError.
  2. Step 2: Use safe access method

    Replacing event['message'] with event.get('message', 'No message') avoids error by providing default.
  3. Final Answer:

    Use event.get('message', 'No message') instead of event['message'] -> Option A
  4. Quick Check:

    Use get() to avoid KeyError on missing keys [OK]
Hint: Use get() with default to prevent KeyError [OK]
Common Mistakes:
  • Ignoring missing key causes error
  • Thinking print fixes KeyError
  • Assuming function name affects key access
5. You want an AWS Lambda function to process image uploads to S3 and resize them. Which combination of AWS services and Lambda features is best suited for this task?
hard
A. Use Lambda to create EC2 instances that resize images
B. Run Lambda on a schedule to scan S3 and resize images manually
C. Upload images directly to Lambda storage for resizing
D. Use S3 event trigger on object creation to invoke Lambda, which resizes images and saves back to S3

Solution

  1. Step 1: Understand event-driven processing

    S3 can trigger Lambda automatically when new objects are created, ideal for immediate processing.
  2. Step 2: Evaluate options for image resizing

    Use S3 event trigger on object creation to invoke Lambda, which resizes images and saves back to S3 uses S3 event triggers and Lambda to resize and save images back to S3, which is efficient and serverless. Run Lambda on a schedule to scan S3 and resize images manually delays processing and requires scanning. Use Lambda to create EC2 instances that resize images misuses Lambda to create servers. Upload images directly to Lambda storage for resizing is invalid as Lambda has no persistent storage for uploads.
  3. Final Answer:

    Use S3 event trigger on object creation to invoke Lambda, which resizes images and saves back to S3 -> Option D
  4. Quick Check:

    S3 event triggers + Lambda = best for image processing [OK]
Hint: Use S3 event triggers to run Lambda on uploads [OK]
Common Mistakes:
  • Thinking Lambda can store files persistently
  • Using scheduled scans instead of event triggers
  • Misusing Lambda to create servers
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