람다 보안그룹 등록 :: 에버노트

ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 람다 보안그룹 등록
    카테고리 없음 2023. 6. 2. 17:11

    #ChatGPT 파이썬 짬

     

    ChatGPT — Release Notes | OpenAI Help Center

    The latest update for ChatGPT

    help.openai.com

     

    #설정

    google.com 질의 한 ip를 보안그룹에 등록 

     

    아웃바운드 tcp 443 등록

    보안그룹 아웃바운드 세분화하기 위해 코드를 구현함 

    import socket
    import boto3
    import botocore
    
    
    def get_ip_address(domain_name):
        try:
            ip_address = socket.gethostbyname(domain_name)
            return ip_address
        except socket.gaierror:
            return None
    
    
    def lambda_handler(event, context):
        # 도메인 설정
        domain = "example.com"
    
        # IP 주소 추출
        ip_address = get_ip_address(domain)
    
        # 보안 그룹에 IP 주소 및 포트 추가
        security_group_id = sg-aaaa"
        port = 443
    
        if ip_address and not is_ip_in_security_group(security_group_id, ip_address, port):
            add_ip_to_security_group(security_group_id, ip_address, port)
            print("보안 그룹에 IP 주소 {}의 포트 {}를 추가했습니다.".format(ip_address, port))
        else:
            print("보안 그룹에 IP 주소 {}의 포트 {}가 이미 등록되어 있습니다.".format(ip_address, port))
    
    
    def is_ip_in_security_group(security_group_id, ip_address, port):
        # AWS 클라이언트 생성
        ec2_client = boto3.client('ec2')
    
        # 보안 그룹 정보 가져오기
        response = ec2_client.describe_security_groups(GroupIds=[security_group_id])
        security_group = response['SecurityGroups'][0]
    
        # 보안 그룹의 아웃바운드 규칙 검사
        for permission in security_group['IpPermissionsEgress']:
            if (
                permission['IpProtocol'] == 'tcp' and
                permission['FromPort'] == port and
                {'CidrIp': '{}/32'.format(ip_address)} in permission['IpRanges']
            ):
                return True
    
        return False
    
    
    def add_ip_to_security_group(security_group_id, ip_address, port):
        # AWS 클라이언트 생성
        ec2_client = boto3.client('ec2')
    
        # 보안 그룹 업데이트
        ec2_client.authorize_security_group_egress(
            GroupId=security_group_id,
            IpPermissions=[
                {
                    'IpProtocol': 'tcp',
                    'FromPort': port,
                    'ToPort': port,
                    'IpRanges': [{'CidrIp': '{}/32'.format(ip_address)}]
                }
            ]
        )

    댓글

Designed by Tistory.