Creating & Deploying using AWS CLI

Creating and Deploying using AWS CLI ”; Previous Next AWS CLI is a command line tool which helps to work with AWS services. We can use it to create, update, delete, invoke aws lambda function. In this chapter, you will discuss about installation and usage of AWS CLI in detail. Installation of AWS CLI This section will guide you through the installation of AWS CLI on various operating systems. Follow the steps given and observe corresponding screenshots wherever attached. For Windows Check your Windows configuration and choose one of the following links for installing AWS CLI MSI − For Windows 64 bit − AWS CLI MSI install for windows (64bit) For Windows 32 bit − AWS CLI MSI install for windows (32) Once you choose corresponding link and click it, you can find a Window as shown here − Next, set the Environment path in windows as shown in the screenshots below − Once done, you can use the following command on the command prompt, to see if aws cli is installed − aws –version It displays the details of aws-cli version as shown in the following screenshot − For Linux / Mac For installing on Linux and Mac, you need Python 2.6.3 or higher verison of it. Then, use following commands for further installation processes − $ curl “https://s3.amazonaws.com/aws-cli/awscli-bundle.zip” -o “awscli-bundle.zip” $ unzip awscli-bundle.zip $ sudo ./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws Now, we need to configure AWS settings. You can use the following command for this purpose − aws configure For this purpose, it requires details such as − AWS Access Key ID AWS Secret Access Key Default region name Default output from format You can obtain these details from your aws console. Go to you Account name at top right corner as shown − Now, click My Security Credentials and select users from left side. Add user with details as asked. Add the user and to get the access key and secret key. To see the new access key, choose Show. Your credentials will look like as shown below − Access key ID − AOSAIOSFOCDD7Example Secret access key − aJuirCVtnROUN/K7MDENG/bPxRfiCYExampleKEY Reference Commands for AWS CLIS The following table will give command references available to work with aws cli. Name of aws cli command Command reference create-function create-function –function-name <value> –runtime <value> –role <value> –handler <value> [–code <value>] [–description <value>] [–timeout <value>] [–memory-size <value>] [–environment <value>] [–kms-key-arn <value>] [–tags <value>] [–zip-file <value>] [–cli-input-json <value>] list-functions list-functions [–master-region <value>] [–function-version <value>] [–max-items <value>] [–cli-input-json <value>] [–starting-token <value>] [–page-size <value>] [–generate-cli-skeleton <value>] get-function get-function –function-name <value> [–qualifier <value>] [–cli-input-json <value>] [–generate-cli-skeleton <value>] get-function-configuration get-function-configuration –function-name <value> [–qualifier <value>] [–cli-input-json <value>] [–generate-cli-skeleton <value>] get-account-settings get-account-settings [–cli-input-json <value>] [–generate-cli-skeleton <value>] update-function-configuration update-function-configuration –function-name <value> [–role <value>] [–handler <value>] [–description <value>] [–timeout <value>] [–memory-size <value>] [–vpc-config <value>] [–environment <value>] [–runtime <value>] [–dead-letter-config <value>] [–kms-key-arn <value>] [–tracing-config <value>] [–revision-id <value>] [–cli-input-json <value>] [–generate-cli-skeleton <value>] update-function-code update-function-code –function-name <value> [–zip-file <value>] [–s3-bucket<value>] [–s3-key <value>] [–s3-object-version <value>] [–publish | –no-publish] [–dry-run | –no-dry-run] [–revision-id <value>][–cli-input-json <value>][–generate-cli-skeleton <value>] delete-function delete-function –function-name <value> [–qualifier <value>] [–cli-input-json <value>] [–generate-cli-skeleton <value>] Now, let us discuss these commands one by one in detail. create-function This api will create a new lambda function. The code needs to be given in zip format. If the function to be created already exists, the api will fail. Note that the function name is case-sensitive. Commands Included The list of commands that you can use with create-function is given here − create-function –function-name <value> –runtime <value> –role <value> –handler <value> [–code <value>] [–description <value>] [–timeout <value>] [–memory-size <value>] [–environment <value>] [–kms-key-arn <value>] [–tags <value>] [–zip-file <value>] [–cli-input-json <value>] Options Included Various options that you can use with the functions above are as follows − –function-name (string) − This takes the name of the function. The name can be 64-bit characters. –runtime(string) − Here you need to specify the runtime environment ie the language selection. The details of the runtime are as given below − Options available runtime Python v3.6 python3.6 Python v2.7 python2.7 NodeJS v6.10 nodejs6.10 NodeJS v8.10 nodejs8.10 Java java8 C# 1 dotnetcore1.0 C# 2 dotnetcore2.0 Go go1.x –role(string) − This will be the name of the lambda policy ie the role to be given to the lambda function for accessing other services. It will have the permission as per the role specified. –handler (string) − This is the name of the handler where the lambda code execution will start. For nodejs, handler name is the module name that we export. For java, it is package.classname :: handler or package.classname For python, handler is nameofthefile. –code (structure) −AWS Lambda code –description (string) − description for the AWS Lambda function –timeout (integer) − timeout will have the time at which the lambda function has to terminate execution. The default is 3s. –memory-size (integer) − This is the memory given to the aws lambda function. AWS will allocate the amount of CPU and memory allocation based on the memory given. –environment (structure) − its a object with environment details required in the aws lambda function. e.g : Variables = {Name1 = string, Name2 = string} –kms-key-arn (string) − this is amazon resource name (ARN) used to encrypt the environment variables. If not provided it will take the default settings to encrypt. –zip-file (blob) − path of the zip file which has the details of the code. –cli-input-json (string) : Performs service operation based on the JSON string provided. The JSON string follows the format provided by –generate-cli-skeleton. If other arguments are provided on the command line, the CLI values will override the JSON-provided values. Now, let us create a simple AWS Lambda function using runtime as nodejsand add some console.logs to be printed. Consider a sample code for understanding the same − exports.handler = async (event) => { console.log(“Using aws cli”); return ”Hello from Lambda from aws cli!” }; Now, zip the file and store it as awscli.zip. Getting ARN For the role, let us use the arn from the existing role we have

