AWS CLI Lambda Function Example

December 01, 2018

Photo by Rahul Chakraborty on Unsplash

Tutorial: AWS CLI Lambda Function Example

Technology is constantly evolving. In the near future, everyone will be moving towards serverless architectures or Lambda in the context of AWS. Serverless refers to how that you don’t interact with anything lower than the application layer.

Say you host a website similar to Amazon, managing the infrastructure to host and execute backend code requires requires you to do the following.

  • Monitor for performance and availability
  • Manage operating system updates
  • Apply security patches
  • Scale the number of servers to match demand

Purchasing hardware requires a sizable capital investment up front. A single server can handle a certain number of requests at a given point in time. In the event there’s a short window where the traffic is beyond its capacity, you must purchase another server to meet the demand, even though both servers might end up sitting idle around say 2 in the morning.

With AWS Lambda, you’re charged a low fee per request and for the time your code runs in increments of one hundred milliseconds. If the demand goes up, AWS will automatically provision servers to give users a seamless experience. When demand goes down, it will decommission the servers so that you don’t have to continue to incur computational costs.

When writing Lambda functions, you can choose between the following languages.

In the proceeding example, we will be making use of Node (Javascript). Lambda functions consist of handlers to be triggered on particular events such as an upload to a S3 bucket.

exports.handler = async function(event, context, callback) {
  return 'hello world';

Before we can upload our code, we must create a zip file.

**zip index.js**

Next, we will create a role based off the following configuration file.

  "Version": "2012-10-17",
  "Statement": [
      "Effect": "Allow",
      "Principal": {
      "Service": [
      "Action": "sts:AssumeRole"
**aws iam create-role --role-name lambda-role --assume-role-policy-document file://role.json**

Make sure you copy the Amazon Resource Name (ARN) from the output as we’ll use it to create the lambda function.

When specifying the handler, use the following syntax.


`**aws lambda create-function --function-name hello-world --zip-file fileb:// --runtime nodejs8.10 --role**` **arn:aws:iam::084696551378:role/lambda-role --handler index.handler**

We can trigger the Lambda function manually by running the proceeding command.

`**aws lambda invoke --function-name hello-world**` **outputfile.txt**

The value returned by our function is stored in the outputfile.txt. We can view the contents with cat outputfile.txt.

Cory Maklin
_Sign in now to see your channels and recommendations!

Profile picture

Written by Cory Maklin Genius is making complex ideas simple, not making simple ideas complex - Albert Einstein You should follow them on Twitter