AWS Lambda Hands-On| Part-2

aditya goel
11 min readJan 22, 2022

In case you are landing here directly, it’s recommended to read through this documentation first.

In this particular blog, we would demonstrate following aspects :-

  • Cloning from Docker Image.
  • Launching Container from the Docker Image.
  • SAM INIT to setup a sample project for Lambda.
  • SAM BUILD to compile & build the Java based Lambda project.
  • SAM DEPLOY to deploy Lambdas to AWS Stack.
  • Creating our first Lambda function and managing it’s lifecycle.
  • Creating Lambda function to receive simple parameter in request.
  • Anatomy of any SAM Template.yaml file.
  • Sneak peak under the hoods of SAM DEPLOY command.
  • Destroying entire AWS Stack using AWS CLI.

Question:- Let’s demonstrate Building a Simple Lambda Function ?

Answer:- We would begin with the Docker Image that we built in the last blog. That Docker Image has all necessary softwares installed like AWS CLI & SAM CLI. It’s just that we have to begin by configuring the AWS on the same.

Step #1.) Download the Docker Image from Docker Hub :-

Step #2.) Let’s see here, we get the docker image on our local machine :-

Step #3.) Let’s start a fresh container from this Image and login to the same, post which we shall start with setting up a fresh Lambda project inside our container :-

Step #4.) Let’s choose quick start for above choice :-

Step #5.) Let’s choose Hello World Example for above choice :-

Step #5.) Let’s choose java8 as runtime for above choice :-

Step #6.) Let’s choose Zip as package type AND maven as Dependency manager for above choice :-

Step #6.) Let’s give the name of our application as “adityaLearningLambda” :

Step #7.) Let’s now bring this project folder as it is to our local machine :-

docker cp peaceful_allen:/adityaLearningLambda .

Step #8.) Let’s now install maven software to our container :-

sudo apt-get update && apt-get install maven

Step #9.) Let’s now build our project :-

sam build

Step #9.) Let’s now see, what all has happened, post we build our project. It has created a folder called Dot AWS SAM, it does it for every AWS lambda function project you create.

Under that, there is a folder called Build within which your source code, which is compiled lives and also all the dependencies of your project will be packaged under a folder called Lib.

Step #10.) Let’s now see first, how does these details looks like :-

Question:- Let’s demonstrate Deploying a Simple Lambda Function to the AWS ?

Answer:- We would be using SAM CLI to deploy the Lambda to the AWS :-

Step #1.) Let’s now proceed to deploy this Lambda function to the AWS. As we are running the deploy command for the first time, we would be running the same in guided way. This shall create a AWS CloudFormation Stack :-

Step #2.) Let’s now proceed to deploy this Lambda function to the AWS. As we are running the deploy command for the first time, we would be running the same in guided way. This shall create a AWS CloudFormation Stack in “us-east-1” region :-

It also does creates a S3 bucket. It will copy the artifacts from the build directory to this S3 bucket.

Step #3.) Let’s now see, what all resources have been created under the hoods by this operation :-

Step #4.) Let’s now verify that, the above endpoint is active :-

  • Note that, the above endpoint belongs to the API-Gateway and in this case, hitting to the gateway would eventually trigger the Lambda function and the above response is well coming from the Lambda function.
  • This is the IP address where the lambda function is being run dynamically when the lambda environment is created for a few seconds, that IP address of virtual machine or the machine on the cloud.

Question:- Can you show, from where does the above output is coming ?

Answer:- Following code is leading to the above output :-

Question:- Can you demonstrate the API-Gateway created under the hoods by our IAAS ?

Answer:- Yes here is the API-Gateway been created by our CFN :-

Question:- Can you demonstrate the S3 bucket created under the hoods by “sam deploy” command ?

Answer:- Yes here is the S3 bucket, which has been created under the hoods automatically.

Question:- Let’s demonstrate a very basic / simple Lambda Function ?

Part #1.) Let’s first trim our yaml file. Note that, we have trimmed this yaml file and it looks something like this now :-

root@9090f8d966d0:/adityaLearningLambda# cat template.yamlAWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
adityaLearningLambda

Sample SAM Template for adityaLearningLambda

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 20

Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: HelloWorldFunction
Handler: helloworld.App::hello
Runtime: java8
MemorySize: 512
  • We only have a Resource being defined inside the yaml and there is a Handler that we have defined here : ClassName is “App” and MethodName is “hello”.
  • Also observe that, we have allocated 512MB of RAM to this Lambda function.

Part #2.) Let’s now prepare our sample Java code file :-

package helloworld;

public class App {
public String hello() {
return "First Awesome hello from Lambda Functions..";
}
}

