Create & deploy your first-ever AWS lambda function by serverless

Hello, developers. As we know, there is a lot of hype about cloud computing or, in a single term, Serverless. So, what problems is it solving exactly? Cloud computing is the on-demand availability of computer system resources, especially data storage and computing power, without direct active management by the user. The term is generally used to describe data centers available to many users over the Internet.

If we had to define cloud computing in a single line, it would be Communication Network.

The word cloud often refers to the Internet and, more precisely, to some Data-Centers full of servers connected with the Internet.

Cloud computer is a vast field of Information Technology, so I will not discuss it. What this article is really about is the basics of Serverless and Lambda functions.

But what exactly is this term, Serverless?

Serverless

Serverless or Serverless Computing is an architectural model for your application infrastructure where you don’t have to worry about managing your own servers or creating your own deployment models. Instead, you just use someone else servers or machines and pay them to use it.

Alt Text

Serverless is just a fancy word for someone’s servers or Paas (Product as a Service).

Lambda functions

We’ll use Lambda functions which are standard cloud functions for AWS. Lambda functions let you run code without any provisioning or managing servers. You only pay for the compute-time you consume.

Enough talk, let’s do some practical stuff.

First of all, I am gonna install Serverless Framework globally in my machine via npm (node package manager). Serverless Framework is a framework that helps you build cheaper serverless apps with radically less overhead. It provides a powerful, unified experience to develop, deploy, test, secure, and monitor your serverless application, as well as own CLI (command-line interface) where you can manage almost all operations.

Now, open your terminal in Linux or command prompt if you are in windows, and install the serverless framework:

 // Install the serverless CLI
 npm install -g serverless

 // Or, update the serverless CLI from a previous version
 npm update -g serverless

You can actually check if it installed successfully by typing:

 // where serverless is installed on your machine
 which serverless

 // check all available commands
 serverless --help

Now, you have to connect with it with your AWS account. If you do not yet have an account, you can create one with the free tier for playing around with.

After creating an account, go to Cloud Console and into IAM service to create a user, but it’s not mandatory. You can create a sub-user and connect with it. The main thing you’ll need for connecting your serverless framework CLI to your AWS account is an Access Key Id & Secret Access Key, which you’ll get once you create your account.

// This command will connect your serverless CLI to AWS account 
serverless config credentials --provider aws --key my-access-id --secret my-secret-id

where --provider flag is for the which cloud service you want to connect, --key if for access key id, and --secret is for secret id.

If everything works correctly, you’ll see this screen:

Alt Text

In your main Home directory, there will be a file saved under the name .aws. This file contains your credentials.

So far so good, now create a serverless project based on node.js by command-line interface:

// creating a serverless template for node.js
serverless create --template aws-nodejs --path first-lambda-functions --name first-lambda-functions

After typing the above command, you’ll see this on your cmd:

Alt Text

Now, go to the newly created project by changing directory into the project directory: cd first-lambda-functions. You’ll see two files named handler.js and serverless.yml.

Handler.js

handler.js is your file where you will write your functions.

Serverless.yml

serverless.yml is your file where all your AWS configurations will be written.

In serverless.yml you’ll see this code:

# Welcome to Serverless!
#
# This file is the main config file for your service.
# It's very minimal at this point and uses default values.
# You can always add more config options for more control.
# We've included some commented out config examples here.
# Just uncomment any of them to get that config option.
#
# For full config options, check the docs:
#    docs.serverless.com
#
# Happy Coding!

service: aws-node-example
# app and org for use with dashboard.serverless.com
#app: your-app-name
#org: your-org-name

# You can pin your service to only deploy with a specific Serverless version
# Check out our docs for more details
# frameworkVersion: "=X.X.X"

provider:
  name: aws
  runtime: nodejs12.x

# you can overwrite defaults here
#  stage: dev
#  region: us-east-1

