AWS Lambda
Configuring Lambda
Create a Basic Lambda Function using CLI
Building serverless applications with AWS Lambda becomes seamless when you automate deployments using the AWS Command Line Interface (CLI). In this tutorial, you’ll learn how to write, package, deploy, and test a simple Python-based Lambda function from start to finish.
Environment Setup
Before we dive in, ensure you have the following:
- AWS CLI installed and configured
- Python 3.x installed on your local machine
- An IDE or text editor (e.g., Visual Studio Code)
- AWS account with permissions to create IAM roles and Lambda functions
Note
Run aws configure
to set up your credentials, default region (e.g., us-east-1
), and output format (json
).
To begin, verify there are no existing Lambda functions in your target region:
1. Write the Lambda Function
Create a file named basic_hello_world.py
and add:
def lambda_handler(event, context):
if event.get("name") == "KodeKloud":
return "Successful"
return "Failed"
This handler inspects the name
key in the incoming event and returns "Successful"
when it matches "KodeKloud"
.
2. Package Your Code
AWS Lambda requires your function code in a ZIP archive. On Windows:
- Right-click
basic_hello_world.py
- Select Send to → Compressed (zipped) folder
- Name it
basic_hello_world.zip
3. Create an IAM Execution Role
Your function needs permission to write logs to CloudWatch. In the IAM console:
- Create or select a role (e.g., LambdaDemoRole)
- Attach the AWSLambdaBasicExecutionRole policy
- Copy the Role ARN for use in the CLI
Warning
Keep your IAM credentials secure. Grant only the permissions your function requires.
4. Deploy the Function with AWS CLI
Use the create-function
command to deploy:
aws lambda create-function \
--function-name basic_hello_world \
--runtime python3.7 \
--role arn:aws:iam::610879136425:role/LambdaDemoRole \
--handler basic_hello_world.lambda_handler \
--zip-file fileb://basic_hello_world.zip
On success, you’ll see a JSON payload with details like function name, runtime, role, and handler.
5. Verify Deployment
Refresh the AWS Lambda console in the us-east-1 region. Your function should appear in the list:
6. Test Your Lambda Function
Click Test in the function’s detail page.
Create a new event named Demo Test Event.
Replace the sample JSON with:
{ "name": "KodeKloud" }
Save and run. The execution result should return:
Successful
Summary of AWS CLI Commands
Step | Command | Description |
---|---|---|
Configure AWS CLI | aws configure | Set credentials, region, and output format |
Create Lambda function | aws lambda create-function … | Deploy code as a new Lambda function |
Update function code (future) | aws lambda update-function-code … | Replace function ZIP with new code |
Congratulations! You now have a working Python Lambda function entirely managed through the AWS CLI.
References
Watch Video
Watch video content
Practice Lab
Practice lab