How to associate an event bus created via boto3 with a mongodb event trigger?

0

I have an event bus that I created through boto3. Now, this event bus needs to get information from a mongodb trigger (https://cloud.mongodb.com/v2/662b391615a47202d49f2fa0#/triggers/66b09906efb4ea73e72cd7dd) How to associate this mongodb trigger with the event bus?

This is the code i used to create the event bus

import boto3
import json
from botocore.exceptions import ClientError
#mongotriggerid = '66752f191141184fc363c657'
session = boto3.Session(
      aws_access_key_id=userdata.get('AWS_ACCESS_KEY_VALUE'),
      aws_secret_access_key=userdata.get('AWS_SECRET_KEY_VALUE'),
      region_name='us-east-1'
  )
eventbridge = session.client('events', region_name='us-east-1')

# Function to create an event bus if it doesn't exist
def create_event_bus(event_bus_name):
    try:
        response = eventbridge.create_event_bus(
            Name=event_bus_name,
            #EventSourceName='string',
            Description='Event bus which will bring information from MongoDB Trigger to Event Bridge Rule'
            #KmsKeyIdentifier='string',
            #DeadLetterConfig={
            #    'Arn': 'string'
            #},
            #Tags=[
            #    {
            #        'Key': 'string',
            #        'Value': 'string'
            #    },
            #]
        )
        print(f"Event bus '{event_bus_name}' created.")
        return response #response['Arn']
    except ClientError as e:
        if 'ResourceAlreadyExistsException' in str(e):
            print(f"Event bus '{event_bus_name}' already exists.")
            response = eventbridge.describe_event_bus(
                Name=event_bus_name
            )
            return response['Arn']
        else:
            raise e

# Event bus name
event_bus_name = "test-event-bus-1"#'aws.partner/mongodb.com/stitch.trigger/'+ mongotriggerid

# Create the event bus or get its ARN if it already exists
event_bus_arn = create_event_bus(event_bus_name)

# Define the event pattern
event_pattern = {
    "source": [{
        "prefix": "aws.partner/mongodb.com"
    }]
}

# Create or update the rule
response = eventbridge.put_rule(
    Name='darwin-early-cancer-detection-crawl-job',
    Description='Send the event to an SQS Queue which would invoke the lambda function for Crawl job for a new company.',
    EventPattern=json.dumps(event_pattern),
    State='ENABLED',
    EventBusName=event_bus_name,
    Tags=[
        {
            'Key': 'owner',
            'Value': 'decibio-grazitti'
        }
    ]
)

rule_arn = response['RuleArn']

# Add target to the rule
response = eventbridge.put_targets(
    Rule='darwin-early-cancer-detection-crawl-job',
    EventBusName=event_bus_name,
    Targets=[
        {
            'Id': '1',  # Unique identifier for the target
            'Arn': '#########################',
            'InputPath': '$',
            'RetryPolicy': {
                'MaximumRetryAttempts': 0,
                'MaximumEventAgeInSeconds': 86400  # 24 hours
            },
            'SqsParameters': {
                'MessageGroupId': '2'
            },
        }
    ]
)

print('Rule ARN:', rule_arn)
print('Target response:', response)
1 Answer
1

Hello,

Please try this solution.

To associate a MongoDB trigger with an AWS EventBridge event bus fellow below step.

To Create an AWS Lambda Function:

This function will forward MongoDB trigger events to EventBridge.

import json
import boto3

def lambda_handler(event, context):
    eventbridge = boto3.client('events')
    
    # Prepare and send the event to EventBridge
    response = eventbridge.put_events(
        Entries=[
            {
                'Source': 'mongodb.trigger',
                'DetailType': 'MongoDB Trigger Event',
                'Detail': json.dumps(event),
                'EventBusName': 'test-event-bus-1'  # Replace with your EventBus name
            }
        ]
    )
    
    return {
        'statusCode': 200,
        'body': json.dumps('Event sent to EventBridge')
    }

Deploy the Lambda Function:

Deploy the Lambda function and note its ARN.

Configure MongoDB Trigger:

Set up your MongoDB trigger to invoke the Lambda function. This sends MongoDB events to the Lambda function.

Update EventBridge Rule:

the EventBridge rule targets the Lambda function. Modify the existing rule or create a new one.

import boto3

session = boto3.Session(
    aws_access_key_id='YOUR_ACCESS_KEY',
    aws_secret_access_key='YOUR_SECRET_KEY',
    region_name='YOUR_REGION'
)
eventbridge = session.client('events')

response = eventbridge.put_targets(
    Rule='darwin-early-cancer-detection-crawl-job',  # Your rule name
    EventBusName='test-event-bus-1',  # Your EventBus name
    Targets=[
        {
            'Id': '1',
            'Arn': 'arn:aws:lambda:your-region:your-account-id:function:your-lambda-function-name',
            'InputPath': '$'
        }
    ]
)

This setup forwards events from MongoDB triggers through a Lambda function to your EventBridge event bus, allowing you to integrate MongoDB events with AWS services.

https://aws.amazon.com/blogs/compute/ingesting-mongodb-atlas-data-using-amazon-eventbridge/

https://hands-on.cloud/eventbridge-building-loosely-coupled-event-drivent-serverless-architectures/#google_vignette

https://www.mongodb.com/docs/atlas/app-services/triggers/aws-eventbridge/

EXPERT
answered 3 months ago
profile picture
EXPERT
reviewed 3 months ago
profile pictureAWS
EXPERT
reviewed 3 months ago
  • Can I just use the code

    response = eventbridge.put_events(
        Entries=[
            {
                'Source': 'mongodb.trigger',
                'DetailType': 'MongoDB Trigger Event',
                'Detail': json.dumps(event),
                'EventBusName': 'test-event-bus-1'  # Replace with your EventBus name
            }
        ]
    )
    

    directly in a single function which creates event bus and associates mongodb trigger with it?

    Secondly, do i have to put the mongodb trigger details anywhere?

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions