How to Trigger Lambda Function in Amazon Web Services

When we think about a cloud solution provider, we often consider the most popular ones, i.e. Amazon Web Services, Microsoft Azure, and Google Cloud Platform. There are other popular providers (IBM, Oracle, etc.), but the three giants take the lion’s share of the market. Hence, companies prefer migrating their architectures to these providers. Amazon is a leader with over 200 web services currently, and it adds more every month.

CodingSight - AWS Lambda and Auto-triggering its Functions

AWS Lambda is a service offered by Amazon. It can be used to run programs directly on the cloud without worrying about any underlying infrastructure.  Customers can lift and shift their existing codes and create Lambda functions out of them. At present, Lambda supports multiple programming languages, such as C#, Java, JavaScript, Python, Ruby, etc. to write programs.

AWS Lambda Advantages 

Some of the primary AWS Lambda advantages are:

  • Serverless. As already mentioned, you can directly upload your code as a compressed zip archive or via containers like Docker. This zip archive will be loaded by Lambda and executed whenever triggered.
  • Automatic Scaling. Since AWS Lambda is a managed service, we may not worry about load during the execution. It automatically scales up and down according to incoming requests. Also, it can run multiple instances of the same function in parallel.
  • Low cost. As compared to on-premise solutions where you pay for infrastructure even though your program is not executed, AWS Lambda bills you only for the duration of your program execution. Customers can save on their costs budget a lot. It is considered one of the main pluses of moving to the cloud.

How to Create a Lambda Function in AWS Using Python 

Now that we have some idea about AWS Lambda and its features, let us proceed to the AWS Console and try to find out how to use Lambda from scratch.

Navigate to the AWS Console and search for Lambda. The Lambda console will show up on the display:

AWS Lambda Console
Figure 1 – AWS Lambda Console

As you can see, there are no functions created at the moment. We can create a simple one by using the Create Function feature on the right. For demonstration purposes, I am going to use Python 3.8 in this tutorial as the runtime. However, you are free to choose any suitable language and runtime.

A basic function in Lambda
Figure 2 – A basic function in Lambda

Thus, we have defined the basic Lambda function using Python.

Lambda Event Triggers 

Before we proceed to examine different AWS Lambda triggers, let’s clarify what that trigger is.

When we work with Lambda, we can invoke some of its functions in response to a definite event, request, or run them by schedule. These will be our AWS Lambda triggers.

The event triggers can be anything – a message to the queue, the addition of a file to S3, etc. All these events can also pass some information to the Lambda function for execution. The information gets passed with the help of the event variable.

A basic test event in Lambda
Figure 3 – A basic test event in Lambda

The figure above demonstrates the basic test event in JSON format. It will be passed on to the Lambda function when triggered. The Lambda function will parse the information from the event variable and then process and print out the results on the console.

To trigger the event, you can click on the Test button under the Test Event section on the Lambda console. After testing the function, you can see the output on the console and the JSON response about the status.

Execution status of the Lambda function
Figure 4 – Execution status of the Lambda function

Once you’ve executed the Lambda function from the console, it will immediately execute and display the result. On the top section, you will see the result returned by the successful execution of the function. It also provides information regarding some of the important metrics during the execution:

  • Init. Duration – the duration that is taken by the service to initialize the program.
  • Duration – the time that Lambda took to execute the function.
  • Billed Duration – the time on which the billing has to be calculated.
  • Resources configured – the maximum amount of memory allocated to this Lambda function.
  • Max memory used – the maximum amount of memory used by the Lambda function.

On the bottom, you can see the Lambda function log output – it is generated while executing. There are some fixed outputs in the log, such as Start and End Request IDs along with some other metrics. The output This is a basic test function is generated by the Lambda function during the execution.

CloudWatch Lambda Trigger

CloudWatch console is another service from AWS. You can use CloudWatch to configure events – these will be the CloudWatch Lambda triggers. For instance, it will invoke the Lambda function to log the activity.

CloudWatch will allow you to view historic logs that are generated whenever the Lambda functions are executed by the CloudWatch Lambda trigger or different triggers.

Using CloudWatch console to view logs
Figure 5 – Using CloudWatch console to view logs

To view a log from the CloudWatch console, click on the Logs section. It will redirect you to the necessary section.

Viewing logs in the CloudWatch Console
Figure 6 – Viewing logs in the CloudWatch Console

The CloudWatch console contains Log streams from each duration of Lambda executions. Whenever a Lambda function is executed, it creates a log stream. You can view the actual log information by navigating into the stream.

Schedule Events and Tasks with Lambda Scheduled Functions Trigger 

We should be able to automate the execution, and this is the idea behind the AWS Lambda scheduled functions. The jobs are automated on a predefined schedule, such as every minute, hour, or during a specified time every day, etc.

This can be done by setting up special rules in the CloudWatch console. Then AWS lambda scheduled functions will be triggered whenever the condition is met.

Navigate to Rules under Events on the left pane in the CloudWatch portal and click Create Rule. A new page will appear at once.

Creating Rules in CloudWatch to trigger Lambda functions
Figure 7 – Creating Rules in CloudWatch to trigger Lambda functions

We will create a schedule to execute the Lambda function every minute.

Event Source > Schedule > type 1 for the Fixed Rate of section. This will create the schedule to run Lambda every one minute. Alternatively, you can write a cron expression that can do a similar job.

Under Targets, select Lambda Function and then the name of the function for which we create the schedule.

While executing the function from the Lambda console previously, we provided an event in the form of a JSON string. We can provide the same JSON string as an input under the Configure input section: select Constant (JSON text).

Creating the schedule in CloudWatch to trigger Lambda
Figure 8 – Creating the schedule in CloudWatch to trigger Lambda

Click on Configure details once completed. You should provide the name and description for the rule that you have just created and click on Create Rule.

As soon as you create the rule, the Lambda function will start executing every minute or as per the schedule defined in the rule. You can get this verified by viewing the logs in the CloudWatch portal.

Lambda function being executed every minute
Figure 9 – Lambda function being executed every minute

As you see in the figure above, the function has been executed three times so far and will continue to do so until the rule is disabled or deleted.

Also, you can use the Amazon Simple Storage Service and create events as Amazon S3 trigger Lambda functions. Note that you need to provide the appropriate permissions to invoke the action by that trigger. The S3 triggers Lambda when the resource-based policy allows for that.

Conclusion

Thus, we have learned how to create a simple Lambda function and pass event parameters to parse and display results. We have also learned to create automated schedules using the CloudWatch Rules and auto-trigger Lambda functions.

For more information regarding Lambda functions, please refer to the official documentation. Also, if you want to learn more about AWS Lambda you can take a look at article dedicated to AWS Lambda Layers.

Aveek Das
Latest posts by Aveek Das (see all)

Aveek Das

Aveek is an experienced Data and Analytics Engineer, currently working in Dublin, Ireland. His main areas of technical interest include SQL Server, SSIS/ETL, SSAS, Python, Big Data tools like Apache Spark, Kafka, and cloud technologies such as AWS/Amazon and Azure. He is a prolific author, with over 100 articles published on various technical blogs, including his own blog, and a frequent contributor to different technical forums. In his leisure time, he enjoys amateur photography mostly street imagery and still life. Some glimpses of his work can be found on Instagram. You can also find him on LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *