Untitled

mail@pastecode.io avatar
unknown
plain_text
25 days ago
2.7 kB
1
Indexable
Never
import boto3
import os
import logging as logger

client = boto3.client('events')

logging = logger.getLogger()
logging.setLevel(logger.INFO)

def lambda_handler(event, context):
    print("Received event:", event)
    received_event = event
    
    rule_from_event = received_event['alarmData']['alarmName']
    
    # Check the state value
    state_value = event.get('alarmData', {}).get('state', {}).get('value')
    
    # Specify the details of the event to enable
    rule_name = f"{rule_from_event}_rule"  # Replace with the name of your EventBridge rule
    event_bus_name = "default"  # Replace 'default' with the name of your event bus if needed
    
    # List all rules 
    try: 
        rules = client.list_rules(
            EventBusName="default",
            Limit=20
        )
        rules_arns = [rule['Arn'] for rule in rules['Rules']]
    except Exception as e:
        logging.error(f"Error listing EventBridge rules with exception: {e}")
        
    # List tags for rules
    try:
        for arn in rules_arns:
            tags = client.list_tags_for_resource(ResourceARN=arn)['Tags']
            # Find alarm after tags matching
            matching_tag = next((tag for tag in tags if tag['Key'] == 'triggered_by' and tag['Value'] == rule_from_event), None)
            if matching_tag:
                # Check alarm state
                if state_value == 'ALARM':
                    # Enable the EventBridge rule
                    try:
                        response = client.enable_rule(
                            Name=rule_name,
                            EventBusName=event_bus_name
                        )
                        logging.info("EventBridge rule '{}' enabled successfully".format(rule_name))
        
                    except Exception as e:
                        logging.error("Error enabling EventBridge rule '{}': {}".format(rule_name, e))
        
                elif state_value == 'OK':
                    # Disable the EventBridge rule
                    try:
                        response = client.disable_rule(
                            Name=rule_name,
                            EventBusName=event_bus_name
                        )
                        logging.info("EventBridge rule '{}' disabled successfully".format(rule_name))
                    except Exception as e:
                        logging.error("Error disabling EventBridge rule '{}': {}".format(rule_name, e))
        
                else:
                    logging.info(f"Alarm state neither OK nor ALARM: {state_value}")
            else:
                logging.info("No tags matching criteria.")
    except Exception as e:
        logging.error(f"Listing tags failed with exception: {e}")
Leave a Comment