Aws

S3에서 이벤트 발생시 람다를 이용해서 CloudFront 무효화 하기

wngnl-dev 2024. 4. 13. 20:11
import datetime
import boto3

def lambda_handler(event, context):

    aws_region = '<리전 이름>'
    distribution_id = '<CloudFront ID>'
    
    # CloudfRont 무효화
    paths_to_invalidate = ['/*']  # 무효화 경로
    cf_client = boto3.client('cloudfront', region_name=cf_aws_region)
    korea_time = datetime.datetime.now() + datetime.timedelta(hours=9)
    korea_time_str = korea_time.strftime("%Y-%m-%d %H:%M:%S")
    
    # 원본 무효화 요청 생성
    invalidation_response = cf_client.create_invalidation( 
        DistributionId=distribution_id,
        InvalidationBatch={
            'Paths': {
                'Quantity': len(paths_to_invalidate),
                'Items': paths_to_invalidate
            },
            'CallerReference': korea_time_str  # 고유한 무효화 참조값 ( 한국 시간 )
        }
    )
    print("Invalidation response:", invalidation_response)

위의 코드를 사용하면 람다를 실행했을때 CloudFront를 무효화 경로를 바탕으로 무효화를 실행 합니다

 

 

람다 Trigger를 이용해서 S3에 이벤트 발생시 코드를 실행할 수도 있습니다.

 

S3에 파일 이 업로드 되었을때

더보기

Event Types : All object create events

Prefix : 폴더 경로

Suffix : "파일 이름" OR "파일 확장자"  // "test" OR ".csv"

 

S3에 파일 이 복사 되었을때

더보기

Event Types : COPY

Prefix : 폴더 경로

Suffix : "파일 이름" OR "파일 확장자"  // "test" OR ".csv"

 

S3에 파일 이 삭제 되었을때

더보기

Event Types :  All object delete events

Prefix : 폴더 경로

Suffix : "파일 이름" OR "파일 확장자"  // "test" OR ".csv"