Function in C#

AWS Lambda – Function in C# ”; Previous Next This chapter will explain you how to work with AWS Lambda function in C# in detail. Here, we are going to use visual studio to write and deploy the code to AWS Lambda. For any information and help regarding installation of Visual studio and adding AWS toolkit to Visual Studio, please refer to the Introduction chapter in this tutorial. Once you are done with installation of Visual Studio, please follow the steps given below. Refer to the respective screenshots for a better understanding − Step 1 Open your Visual Studio and follow the steps to create new project. Click on File -> New -> Project. Step 2 Now, the following screen is displayed wherein you select AWS Lambda for Visual C#. Select AWS Lambda Project (.NET Core). You can change the name if required, will keep here the default name. Click OK to continue. The next step will ask you to select a Blueprint. Select Empty function for this example and click Finish. It will create a new project structure as shown below − Now, select Function.cs which is the main file where the handler with event and context is created for AWS Lambda. The display of the file Functions.cs is as follows − You can use the command given below to serialize the input and output parameters to AWS Lambda function. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] Handler Details for C# The handler is displayed as follows − public string FunctionHandler(string input, ILambdaContext context) { return input?.ToUpper(); } Various components of the above code are explained below − FunctionHandler −This is the starting point of the C# AWS Lambda function. String input − The parameters to the handler string input has all the event data such as S3 object, API gateway details etc. ILambdaContext context − ILamdaContext is an interface which has context details. It has details like lambda function name, memory details, timeout details etc. The Lambda handler can be invoked in sync and async way. If invoked in a sync way as shown above you can have the return type. If async than the return type has to be void. Now, let us deploy the AWS Lambda C# and test the same. Right click the project and click Publish to AWS Lambda as shown below − Fill up the Function Name and click on Next. The next screen displayed is the Advanced Function Details as shown − Enter the Role Name, Memory and Timeout. detailsNote that here we have selected the existing role created and used memory as 128MB and timeout as 10seconds. Once done click Upload to publish to AWS Lambda console. You can see the following screen once AWS Lambda function is uploaded. Click Invoke to execute the AWS Lambda function created. At present, it shows error as it needs some input as per the code written. Now, let us enter some sample input and Invoke it again. Note that here we have entered some text in the input box and the same on clicking invoke is displayed in uppercase in the response section. The log output is displayed below − Now, let us also check AWS console to see if the function is created as we have deployed the function from Visual Studio. The Lambda function created above is aws lambda using csharp and the same is displayed in AWS console as shown in the screenshots given below − Handler Signature Handler is start point for AWS to execute. The name of the handler should be defined as − ASSEMBLY::TYPE::METHOD The details of the signature are explained as below − ASSEMBLY − This is the name of the .NET assembly for the application created. It is basically the name of the folder from where the project is created. TYPE − This is the name of the handler. It is basically the namespace.classname. METHOD − This is the name of the function handler. The code for handler signature is as shown below − using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function”s JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace AWSLambda3 { public class Function { /// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name=”input”></param> /// <param name=”context”></param> /// <returns></returns> public string FunctionHandler(string input, ILambdaContext context) { return input?.ToUpper(); } } } Note that here the assembly is AWSLamda3, Type is namespace.classname which is AWSLambda3.Function and Method is FunctionHandler. Thus, the handler signature is AWSLamda3::AWSLambda3.Function::FunctionHandler Context object in C# Context Object gives useful information about the runtime in AWS environment. The properties available in the context object are as shown in the following table − Sr.No Properties & Description 1 MemoryLimitInMB This will give details of the memory configured for AWS Lambda function 2 FunctionName Name of AWS Lambda function 3 FunctionVersion Version of AWS Lambda function 4 InvokedFunctionArn ARN used to invoke this function. 5 AwsRequestId AWS request id for the AWS function created 6 LogStreamName Cloudwatch log stream name 7 LogGroupName Cloudwatch group name 8 ClientContext Information about the client application and device when used with AWS mobile SDK 9 Identity Information about the amazon cogbnito identity when used with AWS mobile SDK 10 RemainingTime Remaining execution time till the function will be terminated 11 Logger The logger associated with the context Example In this section, let us test some of the above properties in AWS Lambda in C#. Observe the sample code given below − using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function”s JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace AWSLambda6 { public class Function { /// <summary> /// </summary> /// <param name=”input”></param> /// <param name=”context”></param> /// <returns></returns> public void FunctionHandler(ILambdaContext context) { LambdaLogger.Log(“Function name: ” + context.FunctionName+”n”); context.Logger.Log(“RemainingTime: ” + context.RemainingTime+”n”); LambdaLogger.Log(“LogGroupName: ” + context.LogGroupName+”n”); } } } The related output that you can