# you can add statements to the Lambda function's IAM Role here
#  iamRoleStatements:
#    - Effect: "Allow"
#      Action:
#        - "s3:ListBucket"
#      Resource: { "Fn::Join" : ["", ["arn:aws:s3:::", { "Ref" : "ServerlessDeploymentBucket" } ] ]  }
#    - Effect: "Allow"
#      Action:
#        - "s3:PutObject"
#      Resource:
#        Fn::Join:
#          - ""
#          - - "arn:aws:s3:::"
#            - "Ref" : "ServerlessDeploymentBucket"
#            - "/*"

# you can define service wide environment variables here
#  environment:
#    variable1: value1

# you can add packaging information here
#package:
#  include:
#    - include-me.js
#    - include-me-dir/**
#  exclude:
#    - exclude-me.js
#    - exclude-me-dir/**

functions:
  currentTime:
    handler: handler.currentTime
    events:
      - http: 
          path: current-time
          method: get
   # The following are a few example events you can configure
   # NOTE: Please make sure to change your handler code to work with those events
   # Check the event documentation for details
#    events:
#      - http:
#          path: users/create
#          method: get
#      - websocket: $connect
#      - s3: ${env:BUCKET}
#      - schedule: rate(10 minutes)
#      - sns: greeter-topic
#      - stream: arn:aws:dynamodb:region:XXXXXX:table/foo/stream/1970-01-01T00:00:00.000
#      - alexaSkill: amzn1.ask.skill.xx-xx-xx-xx
#      - alexaSmartHome: amzn1.ask.skill.xx-xx-xx-xx
#      - iot:
#          sql: "SELECT * FROM 'some_topic'"
#      - cloudwatchEvent:
#          event:
#            source:
#              - "aws.ec2"
#            detail-type:
#              - "EC2 Instance State-change Notification"
#            detail:
#              state:
#                - pending
#      - cloudwatchLog: '/aws/lambda/hello'
#      - cognitoUserPool:
#          pool: MyUserPool
#          trigger: PreSignUp
#      - alb:
#          listenerArn: arn:aws:elasticloadbalancing:us-east-1:XXXXXX:listener/app/my-load-balancer/50dc6c495c0c9188/
#          priority: 1
#          conditions:
#            host: example.com
#            path: /hello

#    Define function environment variables here
#    environment:
#      variable2: value2

# you can add CloudFormation resource templates here
#resources:
#  Resources:
#    NewResource:
#      Type: AWS::S3::Bucket
#      Properties:
#        BucketName: my-new-bucket
#  Outputs:
#     NewOutput:
#       Description: "Description for the output"
#       Value: "Some output value"

Where service property will be your project folderwhere your functions are. The provider name is AWS as we have chosen AWS and nodejs, which are installed in your machine. functions is our function name, which in this case is currentTime. Your function is saved in handler(path).

Now, let’s check our function handler.js code:

'use strict';

module.exports.currentTime = async event => {
  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: `Current time: ${new Date().toTimeString()}`,
        input: event,
      },
      null,
      2
    ),
  };  
};

We have created a function named currentTime which returns current date time in string format with statusCode 200.

Now, in cmd if you type:

// invoking function locally
serverless invoke local --function currentTime

You’ll get your response:

{
    "statusCode": 200,
    "body": "{\n  \"message\": \"Current time: 18:17:02 GMT+0000 (Coordinated Universal Time)\",\n  \"input\": {}\n}"
}

But the whole purpose of this article is to show you how to deploy this function. So we’ll do type:

//deploying to AWS via serverless
serverless deploy

During this process whole services are packaged, a cloud formation stack is created, and eventually, the whole thing is deployed.

Alt Text

Now, the URL provided in the GET endpoint is your Lambda function URL.

You can try using curl to find the response of this URL by typing:

  curl https://ipfs3cwa7g.execute-api.us-east-1.amazonaws.com/dev/current-time

And you’ll see your response in the terminal.

If you go to your AWS cloud console and go to cloudformation service, you’ll see your deployed function details for every operation done on that function. Like below, in my console screen.

Alt Text

🎉🎉 So, finally, you can deploy your first ever Lambda function to AWS. 🎉🎉

Free Resources