Photo by Rahul Chakraborty on Unsplash

AWS CLI Lambda Function Example

Cory Maklin
2 min readDec 1, 2018

--

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.

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

zip function.zip index.js

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

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.

<Name of file>.<Handler>

aws lambda create-function --function-name hello-world --zip-file fileb://function.zip --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.

--

--