AWS LAMBDA Function made easy

kunal singh
2 min readSep 12, 2021

Lets create and activate virtual environment

python3 -m venv venv
source venv/bin/activate

For creating and deploying the lambda we will use chalice. Lets install it first

python3 -m pip install chalice

Now platform is setup lets create and deploy our project.

chalice new-project helloworld
cd helloworld

In the helloworld directory you will be seeing two files:

  1. app.py : This file contains special functions which are called as handlers, which are called when certain conditions are met. Example say you want to call the function every five minutes or when a file is dropped in S3 or even as REST api it can be called.
  2. requirements.txt : We need to add all the files that need to be installed in AWS when we deploy it.

Easy way to add all the library/modules that we have installed till now is by following command

pip freeze > requirements.txt

Lets go through sample handler that’s get created initially when we create our project and is present in app.py file.

@app.route('/')
def index():
return {'hello': 'world'}

This is basically a handler that will be triggered via REST api, that will be generated when we deploy it.

Let’s deploy our helloworld lambda .

If your AWS profile is default then use

chalice deploy 

else

chalice deploy --profile <name of profile you want to use>

If you have not configured your aws profile first configure it first.

After deploying the lambda function you will get an endpoint url, just copy the url and paste in browser. You will get something like this if everything is fine.

{"hello": "world"}

Now you can play with the lambda function by adding some custom code and response.

In case you faced any issue while deploying lambda there can be multiple reason:

  1. Main Reason could be you don’t have permission to create own IAM Role for that please update config.json present in .chalice/ directory. For that you will be needing an IAM role that has access to AWS lambda and api gateway.
{
"version": "2.0",
"app_name": "helloworld",
"stages": {
"dev": {
"api_gateway_stage": "api",
"manage_iam_role": false,
"iam_role_arn": "<role for lambda and api gateway>",
}
}
}

Now to delete your lambda function run:

chalice delete

In this blog we added a saw an example lambda that was getting triggered via API, In coming blogs we will see how can we create lambda that gets triggered like a Cron Job(which runs at particular interval) or it gets triggered when we drop a new file in a particular S3 bucket in particular path.

Stay tuned.

--

--