def lambda_handler()

in lambda_function_code/dashboard_connection.py [0:0]


def lambda_handler(event, context):
    """This is the main handler. It will be called with a payload
    specifying if it needs to configure the eventbus resource policy
    or if it has to create rolues to forward events

    Its task is to properly configure the source/destination of metrics-related
    events, using info in the parameter store.

    Example structure of the parameter store

    Name=/monitors/MonitorName Value=123456789123
    Name=/monitored_projects/ProjectName/CustomTag Value=987654321987

    CustomTag can be used when a project has more than one account (e.g. dev/int/prod)

    Args:
        event (dict): the payload received for this execution
        context: the execution context
    """

    logger.info("Starting invocation with payload:")
    logger.info(json.dumps(event))

    eb_put = event["action"] == "EBPut"

    monitors = ssm_client.get_parameters_by_path(Path="/monitors/", Recursive=True)[
        "Parameters"
    ]
    monitored_projects = ssm_client.get_parameters_by_path(
        Path="/monitored_projects/", Recursive=True
    )["Parameters"]

    monitors = flatten_parameters(monitors)
    monitored_projects = flatten_parameters(monitored_projects)

    # this means we are serving as monitored_project
    for account_id, project_name in monitors.items():

        logger.info(f"Connecting to monitor {project_name} in account {account_id}")

        event_pattern = {
            "source": ["metric_extractor"],
            "detail-type": ["metric_extractor"],
        }

        if eb_put:
            # allow monitor to send us events
            allow_event_puts(account_id)
        else:
            # forward our metrics to monitor
            forward_events(account_id, event_pattern, "MetricValues")

    # this means we are serving as monitor
    for account_id, project_name in monitored_projects.items():

        logger.info(
            f"Connecting to monitored project {project_name} in account {account_id}"
        )

        event_pattern = {
            "source": ["metric_fetch"],
            "detail-type": ["metric_fetch"],
        }

        if eb_put:
            # allow monitored_project to send us events
            allow_event_puts(account_id)
        else:
            # send requests to fetch new data to monitored_projects
            forward_events(account_id, event_pattern, "FetchData")