Serverless Deployment: Deploying Your App to AWS Lambda
Written by Sigal Zigelboim   
Tuesday, 27 June 2023
Article Index
Serverless Deployment: Deploying Your App to AWS Lambda
Add AWS Resources

 

Add AWS Resources

At this stage, the Git repository created by Lambda should include a template, function code, and build specification. You can modify the template and push the changes to this repository to include additional resources in the application.  

Cloning the repository

You might choose to create a local copy of the repository by cloning it: 

  1. On the Applications page, select the application (my-app).

  2. Click on Code.

  3. Go to the Repository details tab and copy the repository URI (SSH or HTTP, depending on your specified authentication mode).  

LA3

  4. Apply the following command to copy the repository:

git clone
ssh://git-codecommit.us-east-1.amazonaws.com/v1/
                                                                repos/my-test-app-repo

Note: SSH is the most common option for GIT authentication.

LA4

Adding a table

You can also add a DynamoDB table to your application by defining the resource AWS::Serverless::SimpleTable in your template:

  1. In a text editor, open the template.yml.

  2. Add the following resources:

    • A table

    • An environment variable to pass the table’s name to your Lambda function

    • A permissions policy to enable the function to manage the resource.

For example:

...
Resources:
  ddbTable:
    Type: AWS::Serverless::SimpleTable
    Properties:
      PrimaryKey:
        Name: id
        Type: String
      ProvisionedThroughput:
        ReadCapacityUnits: 1
        WriteCapacityUnits: 1
  helloFromLambdaFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./
      Handler: src/handlers/
hello-from-lambda.helloFromLambdaHandler
      Runtime: nodejs14.x
      MemorySize: 128
      Timeout: 90
      Description: A Lambda function that
generates a static string.
      Environment:
        Variables:
          DDB_TABLE: !Ref ddbTable
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref ddbTable
        - AWSLambdaBasicExecutionRole 
  1. Commit the change and push it to the repository using the following command:  

git commit -am "Add DynamoDB table"
git push

Once the change is pushed, it will trigger the application pipeline.

 4. You can see the change’s progress through the application pipeline under Deployments.LA5

Update Your Function’s Code

You need to update the Lambda function’s code to enable it to use the DynamoDB table. The example code here uses the table to keep track of how many invocations each function instance has processed. The log-stream ID acts as a unique identifier for each function instance.

To update your function’s code:

  1. Add a handler to the src/handlers folder. It should have the name “index.js” and include this content:

const dynamodb = require('aws-sdk/clients/dynamodb');
const docClient = new dynamodb.DocumentClient();

exports.handler = async (event, context) => {
    const message = 'Hello from Lambda!';
    const tableName = process.env.DDB_TABLE;
    const logStreamName = context.logStreamName;
    var params = {
        TableName : tableName,
        Key: { id : logStreamName },
        UpdateExpression: 'set invocations =
                             if_not_exists(invocations, :start) + :inc',
        ExpressionAttributeValues: {
            ':start': 0,
            ':inc': 1
        },
        ReturnValues: 'ALL_NEW'
    };
    await docClient.update(params).promise();

    const response = {
        body: JSON.stringify(message)
    };
    console.log(`body: ${response.body}`);
    return response;
}

  1. Go to the template and modify the handler’s value to “src/handlers/index.handler”. The template YAML should look like this:
    ...

  helloFromLambdaFunction:

    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./
      Handler: src/handlers/index.handler
      Runtime: nodejs14.x

 

  1. Commit the change and push it to the repository: 

git add . && git commit -m "Use DynamoDB table"

git push

  1. Once you’ve deployed the change, you can invoke the Lambda function several times to ensure the table is up to date. You can view the table via the DynamoDB console on the Tables page.

  2. Select the table starting with “my-app” and click on Items.

LASSall 6. Select Start search to find the table.

Lx

Lambda can create more instances of a function when it needs to handle simultaneous invocations. The log group CloudWatch Logs should contain individual logs corresponding to specific function instances. When you change the function code or its configuration, Lambda creates a new instance of the function.

Monitor the Application

You can also leverage the AWS Lambda console to monitor Lambda applications and make management easier. You can view a CloudWatch dashboard under the Monitoring tab, which aggregates metrics for an application’s resources.

Lfinal

The console will display a basic dashboard by default, but this page can be customized via the application template. If the template contains one or multiple dashboards, the dashboard page will show the specified dashboards rather than the default dashboard. The drop-down menu at the top right of this page lets you switch between dashboard views. 

For a more detailed view of your serverless application and the entire event pipeline, use distributed tracing tools like Amazon X-Ray. 

Conclusion

In conclusion, serverless deployment offers a powerful and scalable way of deploying applications to the cloud. By using AWS Lambda, developers can leverage the benefits of serverless computing and focus on writing code instead of managing infrastructure. 

In this article, we've walked through the steps of deploying an application to AWS Lambda using the Serverless Framework. We've covered the basics of creating an application, invoking a Lambda function, adding AWS resources, updating the function’s code, and monitoring the application. 

The process of deploying an application to AWS Lambda using the Serverless Framework is straightforward and offers a lot of flexibility in terms of configuration and customization. As serverless deployment continues to gain popularity, we can expect to see more tools and services being developed to simplify the process even further.  

Serverless sq

 Image Credit:vectorjuice on Freepik

Related Articles 

AWS Lambda For The Impatient Parts 1-3

Cloud Bursting: A Practical Guide to Hybrid Cloud Automation

Google Goes Serverless with Cloud Functions

Sysdig Exposes The Risk and Cost Of Cloud Usage

Google Cloud Training Free On edX

Insights Into Successful Software Delivery

 

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

 

Banner


Run WebAssembly Components Inside Node.js With Jco
28/03/2024

Jco 1.0 has been just announced by the Bytecode Alliance.It's a native JavaScript WebAssembly toolchain and runtime that runs Wasm components inside Node.js. Why is that useful?



The University of Tübingen's Self-Driving Cars Course
22/03/2024

The recorded lectures and the written material of a course on Self-Driving Cars at the University of Tübingen have been made available for free. It's a first class opportunity to learn the in an [ ... ]


More News

raspberry pi books

 

Comments




or email your comment to: comments@i-programmer.info



Last Updated ( Wednesday, 28 June 2023 )