Integrating two Lambda functions using EventBridge

TOC

Integrating two Lambda functions using EventBridge

EventBridge is a fully managed event bus service.

Amazon EventBridge is a service that provides real-time access to changes in data in AWS services, your own applications, and software as a service (SaaS) applications without writing code. EventBridge will automatically deliver the events in near real-time.

Amazon EventBridge FAQs

The goal of this page is to link two Lambda functions using EventBridge.

Environment

Diagram of integrating two Lambda functions using EventBridge.

Create two Lambda functions.

The first Lambda function will publish events for EventBridge.
Specifically, the first Lambda function will retrieve the UNIX time from the current date and time, and publish the event with this information.

In EventBridge, define rules for events received from the first Lambda function.
Specifically, the rule is for the content that targets Lambda function 2.

The second Lambda function performs processing according to the contents of the received event.
Specifically, it determines whether the UNIX time obtained from the event is even/odd.

The runtime of the function is Python 3.8.

CloudFormation template files

The above configuration is built using CloudFormation.
The CloudFormation templates are located at the following URL

https://github.com/awstut-an-r/awstut-fa/tree/main/099

Explanation of key points of the template files

EventBridge

Resources:
  EventsRule:
    Type: AWS::Events::Rule
    Properties:
      EventBusName: !Ref EventBusName
      EventPattern:
        source:
          - !Ref Prefix
      Name: !Sub "${Prefix}-EventsRule"
      State: ENABLED
      Targets:
        - Arn: !Ref FunctionArn2
          Id: !Ref Function2
Code language: YAML (yaml)

Specify the event bus name in the EventBusName property.

An event bus is a pipeline that receives events. Rules associated with the event bus evaluate events as they arrive.

Amazon EventBridge event buses

The default event bus “default” is used in this case.

The EventPattern property specifies the events accepted by this rule.

An event pattern defines the event structure and the fields that a rule matches.

Amazon EventBridge rules

In this case, events with a source value of “fa-099” are the target of this rule.

Specify the destination of the events matched by this rule in the Targets property.

A target is a resource or endpoint that EventBridge sends an event to when the event matches the event pattern defined for a rule.

Amazon EventBridge targets

In this case, we will specify Lambda function 2, which is described below.

When a Lambda function is specified as the target, the behavior is that EventBridge invokes the function.
Therefore, it is necessary to give EventBridge the authority to invoke the function.

Resources:
  EventsRulePermission:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !Ref Function2
      Action: lambda:InvokeFunction
      Principal: events.amazonaws.com
      SourceArn: !GetAtt EventsRule.Arn
Code language: YAML (yaml)

I set it up with reference to the following official AWS page

https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-use-resource-based.html#eb-lambda-permissions

Lambda Functions

Function 1

Resources:
  Function1:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        ZipFile: |
          import boto3
          import datetime
          import json
          import time
          import os

          event_bus_name = os.environ['EVENT_BUS_NAME']
          detail_type = os.environ['DETAIL_TYPE']
          source = os.environ['SOURCE']

          client = boto3.client('events')

          def lambda_handler(event, context):
            now = datetime.datetime.now()
            unix_time = int(time.mktime(now.timetuple()))

            detail = json.dumps(
              {
                'now': now.strftime('%Y-%m-%d %H:%M:%S.%f'),
                'unix_time': unix_time
              }
            )

            entry = {
              'Time': datetime.datetime.now(),
              'Source': source,
              'Resources': [],
              'DetailType': detail_type,
              'Detail': detail,
              'EventBusName': event_bus_name
            }
            print(entry)

            response = client.put_events(
              Entries=[entry,]
            )
            print(response)
      Environment:
        Variables:
          EVENT_BUS_NAME: default
          DETAIL_TYPE: unix-time-event
          SOURCE: !Ref Prefix
      FunctionName: !Sub "${Prefix}-function-01"
      Handler: !Ref Handler
      Runtime: !Ref Runtime
      Role: !GetAtt FunctionRole.Arn
Code language: YAML (yaml)

No special configuration is required to publish events to EventBridge.
For more information on how to create a Lambda function in CloudFormation, please check the following page