AWS Lambda – Introduction

AWS Lambda – Introduction ”; Previous Next AWS Lambda is a service which takes care of computing your code without any server. It is said to be serverless compute. The code is executed based on the response of events in AWS services like adding /removing files in S3 bucket, updating Amazon DynamoDBtables, HTTP request from Amazon Api gateway etc. AWS Lambda code can be written in NodeJS, Java, C#, Python and Go. This chapter will talk in detail about creating AWS Lambda function in AWS console. AWS Console Login to AWS Console at the link https://aws.amazon.com/console. Once you login into it, it will redirect you to the screen where AWS services are displayed. Example: Creating a Function Let us understand the functionality of AWS Console with the help of an Example. Click on Lambda (marked above), it will redirect to create function as shown below − Click Create function button and the screen displays following details − Note that, by default, the option is Author from scratch. This option lets you to write the Lambda code from scratch. It will just have a simple function with hello world message. The second option Blue prints has following details. It gives details of code already written for some of the aws services in languages available with AWS Lambda. Incase you need to write AWS Lambda code for any services you can check in blue prints and get started. The third option Serverless Application Repository has the setup of serverless application which will help to deploy the AWS Lambda code. In the discussion further, we will work on the first option where we create the AWS lambda function using Author from scratch. Before we create Lambda function, will need a role i.e, permission for working with AWS services and aws lambda. Later the Role has to be assigned to aws lambda function. Role creation in AWS Console For creating a role in AWS Console, go to AWS console services and click on IAM as shown below − Now, if you click IAM, you will the screen as shown below − If you select Roles, you can see the following buttons on the screen − Now, click Create role. It will ask you to choose the service where you need to use the role created. Since we need to use this role with AWS Lambda, select Lambda and click Next:Permissions button as shown above. The next screen displays the policy name which is available as per AWS services. You can select the policy from here − For Example, if you want permission for AWS Lambda to work with S3 and DynamoDB, you need to select the policy. In the search box, enter the AWS service and click on the checkbox. You can select multiple policies and later click on Next:Review. It is also possible to create policy of your own. For Example, there is dynamodb table and you need to give permission only to that table, under such cases you can create policy. Click on Create policy button as shown in the screen above. Following are the details displayed on screen. Choose a Service for which you are creating the policy. Later it will display data for Actions, resources and Request conditions. Now, we should choose the service. Let us select AWS Dynamodb from search. Actions has following details − Now, enter the Access level you want to give to DynamoDB. Then, resources will display the following details − Now, select the table resource type. You can see the following output − For permission on table, you need to Add ARN. ARN is the details which is unique to the table created in AWS DynamoDB. You will get the details when the table is created in dynamodb. If you click Add ARN and it will display following details − Now, if you enter the ARN and the Region, Account and Table name will get populated. You should click Add button to add the policy. Similarly, you can create policies for other services. Here, we have selected two policies AmazonS3FullAccess and AmazonDynamoDBFullACcess. We have given full access to S3 and DynamoDB in that role. However, it is suggested that you give permission only to necessary buckets and tables. You can follow the steps discussed earlier to create the policies using ARN. Step 1 Click Create role button to create the role. All the roles created are displayed as shown − Step 2 Note that you can select the role you require incase you need any modification for the role created. If we select Author from scratch option, you have to enter Name, Runtime and Role. Step 3 You can observe the following details in Runtime dropdown − Step 4 You can select the runtime of your choice and proceed as shown. Role dropdown has following options − Choose an existing role − This will display all the roles created in the IAM roles. Create new role from template(s) − This will allow you to create role and will display permission to be selected for that role. Observe the screenshot for a better understanding. Create a custom role − This allows the user to create policies as we discussed earlier. Step 5 Select the runtime, role and add the function. Click on Create function button to create the lambda function. The next screen displayed is as follows − Parts of AWS Lambda Function There are two parts for AWS Lambda function:Configuration and Monitoring. Let us discuss each in detail. Configuration The following functionalities are included in the Configuration. Add Triggers The triggers that are needed to added to AWS Lambda function are displayed as follows − Note that when we select a trigger, we need to add the configuration details for that trigger. For Example for S3 trigger, we need to select the bucket name; for Dynamodb trigger we need to select the table name. Example Let us see an example of configuration details for a S3 trigger − Now, add configuration