Lambda Function with Amazon SNS

Using Lambda Function with Amazon SNS ”; Previous Next Amazon SNS is a service used for push notification. In this chapter, we will explain working of AWS Lambda and Amazon SNS with the help of an example where will perform the following actions − Create Topic in SNS Service and use AWS Lambda Add Topics to CloudWatch Send SNS text message on phone number given. Requisites To create Topic in SNS Service and use AWS Lambda Add Topics to CloudWatch, we need not follow the steps given below − Create Topic in SNS Create Role for permission in IAM Create AWS Lambda Function Publish to topic to activate trigger Check the message details in CloudWatch service. To send SNS text message on phone number given, we need to do the following − Add code in AWS Lambda to send message to your phone. Example In this example, we will create a topic in SNS. When details are entered in the topic to publish, AWS Lambda is triggered. The topic details are logged in CloudWatch and a message is sent on phone by AWS Lambda. Here is a basic block diagram which explains the same − Create Topic in SNS You will have to follow the steps given below to create topic in SNS − Step 1 Login to AWS Console and go to SNS service in Amazon as shown below − Step 2 Click Simple Notification Service and Create topic in it. Step 3 Then, you have to click Create new topic button as shown − Step 4 Enter the Topic name and Display name and click on Create topic. You should see the topic name in the display as follows − Create Role for Permission in IAM To create a Role to work with AWS Lambda and SNS service, we need to login to AWS console. Then, select IAM from Amazon services and click role from left side as shown below. Observe that we have added policies for SNS, Lambda and CloudWatch. Add rolename and click Create role button to complete the process of role creation. Create AWS Lambda Function In this section, let us understand how to create AWS Lambda function using nodejs as the runtime. For this purpose, login to AWS console and choose AWS Lambda from AWS services. Add the function name, role details etc and create the AWS Lambda function as shown. Add SNS Trigger To add SNS trigger, enter SNS configuration details as shown − Then, select SNS topic and Add the trigger to AWS Lambda function as shown − Then, add AWS lambda code given below − exports.handler = function(event, context, callback) { console.log(“AWS lambda and SNS trigger “); console.log(event); const sns = event.Records[0].Sns.Message; console.log(sns) callback(null, sns); }; In the above code, event.Records[0].Sns.Message gives the message details added. We have added console logs to see them in CloudWatch. Now, save the Lambda function with required memory and time allocation. Publish to Topic to Activate Trigger Recall that we have already created topic in SNS in Step 1. We will now publish in the topic and see the details in CloudWatch which will be triggered by AWS Lambda − Publish to Topic First Select name of the topic you want to publish. Click on Publish to topic button − Enter the Subject and Message details as shown below − You can also select JSON message format to send in JSON style. Click Publish the message button at the end of the screen. Check Message Details in CloudWatch Service Log intoAWS console and open CloudWatch service. Click on logs on left side and select the logs for AWS Lambda function created. You can find the following display for the logs with messages created as shown above − Add Code in AWS Lambda to Send Message to your Phone Here will use SNS Text messaging to send message on the phone using AWS Lambda. You can use the following code to update AWS Lambda code as follows − const aws = require(“aws-sdk”); const sns = new aws.SNS({ region:”us-east-1” }); exports.handler = function(event, context, callback) { console.log(“AWS lambda and SNS trigger “); console.log(event); const snsmessage = event.Records[0].Sns.Message; console.log(snsmessage); sns.publish({ Message: snsmessage, PhoneNumber: ”+911212121212” }, function (err, data) { if (err) { console.log(err); callback(err, null); } else { console.log(data); callback(null, data); } }); }; We have added AWS SDK and the SNS service to use to send message. The message from the event coming from SNS is send as text message on the phone number given. Observe the following code for example − sns.publish({ Message: snsmessage, PhoneNumber: ”+911212121212” }, function (err, data) { if (err) { console.log(err); callback(err, null); } else { console.log(data); callback(null, data); } }); Enter the topic now to see the message in cloudwatch and the phone number given above. Click Publish message to publish the message. You see a message on the phone number given as follows − Print Page Previous Next Advertisements ”;

Creating & Deploying using Serverless Framework