あわせて読みたい
3 parterns to create Lambda with CloudFormation (S3/Inline/Container) 【Creating Lambda with CloudFormation】 When creating a Lambda with CloudFormation, there are three main patterns as follows. Uploading the code to an S3 buc...

In this case, we will describe the code to be executed inline.

The content of the code to be executed in the function is as follows

  1. retrieve UNIX time from the current date/time.
  2. publish an event by executing the put_events method of the client object for EventBridge.

The arguments passed to the put_events method are set with reference to the following official AWS page.

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/events.html#EventBridge.Client.put_events

Specifically, create and publish the following event data.

{
  'Detail': '{"now": "2022-11-22 23:28:26.622445", "unix_time": 1669159706}',
  'DetailType': 'unix-time-event',
  'EventBusName': 'default',
  'Resources': [],
  'Source': 'fa-099',
  'Time': datetime.datetime(2022, 11, 22, 23, 28, 26, 622526)
}
Code language: Python (python)

Stores data to be passed to function 2 in Detail.
The format must be a JSON string.
In this case, the current date and time and its UNIX time are specified.

Specify the event bus name in EventBusName.
This time, the default event bus is used, so “default” is specified.

Specify the event source for Source.
This time, the event pattern of the EventBridge rule is set to check this value.
Therefore, specify “fa-099” for this parameter.

Function 2

The settings for Function 2 are the same as for Function 1.
This one checks only the code to be executed.

def lambda_handler(event, context):
  print(event)

  unix_time = event['detail']['unix_time']

  if (unix_time % 2) == 0:
    print('{int} is even !'.format(int=unix_time))
  else:
    print('{int} is odd !'.format(int=unix_time))
Code language: Python (python)

Get UNIX time from events received from EventBridge and determine even/odd.
Event data is stored in the event variable.

Architecting

Using CloudFormation, build this environment and check the actual behavior.

Create CloudFormation stacks and check resources in stacks

Create CloudFormation stacks.
For information on how to create stacks and check each stack, please refer to the following page

あわせて読みたい
CloudFormation’s nested stack 【How to build an environment with a nested CloudFormation stack】 Examine nested stacks in CloudFormation. CloudFormation allows you to nest stacks. Nested ...

After checking the resources in each stack, information on the main resources created this time is as follows

  • EventBridge rule: fa-099-EventRule
  • Lambda function 1: fa-099-function-01
  • Lambda function 2: fa-099-function-02

Check the created resource from the AWS Management Console.
Check the EventBridge rule.

Detail of EventBridge 1.
Detail of EventBridge 2.

The rule is created on the default event bus.
Looking at the event pattern and target, we can see that the event data is sent to function 2 if the value of the source of the event data is “fa-099”.

In the meantime, we also check the detailed event rule settings.

Detail of EventBridge 3.
Detail of EventBridge 4.
Detail of EventBridge 5.

Check the two Lambda functions.

Detail of Lambda Function 1.
Detail of Lambda Function 2.

Both functions are created as specified in the CloudFormation template.
If we look at function 2, we can also see that invokes from EventBridge are allowed.

Checking Operation

1st time

Now that we are ready, we execute Function 1.

Detail of Lambda Function 3.

From the Function 1 page, click on “Test” to execute it.

Check the execution log of Function 1 from CloudWatch Logs.

Detail of Lambda Function 4.

You can see that the function was successfully invoked.
You can read that an object for the event was created and that it was successfully published to EventBridge.
This time the UNIX time was “1669163606”.

Next we check the log of function 2.

Detail of Lambda Function 5.

There is evidence that the function was invoked.
This means that the function 2 specified in the rule was automatically invoked when the event was published to EventBridge.

The UNIX time passed in detail is determined to be even/odd, and “1669163606 is even ! was output.

2nd time

Perform the same operation again.

The following is the invocation log of both functions.

Detail of Lambda Function 6.
Detail of Lambda Function 7.

This time, an event with UNIX time “1669163697” was published to EventBridge by Function 1.
In response, function 2 was automatically invoked, which determined that the number was odd and output “1669163697 is odd !”

Summary

We have identified a way to integrate two Lambda functions using EventBridge.

TOC