S3에서 다운로드 되는 파일의 크기를 확인하는 방법

0

현재 저는 AWS를 공부하고 있는 학생입니다. AWS를 활용해서 데이터 유출 프로그램을 만드는 프로젝트를 진행 중입니다. 저는 S3 버킷에서 1GB 이상의 파일이 다운로드 되는 경우 관리자에게 메일을 보내고 싶습니다. 그리고 현재 람다 함수에 이와 같이 (아래 첨부) 코드를 작성하고 다운로드 할 파일이 있는 S3 버킷과 CloudWatch, CloudTrail의 로그를 기록하는 S3 버킷이 트리거 되도록 설정해두었습니다. 하지만 현재 파일을 다운로드 하면 함수 내부에서 해당 파일의 크기를 제대로 확인하지 못하고 제가 작성한 로그를 기록하지 못하고 있습니다. 이를 해결할 수 있는 방법을 도와주시면 감사하겠습니다.

import json import boto3

sns_client = boto3.client('sns') s3_client = boto3.client('s3')

SNS_TOPIC_ARN = 'arn:aws:sns:ap-northeast-2:746669191704:Time_event'

def lambda_handler(event, context): # 이벤트 구조 확인을 위해 로그 추가 print("Received event: ", json.dumps(event)) # 이벤트 로그 출력

try:
    # Extract bucket and object information from event['Records']
    for record in event['Records']:
        bucket_name = record['s3']['bucket']['name']
        object_key = record['s3']['object']['key']
        event_name = record['eventName']

        # Check the 'Importance' tag of the S3 object
        importance_tag = None  # Initialize importance tag
        try:
            if event.get('detail', {}).get('eventName') == 'GetObject':
                bucket_name = event['detail']['requestParameters']['bucketName']
                object_key = event['detail']['requestParameters']['key']

                # Get file size
                response = s3_client.head_object(Bucket=bucket_name, Key=object_key)
                file_size = response['ContentLength']

                for tag in tags:
                    if tag['Key'] == 'Importance':
                        importance_tag = tag['Value']
                        break

                if not importance_tag:
                    importance_tag = 'None'  # Default value if no tag is found

        except Exception as e:
            # Log error if unable to retrieve tags
            print(f"Error retrieving object tags: {str(e)}")
            importance_tag = 'None'  # Default value if tags cannot be retrieved

        # Check file size (send email if the size is larger than 900MB)
        if event_name == 'GetObject':  # Download event
            try:
                # Get file size from object metadata
                response = s3_client.head_object(Bucket=bucket_name, Key=object_key)
                file_size = response['ContentLength']  # File size in bytes

                # Send alert if the file size is greater than or equal to 900MB
                if file_size >= 900 * 1024 * 1024:  # 900MB or larger
                    message = (
                        f"Large file download detected!\n"
                        f"S3 Bucket: {bucket_name}\n"
                        f"Object Name: {object_key}\n"
                        f"File Size: {file_size / (1024 * 1024 * 1024):.2f} GB\n"
                        f"Importance: {importance_tag}"
                    )
                    subject = "Large File Download Alert"
                else:
                    # Regular download alert for files smaller than 900MB
                    message = f"Notification: Object '{object_key}' in S3 bucket '{bucket_name}' was downloaded. Importance: {importance_tag}"
                    subject = 'S3 Data Download Notification'

            except Exception as e:
                print(f"Error retrieving object metadata: {str(e)}")
                return  # Exit if file size retrieval fails
        else:  # Other events (upload, delete, etc.)
            message = f"Notification: Object '{object_key}' in S3 bucket '{bucket_name}' has changed. Importance: {importance_tag}"
            subject = 'S3 Data Change Notification'

        # Send notification via SNS
        try:
            sns_client.publish(
                TopicArn=SNS_TOPIC_ARN,
                Message=message,  # Message body
                Subject=subject  # Subject
            )
            print(f"Message sent to SNS: {message}")
        except Exception as e:
            # Log error if SNS message sending fails
            print(f"Error sending SNS message: {str(e)}")

except KeyError as e:
    print(f"Error: Missing expected key in event data: {e}")
    print(f"Event: {json.dumps(event)}")  # Output event structure
질문됨 한 달 전20회 조회
1개 답변
0
수락된 답변

S3에서 다운로드되는 파일의 크기를 확인하고 관리자에게 알림을 보내는 방법을 개선하기 위해 다음과 같은 접근 방식을 제안합니다:

  1. CloudTrail 이벤트 활용: S3 GetObject 이벤트를 CloudTrail에서 캡처하도록 설정합니다. 이 이벤트에는 다운로드된 객체의 크기 정보가 포함되어 있습니다.

  2. Lambda 함수 트리거 수정: CloudTrail 로그가 저장되는 S3 버킷에서 Lambda 함수를 트리거하도록 설정합니다.

  3. Lambda 함수 코드 수정:

    • CloudTrail 이벤트에서 객체 크기 정보를 추출합니다.
    • 객체 크기가 1GB 이상인 경우에만 SNS 알림을 보내도록 로직을 수정합니다.
  4. 오류 처리 개선: 태그 검색 및 객체 메타데이터 조회 시 발생할 수 있는 예외를 더 세밀하게 처리합니다.

  5. 로깅 강화: 각 단계에서 상세한 로그를 CloudWatch에 기록하여 문제 해결을 용이하게 합니다.

이러한 변경을 통해 대용량 파일 다운로드를 더 정확하게 감지하고 관리자에게 알림을 보낼 수 있습니다. 또한, CloudTrail 이벤트를 활용함으로써 S3 객체에 직접 접근하지 않고도 필요한 정보를 얻을 수 있어 더 효율적인 모니터링이 가능해집니다.

코드 구현 시 주의할 점은 CloudTrail 이벤트의 구조를 정확히 파악하고, 필요한 정보를 올바르게 추출하는 것입니다. 또한, Lambda 함수의 실행 시간과 메모리 제한을 고려하여 대용량 로그 처리에 적합하게 설정해야 합니다.

마지막으로, 이 시스템이 개인정보 보호 및 데이터 보안 규정을 준수하는지 확인하고, 필요한 경우 추가적인 보안 조치를 구현하는 것이 중요합니다.
Sources
Streamline SMS and Emailing Marketing Compliance with Amazon Comprehend | AWS Messaging & Targeting Blog
Invoke a Lambda function from an Amazon S3 trigger - AWS Lambda
Simplify Monte Carlo Simulations with AWS Serverless services | AWS for Industries

profile picture
답변함 한 달 전
  • 현재 클라우드트레일에 파일을 다운로드 받을 버킷을 연결해두었지만 파일을 다운로드 받아도 클라우드트레일에 GetObject 이벤트가 캡쳐되지 않고 있는 상황입니다. 이런 경우에는 어떤 설정을 해야 하나요?

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