Function in Java

AWS Lambda – Function in Java ”; Previous Next In this chapter, let us understand in detail how to create a simple AWS Lambda function in Java in detail. Creating JAR file in Eclipse Before proceeding to work on creating a lambda function in AWS, we need AWS toolkit support for Eclipse. For any guidance on installation of the same, you can refer to the Environment Setup chapter in this tutorial. Once you are done with installation, follow the steps given here − Step 1 Open Eclipse IDE and create a new project with AWS Lambda Java Project. Observe the screenshot given below for better understanding − Step 2 Once you select Next, it will redirect you the screen shown below − Step 3 Now, a default code is created for Input Type Custom. Once you click Finish button the project gets created as shown below − Step 4 Now, right click your project and export it. Select Java / JAR file from the Export wizard and click Next. Step 5 Now, if you click Next, you will be prompted save the file in the destination folder which will be asked when you click on next. Once the file is saved, go back to AWS Console and create the AWS Lambda function for Java. Step 6 Now, upload the .jar file that we created using the Upload button as shown in the screenshot given below − Handler Details for Java Handler is package name and class name. Look at the following example to understand handler in detail − Example package com.amazonaws.lambda.demo; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class LambdaFunctionHandler implements RequestHandler { @Override public String handleRequest(Object input, Context context) { context.getLogger().log(“Input: ” + input); // TODO: implement your handler return “Hello from Lambda!”; } } Observe that from the above code, the handler will be com.amazonaws.lambda.demo.LambdaFunctionHandler Now, let us test the changes and see the output − Context Object in Java Interaction with AWS Lambda execution is done using the context. It provides following methods to be used inside Java − Sr.No Context Methods & Description 1 getMemoryLimitInMB() this will give the memory limit you specified while creating lambda function. 2 getFunctionName() this will give the name of the lambda function. 3 getFunctionVersion() this will give the version of the lambda function running. 4 getInvokedFunctionArn() this will give the ARN used to invoke the function. 5 getAwsRequestId() this will give the aws request id. This id gets created for the lambda function and it is unique. The id can be used with aws support incase if you face any issues. 6 getLogGroupName() this will give the aws cloudwatch group name linked with aws lambda function created. It will be null if the iam user is not having permission for cloudwatch logging. 7 getClientContext() this will give details about the app and device when used with aws mobile sdk. It will give details like version name and code, client id, title, app package name. It can be null. 8 getIdentity() this will give details about the amazon cognito identity when used with aws mobile sdk. It can be null. 9 getRemainingTimeInMillis() this will give the remaining time execution in milliseconds when the function is terminated after the specified timeout. 10 getLogger() this will give the lambda logger linked with the context object. Now, let us update the code given above and observe the output for some of the methods listed above. Observe the Example code given below for a better understanding − package com.amazonaws.lambda.demo; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class LambdaFunctionHandler implements RequestHandler<Object, String> { @Override public String handleRequest(Object input, Context context) { context.getLogger().log(“Input: ” + input); System.out.println(“AWS Lambda function name: ” + context.getFunctionName()); System.out.println(“Memory Allocated: ” + context.getMemoryLimitInMB()); System.out.println(“Time remaining in milliseconds: ” + context.getRemainingTimeInMillis()); System.out.println(“Cloudwatch group name ” + context.getLogGroupName()); System.out.println(“AWS Lambda Request Id ” + context.getAwsRequestId()); // TODO: implement your handler return “Hello from Lambda!”; } } Once you run the code given above, you can find the output as given below − Logs for context You can observe the following output when you are viewing your log output − The memory allocated for the Lambda function is 512MB. The time allocated is 25 seconds. The time remaining as displayed above is 24961, which is in milliseconds. So 25000 – 24961 which equals to 39 milliseconds is used for the execution of the Lambda function. Note that Cloudwatch group name and request id are also displayed as shown above. Note that we have used the following command to print logs in Java − System.out.println (“log message”) The same is available in CloudWatch. For this, go to AWS services, select CloudWatchservices and click Logs. Now, if you select the Lambda function, it will display the logs date wise as shown below − Logging in Java You can also use Lambdalogger in Java to log the data. Observe the following example that shows the same − Example package com.amazonaws.lambda.demo; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.LambdaLogger; public class LambdaFunctionHandler implements RequestHandler<Object, String> { @Override public String handleRequest(Object input, Context context) { LambdaLogger logger = context.getLogger(); logger.log(“Input: ” + input); logger.log(“AWS Lambda function name: ” + context.getFunctionName()+”n”); logger.log(“Memory Allocated: ” + context.getMemoryLimitInMB()+”n”); logger.log(“Time remaining in milliseconds: ” + context.getRemainingTimeInMillis()+”n”); logger.log(“Cloudwatch group name ” + context.getLogGroupName()+”n”); logger.log(“AWS Lambda Request Id ” + context.getAwsRequestId()+”n”); // TODO: implement your handler return “Hello from Lambda!”; } } The code shown above will give you the following output − The output in CloudWatch will be as shown below − Error handling in Java for Lambda Function This section will explain how to handle errors in Java for Lambda function. Observe the following code that shows the same − package com.amazonaws.lambda.errorhandling; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class LambdaFunctionHandler implements RequestHandler<Object, String> { @Override public String handleRequest(Object input, Context context) { throw new RuntimeException(“Error from aws lambda”); } } Note that the error details are displayed in json format with errorMessage Error from AWS Lambda. Also, the ErrorType and stackTrace gives more details about the error.

Function in Python

AWS Lambda – Function in Python ”; Previous Next In this chapter, we will create a simple AWS Lambda function in Python and understand its working concepts following detail. Before proceeding to work on creating a Lambda function in AWS, we need AWS toolkit support for Python. For this purpose, follow the steps given below and observe the corresponding screenshots attached − Step 1 Login to AWS console and create Lambda function and select the language as Python. Step 2 Now, click Create function button and enter the details for creating a simple AWS Lambda in Python. This code returns the message Hello from Lambda using Python and looks as shown here − Step 3 Now, save the changes and the test the code to see the output. You should see the following output and logs when you test it in AWS console using the test button from the UI. Step 4 Now, you can write code inside any editor or an IDE for Python. Here, we are using visual studio code for writing the code. You should later zip the file and upload in AWS console. Here, we have zipped the code and using it AWS console. Step 5 Now, select Upload a .ZIP file option as shown below − Handler Details for Python Note that the handler has to be name of the file followed by name of the function. In the above case, our file name is hellopython.py and name of the function is my_handler; so the handler will be hellopython.my_handler. Once the upload is done and changes are saved, it actually shows the details of the zip file in the online editor in AWS Lambda console. Now, let us test the code to see the output and logs. Now, let us understand the details of the Lambda function using the following sample code − def my_handler(event, context): return “aws lambda in python using zip file” In the above code, the function name my_handler is having 2 params, event and context. Context Object in Python Context object gives details like the name of the Lambda function, time remaining in milliseconds, request id, cloud watch group name, timeout details etc. The methods and attributes available on context object are shown in the tables given below − Sr.No Method Name & Description 1 get_remaining_time_in_millis() This method gives the remaining time in milliseconds until the lambda function terminates the function Sr.No Attribute & Description 1 function_name This gives aws lambda function name 2 function_version This gives the version of aws lambda function executing 3 invoked_function_arn This will gives ARN details. 4 memory_limit_in_mb This shows the memory limit added while creating lambda function 5 aws_request_id This gives the aws request id. 6 og_group_name This will give the name of the cloudwatch group name 7 log_stream_name This will give the name of the cloudwatch log stream name where the logs are written. 8 identity This will give details about amazon cognito identity provider when used with aws mobile sdk. Details given are as follows − identity.cognito_identity_id identity.cognito_identity_pool_id 9 client_context This will details of the client application when used with aws mobile sdk. The details given are as follows − client_context.client.installation_id client_context.client.app_title client_context.client.app_version_name client_context.client.app_version_code client_context.client.app_package_name client_context.custom – it has dict of custom values from the mobile client app client_context.env – it has dict of environment details from the AWS Mobile SDK Let us see a working example in Python which outputs the context details. Observe the code given below − def my_handler(event, context): print(“Log stream name:”, context.log_stream_name) print(“Log group name:”, context.log_group_name) print(“Request ID:”,context.aws_request_id) print(“Mem. limits(MB):”, context.memory_limit_in_mb) print(“Time remaining (MS):”, context.get_remaining_time_in_millis()) return “aws lambda in python using zip file” The corresponding output of the code shown above is given below − Logging using Python To log info using Python, we can use print or logger function available. Let us use the above example of context and check inCloudWatch to see if the logs are printed. Observe the following code − def my_handler(event, context): print(“Log stream name:”, context.log_stream_name) print(“Log group name:”, context.log_group_name) print(“Request ID:”,context.aws_request_id) print(“Mem. limits(MB):”, context.memory_limit_in_mb) print(“Time remaining (MS):”, context.get_remaining_time_in_millis()) return “aws lambda in python using zip file” The output of this code in CloudWatch is as shown below − Observe the following example to understand about using logger to print logs to CloudWatch − import logging logger = logging.getLogger() logger.setLevel(logging.INFO) def my_handler(event, context): logger.info(”Using logger to print messages to cloudwatch logs”) return “aws lambda in python using zip file” The output for this will be as shown in the screenshot given below − Error Handling in Python for Lambda function In this section, let us see a working example which shows how to handler errors in Python. Observe the piece of code given here − def error_handler(event, context): raise Exception(”Error Occured!”) The log display is as shown in the image here − Print Page Previous Next Advertisements ”;

AWS Lambda – Overview

AWS Lambda – Overview ”; Previous Next AWS Lambda is a service which performs serverless computing, which involves computing without any server. The code is executed based on the response of events in AWS services such as adding/removing files in S3 bucket, updating Amazon dynamo dB tables, HTTP request from Amazon API gateway etc. To get working with AWS Lambda, we just have to push the code in AWS Lambda service. All other tasks and resources such as infrastructure, operating system, maintenance of server, code monitoring, logs and security is taken care by AWS. AWS Lambda supports languages such as Java, NodeJS, Python, C#, Go, Ruby, and Powershell. Note thatAWS Lambda will work only with AWS services. What is AWS Lambda? Definition of AWS Lambda as given by its official documentation is as follows − AWS Lambda is a compute service that lets you run code without provisioning or managing servers. AWS Lambda executes your code only when needed and scales automatically, from a few requests per day to thousands per second. You pay only for the compute time you consume – there is no charge when your code is not running. How AWS Lambda Works? The block diagram that explains the working of AWS Lambda in five easy steps is shown below − Step 1 − Upload AWS lambda code in any of languages AWS lambda supports, that is NodeJS, Java, Python, C# and Go. Step 2 − These are few AWS services on which AWS lambda can be triggered. Step 3 − AWS Lambda which has the upload code and the event details on which the trigger has occurred. For example, event from Amazon S3, Amazon API Gateway, Dynamo dB, Amazon SNS, Amazon Kinesis, CloudFront, Amazon SES, CloudTrail, mobile app etc. Step 4 − Executes AWS Lambda Code only when triggered by AWS services under the scenarios such as − User uploads files in S3 bucket http get/post endpoint URL is hit data is added/updated/deleted in dynamo dB tables push notification data streams collection hosting of website email sending mobile app, etc. Step 5 − Remember that AWS charges only when the AWS lambda code executes, and not otherwise. Advantages of using AWS Lambda AWS Lambda offers multiple benefits when you are working on it. This section discusses them in detail − Ease of working with code AWS Lambda gives you the infrastructure to upload your code. It takes care of maintaining the code and triggers the code whenever the required event happens. It allows you to choose the memory and the timeout required for the code. AWS Lambda can also execute parallel requests as per the event triggers. Log Provision AWS Lambda gives the details of number of times a code was executed and time taken for execution, the memory consumed etc. AWS CloudWatch collects all the logs, which helps in understanding the execution flow and in the debugging of the code. Billing based on Usage AWS Lambda billing is done on memory usage, request made and the execution, which is billed in increments of minimum 100ms. So for a 500ms execution, the billing will be after every 100ms. If you specify your AWS lambda code to be executed in 500ms and the time taken to execute is just 200ms, AWS will bill you only for the time taken, that is 200ms of execution instead of 500ms. AWS always charges for the execution time used. You need not pay if the function is not executed. Multi Language Support AWS Lambda supports popular languages such as Node. js, Python, Java, C# and Go. These are widely used languages and any developer will find it easy to write code for AWS Lambda. Ease of code authoring and deploying There are many options available for Lambda for authoring and deploying code. For writing your code, you can use AWS online editor, Visual Studio IDE, or Eclipse IDE. It also has support for serverless framework which makes writing and deploying of AWS Lambda code easy. Besides AWS console, we have AWS-cli to create and deploy code. Other features You can use AWS Lambda for free by getting a login to AWS free tier. It gives you service for free for 1 year. Take a look at the free services offered by AWS free tier. Disadvantages of using AWS Lambda In spite of many advantages, AWS Lambda possesses the following disadvantages − It is not suitable for small projects. You need to carefully analyze your code and decide the memory and timeout. Incase if your function needs more time than what is allocated, it will get terminated as per the timeout specified on it and the code will not be fully executed. Since AWS Lambda relies completely on AWS for the infrastructure, you cannot install anything additional software if your code demands it. Events that Trigger AWS Lambda The events can trigger AWS Lambda are as follows − Entry into a S3 object Insertion, updation and deletion of data in Dynamo DB table Push notifications from SNS GET/POST calls to API Gateway Headers modification at viewer or origin request/response in CloudFront Log entries in AWS Kinesis data stream Log history in CloudTrail Use Cases of AWS Lambda AWS Lambda is a compute service mainly used to run background processes. It can trigger when used with other AWS services. The list of AWS services where we can use AWS Lambda is given below − S3 Object and AWS Lambda Amazon S3 passes the event details to AWS Lambda when there is any file upload in S3. The details of the file upload or deletion of file or moving of file is passed to the AWS Lambda. The code in AWS Lambda can take the necessary step for when it receives the event details. For Example creating thumbnail of the image inserted into S3. DynamoDB and AWS Lambda DynamoDB can trigger AWS Lambda when there is data added, updated and deleted in the table. AWS Lambda event has all the

AWS Lambda – Home

AWS Lambda Tutorial PDF Version Quick Guide Resources Job Search Discussion AWS Lambda is a service which computes the code without any server. It is said to be serverless compute. The code is executed based on the response of events in AWS services such as adding/removing files in S3 bucket, updating Amazon DynamoDB tables, HTTP request from Amazon API Gateway etc. Audience This tutorial is designed for software programmers who want to learn the basics of AWS Lambda and its programming concepts in simple and easy way. This tutorial will give you enough understanding on various functionalities of AWS Services to be used with AWS Lambda with illustrative examples. Prerequisites To work with AWS Lambda, you need a login in AWS. The details on how to get free login is discussed in tutorial. AWS Lambda supports languages like NodeJS, Java, Python, C# and Go. If you are novice to any of these technologies, we suggest you to go through tutorials related to these before proceeding with this tutorial. Print Page Previous Next Advertisements ”;

AWS Lambda – Environment Setup

AWS Lambda – Environment Setup ”; Previous Next Before you start working with AWS Lambda, you need to have a login with Amazon console. AWS Lambda supports two IDEs:Visual studio and Eclipse. In this chapter, we will discuss about the installation of AWS Lambda stepwise in detail. Create login in AWS Console You can create your login in AWS Console for free using Amazon free tier. You can follow these steps given below to create a login with amazon to make use of the Amazon services − Step 1 Go to https://aws.amazon.com/free/ and click on create free account. You can see the screenshot as given below − Step 2 Click on Create a Free Account button and you will be redirected to the screen as shown below − Now, fill in the details of email address, password and AWS account name as per your choice in this form shown above and click Continue. Step 3 Now, you can find the screen as shown below − Enter all the required details in this form. Note that there are minimum charges to be paid based on country selected. The same is refunded once the details entered are validated. You need credit or debit card details to create the free account. For Indian users Rs 2/- is deducted and for US $1 is charged.The same is refunded to the respective card user once the user is validated. Please note the account is free and there is limit to the usage of the services. If the usage exceeds the limit, the user will be charged for it. Once the details are entered in the form shown above click Create Account and Continue. You will be redirected to the next screen as shown below. Step 4 You need to enter the payment details, that is either credit card or debit card, along with its expiry date and the card holder”s name as shown below − Step 5 Once all the details are entered, click Secure Submit and it will validate the card with the bank and will give you the OTP on your mobile which is linked with the card. You can find a window as shown below − Now, enter the OTP details and click Make Payment. You are charged based on the country selected. Step 6 Once the payment is done the next step is phone verification. You need to enter your mobile number as shown below − Once details are filled click Call Me Now. AWS will call immediately using automated system. When prompted on call, enter the 4-digit number that will appear on your AWS site to your phone using your phone keypad. This will verify your number and you will get the mail activation in the mail id specified at the start while creating login. Step 7 Click the mail link and enter the account name or email id and the password and login to you to the AWS services as shown below − The account name is displayed at top right corner as shown above. You can now start using the AWS Lambda service. For AWS Lambda service the languages supported are NodeJS, Python, Java, C# and Go. Installation of Visual Studio 2017 There are 2 IDEs compatible with AWS: Visual Studio and Eclipse. In this section, we will discuss installation ofVisual studio 2017 on Windows, Linux Mac. Go to the official site of Visual Studio : https://www.visualstudio.com/downloads/. You can find the welcome screen as shown − Download the community version ie Visual Studio Community 2017 as its a free now for practice. Once installed, it will run you through the installation steps where you need to select packages to be used later. You can select nodejs, python, c# package for us to work later. AWS Toolkit Support for Visual Studio 2017 Once you have Visual Studio 2017 installed, you will have to follow the given steps for installing AWS Toolkit support for Visual Studio 2017 − Step 1 Go to https://aws.amazon.com/visualstudio/ and download the AWS toolkit for Visual Studio.The display is as shown below − Note that the package downloaded for Visual Studio 2017 is vsix package. If your visual studio version is between 2013-2015, it will install a msi installer. Click the Download button as shown below. Step 2 Now, double click the vsix package downloaded and it will run you through installation steps as shown below − Once Visual Studio is successfully installed, you can see a window, as shown below − Step 3 Now, open Visual Studio 2017 and you should see a welcome page from AWS as shown below − Note that you need to add the access key, secret key, account number to get started and use the AWS services from visual studio.s AWS Lambda BoilerPlate for NodeJS You can use it with visual studio code as shown below. Step 1 You can download Visual studio code for free from the official website:https://www.visualstudio.com/downloads/. The home page of Visual Studio downloads looks like this − Step 2 Now, open Visual Studio code as shown below − Step 3 To install support for AWS, support for nodejs option is available inside extensions. You can search for AWS and it will display the option as follows − Step 4 Now, install the boilerplate for AWS Lambda in nodejs as shown − Step 5 Click the repository and clone it in Visual Studio to start writing the Lambda function in Visual Studio. It redirects you to this repository which we can clone in Visual Studio: https://github.com/loganarnett/vscode-lambda-snippets. Now, open command palette from View option in Visual Studio. Step 6 Click on it and choose git clone as shown below − Step 7 Enter the repository url and save it as per your choice locally. Create index.js file as shown below to work with lambda function − Installation of Eclipse IDE Now, you will have to install latest eclipse Java EE IDE. You can download it from Eclipse official site: https://www.eclipse.org/downloads/ AWS Toolkit Support for

Lambda Function with Custom User Applications

Using Lambda Function with Custom User Applications ”; Previous Next We can use AWS lambda function to process using generated events by user application in the following two ways − Using AWS Console Using AWS CLI Using AWS Console From AWS console, we will work with events and AWS Lambda. For this purpose, go to AWS console and create a lambda function. Next, let us add the code for AWS Lambda − exports.handler = (event, context, callback) => { // TODO implement console.log(“Hello => “+ event.name); console.log(“Address =>”+ event.addr); callback(null, ”Hello ”+event.name +” and address is “+ event.addr); }; Note that in the above code, we are printing name and address using event. The details to the event will be given using the test event created as follows − Now, save the event and test it. The corresponding log output is as shown here − Using AWS CLI We can invoke the above function using AWS CLI as follows − aws lambda invoke –function-name “lambdauserevent” –log-type Tail — payload file://C:clioutputinput.txt C:clioutputoutputfile.txt The event details are given to payload and the output is stored at C:clioutputoutputfile.txt. as follows − input.txt {“name”:”Roy Singh”, “addr”:”Mumbai”} On invoking the Lambda using AWS CLI, you can see the output is as follows − Similarly, in case you want to test AWS Lambda for any other AWS service, you can do so using the test event in AWS console and AWS CLI. A sample event for SNS service is shown below − { “Records”: [{ “EventVersion”: “1.0”, “EventSubscriptionArn”: “arnid”, “EventSource”: “aws:sns”, “Sns”: { “SignatureVersion”: “1”, “Timestamp”: “1970-01-01T00:00:00.000Z”, “Signature”: “EXAMPLE”, “SigningCertUrl”: “EXAMPLE”, “MessageId”: “95df01b4-ee98-5cb9-9903-4c221d41eb5e”, “Message”: “Hello from SNS!”, “MessageAttributes”: { “Test”: { “Type”: “String”, “Value”: “TestString” }, “TestBinary”: { “Type”: “Binary”, “Value”: “TestBinary” } }, “Type”: “Notification”, “UnsubscribeUrl”: “EXAMPLE”, “TopicArn”: “topicarn”, “Subject”: “TestInvoke” } }] } Let us add the sample event shown above and test it as shown − In AWS Lambda, code will print the SNS message as shown in the example given below − exports.handler = (event, context, callback) => { // TODO implement console.log(event.Records[0].Sns.Message); callback(null, event.Records[0].Sns.Message);}; Let us invoke the same using AWS CLI. Let us save the event in a file and use that for payload using the command shown − aws lambda invoke –function-name “lambdauserevent” –log-type Tail — payload file://C:clioutputsns.txt C:clioutputsnsoutput.txt Print Page Previous Next Advertisements ”;

Monitoring and TroubleShooting using Cloudwatch

Monitoring and TroubleShooting using Cloudwatch ”; Previous Next Functions created in AWS Lambda are monitored by Amazon CloudWatch. It helps in logging all the requests made to the Lambda function when it is triggered. Consider that the following code is uploaded in AWS Lambda with function name as lambda and cloudwatch. exports.handler = (event, context, callback) => { // TODO implement console.log(“Lambda monitoring using amazon cloudwatch”); callback(null, ”Hello from Lambda”); }; When the function is tested or triggered, you should see an entry in Cloudwatch. For this purpose, go to AWS services and click CloudWatch. Select logs from left side. When you click Logs, it has the Log Groups of AWS Lambda function created in your account. Select anyAWS Lambda function and check the details. Here, we are referring to Lambda function with name:lambdaandcloudwatch. The logs added to the Lambda function are displayed here as shown below − Now, let us add S3 trigger to the Lambda function and see the logs details in CloudWatch as shown below − Let us update AWS Lambda code to display the file uploaded and bucket name as shown in the code given below − exports.handler = (event, context, callback) => { // TODO implement console.log(“Lambda monitoring using amazon cloudwatch”); const bucket = event.Records[0].s3.bucket.name; const filename = event.Records[0].s3.object.key; const message = `File is uploaded in – ${bucket} -> ${filename}`; console.log(message); callback(null, ”Hello from Lambda”); }; Now, add file in s3storetestlambdaEventbucket as shown − When the file is uploaded, AWS Lambda functions will get triggered and the console log messages from Lambda code are displayed in CloudWatch as shown below − If there is any error, CloudWatch gives the error details as shown below − Note that we have referred to the bucket name wrongly in AWS Lambda code as shown − exports.handler = (event, context, callback) => { // TODO implement console.log(“Lambda monitoring using amazon cloudwatch”); const bucket = event.Records[0].bucket.name; const filename = event.Records[0].s3.object.key; const message = `File is uploaded in – ${bucket} -> ${filename}`; console.log(message); callback(null, ”Hello from Lambda”); }; The bucket name reference from the event is wrong. Thus, we should see an error displayed in CloudWatch as shown below − CloudWatch Metrics The details of the Lambda function execution can be seen in the metrics. Click Metrics displayed in the left side. The graph details for the lambda function lambdaandcloudwatch are as shown below − It gives details such as the duration for which the Lambda function is executed, number of times it is invoked and the errors from the Lambda function. Print Page Previous Next Advertisements ”;