Lambda 역활 신뢰 정책
더보기
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"edgelambda.amazonaws.com",
"lambda.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
Lambda 코드
이 코드는 S3 버킷 /frontend 폴더에 있는 이미지를 params로 받고
s3 presigned url로 반환하여 전송하는 코드입니다.
더보기
import json
import boto3
from urllib.parse import parse_qs
import datetime
import boto3
def lambda_handler(event, context):
cf_aws_region = '<CloudFront 리전>'
distribution_id = '<CloudFront 아이디>'
s3_aws_region = '<버킷 리전>'
bucket_name = '<버킷 이름>'
object_key = f'frontend/{img}' # 버킷 경로
# 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)
# S3 presigned URl 만들고 반환하기
s3 = boto3.client('s3', region_name=s3_aws_region)
query_string_parameters = event['Records'][0]['cf']['request']['querystring']
print("Query String Parameters:", query_string_parameters)
params = parse_qs(query_string_parameters)
print("Parsed Params:", params)
img = params.get('img', [None])[0]
print("Image Parameter:", img) # 이미지가 없다면
if not img:
return {
'statusCode': 400,
'body': 'Missing img query parameter',
'headers': {
'content-type': [{
'key': 'Content-Type',
'value': 'text/plain'
}]
}
}
presigned_url = s3.generate_presigned_url( # Presigned URL을 생성합니다.
'get_object',
Params={'Bucket': bucket_name, 'Key': object_key},
ExpiresIn=180 # 3분
)
print("Presigned URL:", presigned_url)
response = event['Records'][0]['cf']['response'] # response 객체를 수정합니다.
response['status'] = '302'
response['statusDescription'] = 'Found'
response['headers']['location'] = [{
'key': 'Location',
'value': presigned_url
}]
response['headers']['access-control-allow-origin'] = [{ # 필요한 CORS 헤더를 추가합니다.
'key': 'Access-Control-Allow-Origin',
'value': '*'
}]
response['headers']['access-control-allow-methods'] = [{ # 필요한 CORS 헤더를 추가합니다.
'key': 'Access-Control-Allow-Methods',
'value': 'GET, POST, PUT, OPTIONS, DELETE'
}]
response['headers']['access-control-allow-headers'] = [{ # 필요한 CORS 헤더를 추가합니다.
'key': 'Access-Control-Allow-Headers',
'value': '*'
}]
print("Modified Response:", response)
return response # 수정한 response 반환하기
CloudFront에서 "Legacy cache settings"를 선택해주세요.