Note that the method name we crated is “hello()” and class name we created is App.Java, as mentioned in the template.yaml file.

Part #3.) Let’s now compile our code using sam build command :-

sam build

Part #4.) Let’s now go ahead and deploy our artefacts to the AWS cloud. ote that, many things that we earlier created have also been deleted, because many resources are no-more required and not in use.

sam deploy

Note that, since we already have the configuration file with us “samconfig.toml”, therefore we don’t need to run the sam deploy in the guided mode.

Part #5.) Let’s now test our Lambda function from the AWS console itself :-

Note that, event format doesn’t matters, because our Lambda function doesn’t accepts any request at all. Also, from the output logs, you can see that the statement has been printed into the Execution Result.

Question:- Let’s demonstrate Lambda Function, which receives some parameter ?

Part #1.) Let’s now prepare our sample Java code file :-

package helloworld;

public class App {
public String hello(String firstParameter) {
return "Executed lambda function along with paramtere in request.." + firstParameter;
}
}

Part #2.) Let’s now review our template.yaml file :-

Part #3.) Let’s now go ahead and validate our SAM Template, whether it’s OK or it has some compilation error :-

sam build

Part #4.) Let’s now go ahead and build the code that we have written :-

sam build

Part #5.) Let’s now deploy our artefacts to the AWS cloud :-

sam deploy

Part #6.) Let’s test our Lambda function from the AWS console. Note that, we would have to supply the parameter in the request. In below request, we are supplying “Aditya” as the parameter and we have kept “TestLambdaWithOneParam” as the name of the test-event.

Part #6.) We can also see the logs in our local console, rather than every time going to the AWS dashboard to see the logs. See here :-

sam logs -n HelloWorldFunction --stack-name adityaLambdaFirstStack --tail

Here are logs in the AWS dashboard :-

And here are same logs in the local terminal :-

Part #7.) Say we supply erroneous values as parameter to the Lambda functions, then it’s expected for Lambda to fail with below exception :-

java.lang.RuntimeException: An error occurred during JSON parsingCaused by: java.io.UncheckedIOException: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token

Question:- Kindly explain the anatomy of the SAM Template file ?

Answer:- Here is our SAM template file :-

Section #1.)

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
  • The very first line “AWS template format version” tells which version of cloud formation template we are using.
  • Then this “Transform” element tells that, this template is of type AWS serverless template and it needs to be transformed to cloud formation.

Section #2.)

Description: >
adityaLearningLambda

Sample SAM Template for adityaLearningLambda

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst

The description is not mandatory. Even if you delete this, it will work. It explains any other developer or Devops Engineer or AWS engineer to know what this lambda exactly does. So you can describe your lambda function right here.

Section #3.)

Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: HelloWorldFunction
Handler: helloworld.App::hello
Runtime: java8
MemorySize: 512

The resources section is mandatory. This is where will define our lambda functions and other resources like SQS, SNS whatever we have to do with our lambda function, all those resources can be defined in the resource section.

  • HelloWorldFunction” is the name of the resource type.
  • AWS::Serverless::Function” is the type of the resource.

We also need to define properties for this lambda function :

  • CodeUri → Here the code can be found. This is the folder, where you have to look inside the build directory for our code.
  • Handler → Here, we define the package name, the class name and then the name of the function
  • Runtime → Here, we can define the Java version that we want to use. If you want to change it to Java Eleven, you simply change this from eight to eleven.
  • MemorySize → Here, we define the memory of 512 MB for our Lambda function.

Section #4.)

Globals:
Function:
Timeout: 20

This global section can be used up top and you can define properties that can be applied across all the resources that we define.

Timeout: This value keeps on changing, but we can configure the same.

Question :- What exactly happens, when someone hits command “sam deploy” ?

Answer :- When you do “sam deploy”, it will pick the class files from “.aws-sam/build” directory and picks up the dependencies from lib directory. It will package them as a zip file and it will push them onto S3 environment. From there, it will go to the LAMBDA service eventually.

Question:- What are the resources to which our AWS Lambda can access right now ?

Answer:- As of now, it can only access Cloudwatch logs, because thats what the current IAM role suggests :-

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "*"
}
]
}

Question:- Which all other resources can access to our LAMBDA function ?

Answer:- As of now, no-other resource on AWS can access our Lambda function, because that what Resource access policy suggests :-

Question:- How can we get rid/delete the entire stack from the AWS Lambda?

Answer:- We can do so by using following command :-

aws cloudformation delete-stack --stack-name adityaLambdaFirstStack

That’s all in this section. If you liked reading this blog, kindly do press on clap button multiple times, to indicate your appreciation. We would see you in next series.

References :-

--

--

aditya goel

Software Engineer for Big Data distributed systems