Creating and Deploying using Serverless Framework ”; Previous Next AWS Lambda can be created and deployed using serverless framework. It allows you to create AWS Lambda triggers and also deploy the same by creating the required roles. Serverless framework allows to handle big projects in an easier way. The events and resources required are written in one place and just a few commands helps in deploying the full functionality on AWS console. In this chapter, you will learn in detail how to get started with AWS serverless framework. Install Serverless Framework using npm install To begin with, you need to first install nodejs. You can check for nodejs as follows − You will have to use the following command to install serverless using npm package − npm install -g serverless Once npm is done, execute serverless command which shows the list of command to be used to create and deploy AWS Lambda function. Observe the screenshots given below − You can also use sls instead of serverless. sls is the shorthand command for serverless. In case you need help on the command sls, you can use the following command − sls create –help For creating a serverless framework, you have to follow the steps given below − Step 1 To start using serverless framework, we need to add the credentials. By this, you can the user first in AWS console as follows − Step 2 Click on Next:Permissions button to add permissions. You will have to attach the existing policies or Administrator Access to this user. Step 3 Click Create User to add the user. It will display the access key and secret key which we need to configure the serverless framework − Configure AWS Serverless Framework Let us see how to configure AWS serverless framework. You can use the following command for this purpose − sls config credentials –provider aws –key accesskey –secret secretkey Note that the details of credentials entered, that is the access key and secret key are stored in the file /aws/credentials. First, create a folder where you want your project files to be stored. Next, we will start the work in aws-serverless folder. Create AWS Lambda using Serverless Framework Now, let us create a Lambda function with the serverless framework using the Steps given below − Step 1 Following are the details for serverless create command − Step 2 Now, we need to assign the template which are as follows − AWS-nodejs, aws-nodejs-typescript, aws-nodejs-ecma-script, aws-python, aws-python3, aws-groovy-gradle etc. Step 3 We shall make use of aws-nodejs template to create our first project using serverless framework. The command for the same purpose is as shown here − sls create –template aws-nodejs Note that this command creates a boilerplate for template aws-nodejs. Step 4 Now, open the folder created in an IDE. Here we are using Visual Studio code and the folder structure is as follows − Step 5 There are 2 files created: handler.js and Serverless.yml The AWS Lambda basic function details are shown in handler.js as follows − ”use strict”; module.exports.hello = (event, context, callback) => { const response = { statusCode: 200, body: JSON.stringify({ message: ”Go Serverless v1.0! Your function executed successfully!”, input: event, }), }; callback(null, response); // Use this code if you don”t use the http event with the LAMBDA-PROXY integration // callback(null, { message: ”Go Serverless v1.0! Your function executed successfully!”, event }); }; This file Serverless.yml has the configuration details of the serverless framework as shown below − # 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-nodejs # NOTE: update this with your service 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: nodejs6.10 # 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: hello: handler: handler.hello # 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 # – 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: # Example: # – “aws.ec2” # detail-type: # – “EC2 Instance State-change Notification” # detail: # state: # – pending # – cloudwatchLog: ”/aws/lambda/hello” # – cognitoUserPool: # pool: MyUserPool # trigger: PreSignUp # 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” Now, we need to add changes in serverless.yml file as per our requirements. You can use the commands as given below −

Function in NODEJS

AWS Lambda – Function in NODEJS ”; Previous Next Nodejs is one of the languages that AWS Lambda function supports. The version supported with nodejs are v6.10 and v8.10. In this chapter, we will learn about various functionalities of AWS Lambda function in NODEJS in detail. Handler in NodeJS To writeAWS Lambda function in nodejs, we should first declare a handler first. The handler in nodejs is name of the file and the name of the export function. For Example, the name of the file is index.js and the export function name is lambda handler, so its corresponding handler is index.lambdahandler Observe a sample handler shown here − exports.lambdahandler = function(event, context, callback) { //code goes here} Params to Handler Handler is the main core for building Lambda function. The handler takes three params: event, context and callback. Event Parameter It has all the details of the event triggered. For Example, if we are using Lambda function to be triggered on S3, the event will have details of the S3 object. Context Parameter It has the details of the context such as the properties and configuration details of the Lambda function. Callback Function It helps in giving details back to the caller. The structure of callback looks as follows − callback(error, result); The parameters of callback function are explained given below − Error − This will have details if any error has occurred during the execution of Lambda function. If the Lambda function succeeds,null can be passed as the first param for callback function. Result − This will give the details of the successful execution of the lambda function. If an error occurs, the result param is ignored. Note − It is not mandatory to use the callback function in AWS Lambda. Incase if there is no callback function, the handler will return it as null. The valid callback signatures are given below − callback(); // It will return success, but no indication to the caller callback(null); // It will return success, but no indication to the caller callback(null, “success”); // It will return the success indication to the caller callback(error); // It will return the error indication to the caller Whenever AWS Lambda gets executed the callback details such as error or success, are logged in AWS CloudWatch along with console messages, if any. Working with AWS Lambda in Nodejs8.10 Let us understand how to work with AWS Lambda in nodejs8.10 and invoke the function in sync and async way. Invoking Lambda Function in Sync Way The following example gives you an idea about invoking Lambda function in sync way − exports.handler = function(event, context, callback) { let arrItems = [4,5,6,8,9,10,35,70,80,31]; function countevennumbers (items) { return new Promise(resolve => { setTimeout(() => { let a = 0; for (var i in items) { if (items[i] % 2 == 0) { a++; } } resolve(a); },2000); }); } let evennumber = countevennumbers(arrItems); callback(null,”even numbers equals =”+evennumber); }; You can observe the following output after testing this code in AWS console − Note that the output from the above code is a promise object. It does not give the count, as the count is incremented inside a setTimeout and the function call does not wait for the execution inside setTimeout and returns the promise object. If we had async/await on the handler function will get exact output of from the lambda function. Invoking the Handler in an Async Way The following example gives you an idea about invoking Lambda function in an async way − exports.handler = async function(event, context, callback) { let arrItems = [4,5,6,8,9,10,35,70,80,31]; function countevennumbers (items) { return new Promise(resolve => { setTimeout(() => { let a = 0; for (var i in items) { if (items[i] % 2 == 0) { a++; } } resolve(a); }, 2000); }); } let evennumber = await countevennumbers(arrItems); callback(null,”even numbers equals =”+evennumber); }; We have added async and await in above code. When we use await beside the function call, the execution pauses till the promise inside the function gets resolved. Note that await is valid only for async functions. You can observe the following output after testing this code in AWS console − ContextDetails in NodeJS Context object gives details such as the name of the Lambda function, time remaining in milliseconds, request id, cloudwatch group name, timeout details etc. The following tables shows the list of methods and attributes available with context object − Method available for context object Sr.No Method Name & Description 1 getRemainingTimeInMillis() This method gives the remaining time in milliseconds until the Lambda function terminates the function Attributes available for context object Sr.No Attribute name & Description 1 functionName This gives AWS Lambda function name 2 functionVersion This gives the version of AWS Lambda function executing 3 nvokedFunctionArn This will gives ARN details. 4 memoryLimitInMB This shows the memory limit added while creating Lambda function 5 awsRequestId This gives the AWS request id. 6 logGroupName This will give the name of the cloudwatch group name 7 logStreamName 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 clientContext 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 environment details from the AWS Mobile SDK Look at the following example to get a better idea about context object − exports.handler = (event, context, callback) => { // TODO implement console.log(”Remaining time =>”, context.getRemainingTimeInMillis()); console.log(”functionName =>”, context.functionName); console.log(”AWSrequestID =>”, context.awsRequestId); console.log(”logGroupName =>”, context.log_group_name); console.log(”logStreamName =>”, context.log_stream_name); console.log(”clientContext =>”, context.clientContext); callback(null, ”Name of aws Lambda is=>”+context.functionName); }; You can observe the following output after testing this code in AWS console − You can observe the following log output after

AWS Executing & Invoking Lambda Function

Executing and Invoking Lambda Function ”; Previous Next This chapter will explain in detail about process of executing and invoking Lambda function and the steps involved in it. AWS Lambda Execution Model AWS execution depends on the configuration details added for AWS Lambda Function. When the function is created, there is a memory and time allotted, which is used for the execution of AWS Lambda function. With the help of the configuration details, AWS Lambda creates an execution context. Execution context is a temporary runtime environment which is made ready with any external dependencies such as database connection, http endpoints, third party libraries etc., if any. When AWS Lambda function is invoked for the very first time or if the lambda function is updated, there is little latency added because of the execution context setup. However, the subsequent calls are faster in comparison to the first one. AWS Lambda tries to reuse the execution context again if the Lambda function is invoked taking lesser time. The reuse of execution context has the following implications − If there is any database connection done for the execution of Lambda, the connection is maintained for reuse. So the Lambda code has to be such that the connection has to be checked first- if exists and reused; otherwise we shall have to make fresh new connection. Execution context maintains a disk space of 500MB in /tmp directory. The data required is cached in this directory. You can have additional check in the code to see if the data exists. If the callbacks or some background processes if the are not complete when the Lambda function was invoked, the execution will start when the lambda function is invoked again. Incase you do not need such thing to happen make sure your processes are all ended properly, when the function execution is complete. You should use of the execution context and the data stored in tmp directory. You will have to add necessary checks in the code to see if the required data exists before creating fresh new ones. This will save the time during execution and make it more faster. Invoking AWS Lambda function We can invoke AWS manually using aws cli. We have already seen how to create and deploy AWS Lambda using cli. Here, we will first create a function using aws cli and invoke the same. Creating AWS Lambda Function using AWS CLI You can use the following commands for creating AWS Lambda function using aws cli − Commands create-function –function-name <value> –runtime <value> –role <value> –handler <value> [–code <value>] [–description <value>] [–timeout <value>] [–memory-size <value>] [–environment <value>] [–kms-key-arn <value>] [–tags <value>] [–zip-file <value>] [–cli-input-json <value>] Command with values aws lambda create-function –function-name “lambdainvoke” –runtime “nodejs8.10” –role “arn:aws:iam::625297745038:role/lambdaapipolicy” –handler “index.handler” –timeout 5 –memory-size 256 –zip-file “fileb://C:nodeprojectindex.zip” The output is as shown below − The function created in AWS console is as shown below − Now, you can invoke the function using the command:invoke –function-name <value> [–invocation-type <value>] [–log-type <value>] [–client-context <value>] [–payload <value>] [–qualifier <value>] outfile <value> Options –function-name − Specify the name of the function you want to invoke. –invocation-type(string) − by default the invokation-type is requestresponse. The values available to be used with invokation-type is RequestResponse, Event and DryRun. Event invocation-type is to be used for async response. DryRun is to be used when you want to verify the Lambda function without need of executing it. –log-type − It will be Tail if the invocation type is RequestResponse. It gives the last 4KB base64-encoded log data. Possible values are Tail and None. –client-context − You can pass client specific details to the Lambda function. The clientcontext has to be in json format and base64-encoded. Maximum file size is 3583 bytes. –payload − json format input to you lambda function. –qualifier − You can specify Lambda function version or alias name. If you pass the function version than the api will use qualified function arn to invoke the Lambda function. If you specify alias name, the api uses alias ARN to invoke Lambda function. outfile − This is the filename where the content will be saved. Command with values aws lambda invoke –function-name “lambdainvoke” –log-type Tail C:nodeprojectoutputfile.txt You can use payload option to send dummy event to the lambda function in json format as shown below. The related AWS Lambda code is as follows − exports.handler = async (event, callback) => { console.log(“Hello => “+ event.name); console.log(“Address =>”+ event.addr); callback(null, ”Hello ”+event.name +” and address is “+ event.addr); }; Observe that in the code, we have console event.name and event.addr. Now, let us use payload option in aws cli to send the event with name and address as follows − aws lambda invoke –function-name “lambdainvoke” –log-type Tail –payload file://C:clioutputinput.txt C:clioutputoutputfile.txt Thenpayload takes input as a filepath which has json input as shown − {“name”:”Roy Singh”, “addr”:”Mumbai”} The corresponding output is as shown below − The output is stored in the file C:clioutputoutputfile.txt as follows − “Hello Roy Singh and address is Mumbai” Sample Events You can test AWS Lambda function by passing a sample event. This section gives some sample events for AWS Services. You can use the invoke command to test the output when triggered with any of the services. Observe the codes given for corresponding sample events below − Amazon S3 Put Sample Event { “Records”: [{ “eventVersion”: “2.0”, “eventTime”: “1970-01-01T00:00:00.000Z”, “requestParameters”: { “SourceIPAddress”: “127.0.0.1” }, “s3”: { “configurationId”: “testConfigRule”, “object”: { “eTag”: “0123456789abcdef0123456789abcdef”, “sequencer”: “0A1B2C3D4E5F678901”, “key”: “HappyFace.jpg”, “size”: 1024 }, “bucket”: { “arn”: bucketarn, “name”: “Sourcebucket”, “ownerIdentity”: { “principalId”: “EXAMPLE” } }, “s3SchemaVersion”: “1.0” }, “responseElements”: { “x-amz-id-2”: “EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH”, “x-amz-request-id”: “EXAMPLE123456789” }, “awsRegion”: “us-east-1”, “eventName”: “ObjectCreated:Put”, “userIdentity”: { “principalId”: “EXAMPLE” }, “eventSource”: “aws:s3” }] } To get the details of the file from the s3 put event, you can use the following command − event.Records[0].s3.object.key //will display the name of the file To get the bucket name, you can use the following command − event.Records[0].s3.bucket.name //will give the name of the bucket. To see

Deleting Lambda Function

Deleting Lambda Function ”; Previous Next Deleting AWS Lambda function will remove the AWS Lambda from the AWS console. There are 2 ways to delete AWS Lambda function. Using AWS console. Using AWS CLI command This chapter discusses these two ways in detail. Using AWS Console For deleting a Lambda function using AWS console, follow the steps given below − Step 1 Login to AWS console and go to AWS Lambda service. You can find that AWS lambda functions created so far are listed in AWS console as shown below − The list shows that there are 23 AWS Lambda functions created so far. You can view them using the pagination provided on the top or search the AWS Lambda by using the search box. Step 2 Observe that there is a radio button across each of the AWS Lambda function. Select the function you want to delete. Observe the screenshot shown below − Step 3 Once you select the AWS Lambda function, the Action dropdown which was earlier grayed out is highlighted now. Now, open the combo box and it will display options as shown − Step 4 Select the Delete button to delete the AWS Lambda function. Once you click Delete, it displays the message as follows − Step 5 Read the message carefully and later click Delete button to remove the AWS lambda function permanently. Note − Deleting aws lambda will not delete the role linked. To remove the role, you need to go to IAM and remove the role. Step 6 The list of roles created so far is shown below. Observe that there is a Create role button and Delete role button. Click the checkbox across the role you want to delete. You can also select multiple roles to delete at a time. Step 7 You will see a confirmation message as shown below once you click Delete button − Now, read the details mentioned carefully and later click Yes, delete button. Using AWS CLI command Let us first create a Lambda function using aws cli and delete the same using the same command. Follow the Steps given below for this purpose − Step 1 The command with values for create-function is as follows − aws lambda create-function –function-name “lambdatestcli” –runtime “nodejs8.10” –role “arn:aws:iam::625297745038:role/lambdaapipolicy” –handler “index.handler” –timeout 5 –memory-size 256 –zip-file “fileb://C:demotestindex.zip” The corresponding output is shown here − Step 2 The AWS Lambda function created is lambdatestcli. We have used existing role arn to create the lambda function. Then you can find this function displayed in AWS console as shown below − Step 3 Now, let us invoke the function to test the output using the command shown − aws lambda invoke –function-name “lambdatestcli” –log-type Tail C:demotestoutputfile.txt This command will give you the output as shown − Step 4 You can observe logs from cloudwatch for lambda function lambdatestcli Step 5 Now, let us come to the actual part of deleting the AWS function. Delete aws cli api will delete the function given. The details of command used for this purpose is given below − Command delete-function –function-name <value> [–qualifier <value>] [–cli-input-json <value>] [–generate-cli-skeleton <value>] Options –function-name(string) − This will take the Lambda function name or the arn of the AWS Lambda function. –qualifier (string) − This is optional. Here you can specify the version of AWS Lambda that needs to be deleted. — cli-input-json(string) − Performs service operation based on the JSON string provided. The JSON string follows the format provided by –generate-cli-skeleton. If other arguments are provided on the command line, the CLI values will override the JSON-provided values. –generate-cli-skeleton(string) − it prints json skeleton to standard output without sending the API request. Command with values aws lambda delete-function –function-name “lambdatestcli” The corresponding output is shown below − Step 6 If you check now, you can observe that the function will not be seen in AWS Lambda function list as shown in the screenshot given below − Print Page Previous Next Advertisements ”;

Working with Amazon API Gateway

Working with Amazon API Gateway ”; Previous Next AWS Lambda function can be invoked on HTTPS url. It can be done on GET, POST, PUT. When the HTTPS url is invoked, the AWS Lambda function can also triggered and the data passed to HTTPS using get/post can be made available inside AWS Lambda to be used to insert in DynamoDB or to send mail etc. This chapter discusses in detail about various processes involved in work in with AWS lambda and API Gateway. Processes involved The following are the processes involved in working with AWS lambda and API Gateway − Create IAM role for permission Create AWS lambda function Create API Gateway Link lambda function to api gateway Passing data to api gateway A basic diagram that explains the working of API gateway and AWS Lambda is given here − These processes are explained in detail further in this chapter with relevant screenshots. Create IAM role for permission From Amazon services as shown below, select IAM for creating roles to be used by Lambda function. Go to IAM and select Roles from left side section as shown below − Click Create role for Lambda function. Select Lambda and click Permissions at the bottom. Select the permission required for the API Gateway and Lambda. Search for API gateway in the search and it will list you all the related permissions. Here we have chosen full access to API gateway as shown below − Now, search for API gateway and it will list you all the related permissions. Here we have chosen full access to API gateway as shown below − You have to repeat the same process for Policies also. Once you are done choosing the necessary policies, click Review for the next step. Enter the name of the role as per your choice as shown below − It displays the policies attached to the role. Click Create role and we are done with the role creation and can proceed with the lambda function. Create AWS Lambda Function Go to AWS services and click on lambda service to create a function for connecting it with api gateway. The UI screen for Lambda function is shown below. Click Create function button to proceed with creation of Lambda function. Enter the name of the function and choose the existing role which we have created above. It flashes a message that the function with the name lambdawithapigateway is created successfully. Note that here we will use nodejs runtime to write the code. The AWS code with helloworld message is as shown below − AWS Lambda code is present in index.js file. The function called handler has the params namely events, context and callback. Callback function basically has the error and the success message. Note that here we do not have any error related code, so null is passed and the success message is HelloWorld from lambda. Lastly, save the changes added and let us proceed to add the Lambda function to the API gateway. Create API Gateway Login to your AWS account and open API Gateway as shown below − Click API Gateway and it will lead you to the screen where new API gateway can be created. Click Create API and add details as shown below − Click the Create API button on right side of the screen. This will display the newly created API on to left side of the screen. Click the Actions dropdown to create a new resource for the API. Now, create a new resource as shown below − Enter the Resource Name as shown below. You will see the name of the resource entered in the url created at the end. Click Create Resource and you will see it on the screen as follows − Add GET/POST methods to the resource created as shown below. Select the method from Actions dropdown. Click the GET method to add the method to the API. Next step is the integration which will integrate it with Lambda function. Now add the Lambda function to it as shown below − Link Lambda Function to API Gateway Select the lambda function created earlier. Save the changes and you can see a dialog box asking for permission as shown below − Click OK for the permission. This is the execution details between the API gateway HTTP request and the Lambda function − Now, let us deploy the API gateway changes. For this purpose, we need to select the Deploy API from Actions dropdown as shown below − Select Deploy API. It will ask for the deployment state. Select New Stage from Deployment stage dropdown and add the stage name as Production. Click Deploy button and it will redirect you to the url as shown below − Select the GET method from left side to get the url. Open the url in a new tab to see the message from Lambda function. This is a basic example of working with AWS Lambda and AWS API Gateway. In the above example, we have hardcoded the message in Lambda function. Now, let us take the message details from the API Gateway. Incase if the HTTPS call has to be called from a different domain, for example AJAX call to the API, we need to enable CORS for the API gateway created. Select the reSource created for the API and click Actions dropdown − Now, Enable CORS will open up the following screen − You can use few methods to ENABLE CORS. Access-Control-Allow-Origin is marked as * which means it will allow to get contents from API gateway from any domain. You can also specify the domain name you want to work with the API. Click Enable CORS and replace existing CORS headers button and it will display confirmation message as shown below − Click Yes, replace existing values button to enable it. The Enable CORS screen looks as shown below − Passing Data to API Gateway Open the API created in API Gateway displayhelloworld

Configuring Lambda Function

AWS Lambda – Configuring Lambda Function ”; Previous Next In the previous chapters, we have learnt how to create AWS Lambda function in AWS console. However, there are other parameters for creating a Lambda function. These include memory allocation, timeout etc. In this chapter, let us understand in detail about the following configuration properties for AWS Lambda. Memory Allocation Login to AWS console and create or select the existing lambda function. Click the Configuration tab to get the details of the memory allocated. Look at the screenshot shown below − Note that by default the memory allocated is 128MB. If you want to increase the memory you can click the slider. The memory will get incremented to 64MB as you move the slider. Observe that the maximum memory available is 3008MB. Look at the screenshot shown below − You can also use aws cli from command prompt to increase the memory limit. You will have to give the memory in increments of 64MB. Now, let us increase the memory limit of AWS Lambda with name :myfirstlambdafunction. The memory details of the function are shown in the screenshot given below − The command used to change the memory using aws cli is as follows − aws lambda update-function-configuration –function-name your function name — region region where your function resides –memory-size memory amount — profile admin user The corresponding output of AWS Lambda function myfirstlambdafunction in AWS console is shown here. Observe that the memory is changed from 128MB to 256MB. Maximum Execution Time Timeout is the time allotted to AWS Lambda function to terminate if the timeout happens. AWS Lambda function will either run within the allocated time or terminate if it exceeds the timeout given. You need to evaluate the time required for the function to execute and accordingly select the time in Configuration tab in AWS console as shown below − IAM Role When creating AWS Lambda function, the role or the permission needs to be assigned. Incase you need AWS Lambda for S3 or dynamoDB, permission with regard to the services of lambda needs to be assigned. Based on the role assigned, AWS Lambda will decide the steps to be taken. For Example if you give full access of dynamodb, you can add, update and delete the rows from the dynamodb table. Handler Name This is the start of execution of the AWS Lambda function. Handler function has the details of the event triggered, context object and the callback which has to send back on success or error of AWS Lambda. The format of the handler function in nodejs is shown here − exports.handler = (event, context, callback) => { callback(null, “hello from lambda”); }; Lambda Function using Environment Variables In this section, we will create a simple Lambda function using environment variables added in the configuration section. For this purpose, follow the steps given below and refer the respective screenshots − Step 1 Go to AWS console and create a function in Lambda as shown. Step 2 Now, add the environment variables as shown − Step 3 Now, let us fetch the same in Lambda code as follows − exports.handler = (event, context, callback) => { var hostName = process.env.host; var userName = process.env.username; callback(null, “Environment Variables =>”+hostName+” and “+userName); }; Step 4 To get the details from environment variables we need to use process.env as shown. Note that this syntax is for NodeJS runtime. var hostName = process.env.host; var userName = process.env.username; Step 5 The output for the Lambda function on execution will be as shown − Print Page Previous Next Advertisements ”;

Function in Go

AWS Lambda – Function in Go ”; Previous Next Go Language support is a recent addition to AWS. To work with Go, you need to select the language from AWS console while creating the AWS Lambda function. In this chapter, let us learn in detail about AWS Lambda function in Go language. Installing Go To get started we need Go Language support. In this section, we will go through following details to start working with AWS Lambda in Go. This is the official site for Go download: https://golang.org/dl/ Now, download the package as per the operating system. Follow the procedure given here to install Go on the respective operating system. Installation on Windows Observe that for Windows, there is 32-bit and 64-bit download available. Download the zip file and extract the contents and store it in a directory of your choice. Add the environment variables available at ControlPanel —> System —> Advanced system settings. Now, click Environment Variables button and add the directory path as shown here − You can also edit the system variable as shown here − Once these steps are done, you should be able to start working with Go. Open command prompt and check the Go command for version. Observe the following screenshot for the same. Installation for Linux and Mac OS For installing packages on Linux and Mac OS, follow the instruction as shown below − Unpack the packages and store it at the location /usr/local/go. Now, add /usr/local/go/bin to the PATH environment variable. It can be done using /etc/profile or $HOME/.profile. For this purpose, you can use the following command export PATH=$PATH:/usr/local/go/bin To add AWS support to for Windows, Linux and mac, use the following in your git command line − go.exe get -u github.com/aws/aws-lambda-go/lambda go.exe get -u github.com/aws/aws-lambda-go/lambdacontext go.exe get -u github.com/aws/aws-lambda-go/cmd/build-lambda-zip To compile the code Windows/Linux/Mac, use the following commands − GOOS=linux GOARCH=amd64 go build -o main main.go %GOPATH%binbuild-lambda-zip.exe -o main.zip main AWS Lambda Function using GO A program returned in Go when build gives an executable file. The following is a simple program in Go with AWS Lambda support. We need to import the github.com/aws/aws-lambda-go/lambda, as this has the Lambda programming functionality.Another important need for AWS Lambda is the handler. Main.go // main.go package main import ( “github.com/aws/aws-lambda-go/lambda” ) func hello() (string, error) { return “Hello Lambda”, nil } func main() { // Make the handler available for Remote Procedure Call by AWS Lambda lambda.Start(hello) } Note that the execution of the Go program starts from main where lambda. start is called with the handler function. Observe the code shown below − func main() { // Make the handler available for Remote Procedure Call by AWS Lambda lambda.Start(hello) } Now, let us execute the above file using Go command and then zip the executable file. The structure of the file we have been using is as shown here − With go build, it creates an executable file called main.exe. To zip the file and upload it in AWS Lambda, you can use the following procedure − To compile the code Windows/Linux/Mac, use the following commands − GOOS=linux GOARCH=amd64 go build -o main main.go %GOPATH%binbuild-lambda-zip.exe -o main.zip main Then, login into AWS console and create Lambda function using Go as runtime − Once the function is created, upload the executable zip file created above. Lambda function handler with Go Handler is where the execution of the Go program starts. From main call to lambda.start, execution is called with the handler function. Note that the handler to be added will be main. Observe the code here for an understanding − func main() { // Make the handler available for Remote Procedure Call by AWS Lambda lambda.Start(hello) } Follow as per the screenshots given below − Now, save the function and test it. You can see the execution result as shown here. The corresponding log output will be as shown here − Context object with Go AWS Lambda in Go gives following global variables and properties for context. MemoryLimitInMB − Memory limit, in MB that is configured in aws lambda. FunctionName − name of aws lambda function. FunctionVersion − the version of aws lambda function executing. LogStreamName − cloudwatch log stream name. LogGroupName − cloudwatch group name. The properties available on context are given as under − AwsRequestID This is AWS request id which you get when AWS Lambda function is invoked. ClientContext This contains details about the client application and device when invoked through the AWS Mobile SDK. It can be null. Client context provides details like client ID, application title, version name, version code, and the application package name. InvokedFunctionArn The ARN of the function invoked. An unqualified ARN executes the $LATEST version and aliases execute the function version it is pointing to. Identity It gives details about the Amazon Cognito identity provider when used with AWS mobile SDK. The changes added to main.go to print context details − // main.go package main import ( “context” “log” “github.com/aws/aws-lambda-go/lambda” “github.com/aws/aws-lambda-go/lambdacontext” ) func hello(ctx context.Context) (string, error) { lc, _ := lambdacontext.FromContext(ctx); log.Print(lc); log.Print(lc.AwsRequestID); log.Print(lc.InvokedFunctionArn); return “Hello Lambda”, nil } func main() { // Make the handler available for Remote Procedure Call by AWS Lambda lambda.Start(hello) } We need to import the log and lambda context to use it with Go. The context details are as follows − func hello(ctx context.Context) (string, error) { lc, _ := lambdacontext.FromContext(ctx); log.Print(lc); log.Print(lc.AwsRequestID); log.Print(lc.InvokedFunctionArn); return “Hello Lambda”, nil } You can observe the following output on testing the above code − Logging data With Go you can log data using the log or fmt module as shown below − // main.go package main import ( “log” “fmt” “github.com/aws/aws-lambda-go/lambda” ) func hello() (string, error) { log.Print(“Hello from Lambda Go using log”); fmt.Print(“Hello from Lambda Go using fmt”); return “Hello Lambda”, nil } func main() { // Make the handler available for Remote Procedure Call by AWS Lambda lambda.Start(hello) } The output for same is as shown below − Checking Logs in CloudWatch You can

Building the Lambda function

Building the Lambda Function ”; Previous Next AWS Lambda function executes a code when it is invoked. This chapter discusses all these steps involved in the life cycle of AWS Lambda function in detail. Steps for Building a Lambda function The lifecycle of Lambda function includes four necessary steps − Authoring Deploying Monitoring Troubleshooting Authoring Lambda Code AWS Lambda function code can be written in following languages − NodeJS Java, Python C# Go. We can write code for AWS Lambda using the AWS console, AWS CLI, from Eclipse IDE, from Visual Studio IDE, serverless framework etc. The following table shows a list of languages and the different tools and IDE that can be used to write the Lambda function − Language IDE for Authoring Lambda Code NodeJS AWS Lambda Console Visual Studio IDE Java Eclipse IDE Python AWS Lambda Console C# Visual Studio IDE .NET core Go AWS Lambda Console Deploying Lambda Code Once you decide the language you want to write the Lambda function, there are two ways to deploy the code − Directly write the code in AWS console Zip or jar the files with all the files and dependencies However, remember that proper permission has to given to be given to the zip file. Testing Lambda Code Lambda Code can be tested for events inside the AWS Lambda console. It is also possible to test the Lambda function from the AWS cli and serverless cli. AWS console has also event data which can be used as sample events while testing AWS Lambda function. Monitoring Lambda function Monitoring of Lambda function can be done using the AWS CloudWatch. We can add necessary log messages in languages we choose and see the same in AWS CloudWatch. To start writing Lambda function, there is pattern to be followed. The following are the main core concepts to be followed for writing a Lambda function − Handler Handler is a name of the AWS lambda function from where the execution starts. It appears in AWS console as shown below − Notice that here we have changed the default handler to another name and updated the same in the Handler − Note that the way a handler is called differs from the languages selected as runtime. Params passed to handler If you observe the handler function, the params passed are event, context and call back function as shown below − Event parameter has all the details for the trigger used. Context parameter basically takes care of runtime details for the Lambda function to execute. We can interact with the Lambda function using the context param. It has the details like the time left before AWS Lambda terminates a function i.e, timeout specified while creating Lambda function, name of the Lambda function, cloudwatch group name, arn details etc. Example Let us understand the details obtained from AWS Lambda context object with the help of an example − exports.lambdahandler = (event, context, callback) => { // TODO implement console.log(“context object details”); console.log(JSON.stringify(context)); callback(null, ”Lambda test”); }; When you execute the Lambda function shown above, you can see the following output − Output The context details are given as follows − { “callbackWaitsForEmptyEventLoop”:true,”logGroupName”:”/aws/lambda/myfirstlambdafunction”, “logStreamName”:”2018/05/20/[$LATEST]04f17ee4ff7048d5bb1fedffaa807c71″,”functionName”: “myfirstlambdafunction”,”memoryLimitInMB”:”128″,”functionVersion”:”$LATEST”,”invokeid”: “c931e21c-5bf3-11e8-acfe-47fdbb39eee9″,”awsRequestId”:”c931e21c-5bf3-11e8-acfe-47fdbb39eee9″, “invokedFunctionArn”:”arn:aws:lambda:us-east-1:625297745038:function:myfirstlambdafunction” } Observe that it has details like functionName, memorylimit, requestId etc. Logging The logs added inside the Lambda function are displayed in AWS CloudWatch when the AWS function executes. The logs syntax will vary from the language selected. For Example in nodejs, it is console.log. This is the output you can see in AWSCloudWatch − Error Handling AWS Lambda function provides a callback function which is used to notify to the Lambda function that an error or success has happened. Note that here we have used nodejs as the runtime. The error handling will differ as per the language selected. Observe the Example given here for a better understanding − exports.lambdahandler = (event, context, callback) => { // TODO implement var error = new Error(“There is error in code”); callback(error); }; Output When you test the Lambda code, you can find the output as shown below − The log details as follows − Print Page Previous Next Advertisements ”;