import json import socket import boto3 import logging logger = logging.getLogger() logger.setLevel(logging.INFO) def lambda_handler(event, context): hosts=['10.129.72.63', '10.135.72.66', '10.129.72.64', '10.135.72.67'] port=636 timeout_seconds=3 test_results = 0 metric_value = 0 for host in hosts: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout_seconds) result = sock.connect_ex((host,int(port))) if result == 0: logger.info("Host {}:{} - Up".format(host, port)) test_results += 1 metric_value = 1 else: logger.error("Host {}:{} - Down".format(host, port)) metric_value = 0 sock.close() logger.info("Publishing cloudwatch metric...") cloudwatch = boto3.client('cloudwatch') try: response = cloudwatch.put_metric_data( MetricData=[ { 'MetricName': 'Ldap Tcp Test', 'Dimensions': [ { 'Name': 'LdapHost', 'Value': host } ], 'Unit': 'None', 'Value': metric_value }, ], Namespace='Custom/Lambda' ) logger.info("Successfully published cloudwatch metric") # logger.info(response) except Exception as e: logger.error("Error publishing cloudwatch metric: {}".format(str(e))) if test_results == 4: return { 'message' : 'Successfully connected to all LDAP servers' } else: raise Exception('Not all LDAP servers can be connected!') return { 'statusCode': 200, 'body': json.dumps("Finished") }