Python

Lambda- UTM 서버 네트워크 확인 및 자동 라우팅 변경 스크립트

Neeson.lee 2023. 5. 15. 09:17
import boto3
import socket
from boto3.session import Session

host1 = "UTM1호기 ip"
host2 = "UTM2호기 ip"

region = "ap-northeast-2"
rt_id_1 = "rtb-id"
rt_id_2 = "rtb-id"


snstopic = "sns arnM"


def lambda_handler(event, context):
    failCount1 = 0
    failCount2 = 0

    # Checks failed ping counts for each UTM
    for i in range(0, 5):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)  # 1 Second Timeout
        response = sock.connect_ex((host1, 541))
        if response != 0:
            failCount1 += 1
        sock.close()
        
    for i in range(0, 5):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)  # 1 Second Timeout
        response = sock.connect_ex((host2, 541))
        if response != 0:
            failCount2 += 1
        sock.close()

    # Changes route table associations for affected subnets

    if failCount1 > 3:

        try:
            session = Session(region_name=region)
            ec2 = session.resource('ec2')
            rt = ec2.RouteTable(rt_id_1)
            for assoc_attr in rt.associations_attribute:
                assoc = ec2.RouteTableAssociation(assoc_attr['RouteTableAssociationId'])
                new_assoc = assoc.replace_subnet(DryRun=False, RouteTableId=rt_id_2)
                if assoc != None:
                    print("Troubled route table: " + rt_id_1 + " has been replaced with: " + rt_id_2)
                                    
        except Exception as e:
            print(e)
            pass

        # Publish to SNS topic

        sns = boto3.resource('sns')
        topic = sns.Topic(snstopic)
        response = topic.publish(
            Message='MYDATA UTM#1 is not working properly!',
            Subject='Alert: MYDATA UTM#1 Failure!'
        )

    elif failCount2 > 3:
        try:
            session = Session(region_name=region)
            ec2 = session.resource('ec2')
            rt = ec2.RouteTable(rt_id_2)
            for assoc_attr in rt.associations_attribute:
                assoc = ec2.RouteTableAssociation(assoc_attr['RouteTableAssociationId'])
                new_assoc = assoc.replace_subnet(DryRun=False, RouteTableId=rt_id_1)
                if assoc != None:
                    print("Troubled route table: " + rt_id_2 + " has been replaced with: " + rt_id_1)

        except Exception as e:
            print(e)
            pass

        # Publish to SNS topic

        sns = boto3.resource('sns')
        topic = sns.Topic(snstopic)
        response = topic.publish(
            Message='MYDATA UTM#2 is not working properly!',
            Subject='Alert: MYDATA UTM#2 Failure!'
        )
    return True