투케이2K

227. (python/파이썬) [AWS] [Lambda] 런타임 Python 3.13 - boto3 모듈 사용해 GetBucketCors S3 특정 버킷 CORS 규칙 조회 본문

Python

227. (python/파이썬) [AWS] [Lambda] 런타임 Python 3.13 - boto3 모듈 사용해 GetBucketCors S3 특정 버킷 CORS 규칙 조회

투케이2K 2026. 2. 7. 18:53
728x90

[개발 환경 설정]

개발 툴 : Aws / Lambda / Runtime Python 3.13

개발 언어 : python

 

[소스 코드]

 

// --------------------------------------------------------------------------------------
[개발 및 테스트 환경]
// --------------------------------------------------------------------------------------

- 언어 : Python


- 개발 툴 : Aws / Lambda / Runtime Python 3.13


- 개발 기술 : AWS Lambda 이벤트 동작 함수


- 사전) AWS Lambda 설명 : 

  >> Aws Lambda 는 서버 리스 FaaS 솔루션으로, 함수의 인스턴스를 실행하여 이벤트를 처리할 수 있습니다.

  >> Aws Lambda 는 이벤트에 응답하여 코드를 실행 하고 해당 코드에 필요한 컴퓨팅 리소스를 자동으로 관리합니다.


- 사전) S3 개념 정리 : 

  >> AWS S3 (Amazon Simple Storage Service) 는 AWS 에서 제공하는 객체 스토리지 서비스로, 인터넷을 통해 데이터를 저장하고 검색할 수 있도록 설계되었습니다

  >> 기본 용어 정리 : 

    - 객체(Object): S3에 저장되는 데이터 단위. 파일과 메타데이터로 구성됩니다

    - 버킷(Bucket): 객체를 저장하는 컨테이너. S3에서 데이터를 저장하려면 먼저 버킷을 생성해야 합니다

    - 키(Key): 객체를 식별하는 고유한 이름. 버킷 내에서 객체를 구분하는 데 사용됩니다

// --------------------------------------------------------------------------------------






// --------------------------------------------------------------------------------------
[소스 코드]
// --------------------------------------------------------------------------------------

# ========================================================================
# [Aws] : [boto3 모듈] : IAM 계정 정보 사용해 GetBucketCors S3 특정 버킷 CORS 규칙 조회
# ========================================================================
# [참고] : API Gateway 와 연동 되어 Post 방식으로 Lambda 함수 호출 및 응답 값 반환 수행
# ========================================================================
"""
1. aws lambda python 3.13 런타임 환경 기반
2. boto3 모듈 기본 내장 AWS 사용 모듈
3. import ClientError : AWS SDK for Python 인 boto3 에서 발생할 수 있는 예외 중 하나로, AWS 서비스 호출 중 오류가 발생했을 때 사용됩니다
"""
# ========================================================================

import json
import os

import boto3
from botocore.exceptions import ClientError
from decimal import Decimal

def lambda_handler(event, context): # Lambda 호출 시 동작 되는 메인 함수

    # [event , context 정보 디버깅 로그 출력]
    print(f"DLOG = event : {event} / context {context}")


    # [Return 반환 Json 변수 선언]
    response = {
        "statusCode" : 0,
        "headers" : {},
        "body" : ""
    }


    # [AWS IAM 계정 AccessKey, SecretKey 변수 선언]
    iamAccessKey = "AK..7Q"
    iamSecretKey = "Zz..xj"
    iamRegion = "ap-northeast-2"  # 서울 리전


    # [명시적 인증 정보로 세션 생성]
    session = boto3.Session(
        aws_access_key_id=iamAccessKey,
        aws_secret_access_key=iamSecretKey,
        region_name = iamRegion
    )


    # [AWS 클라이언트 생성]
    aws_client = session.client('s3')

    
    try:

      # ---------------------------------------------
      # ✅ [주요 에러 정리]
      # ---------------------------------------------
      # >> InvalidAccessPointAliasError : Access point 또는 Object Lambda Access Point alias가 잘못된 값인 경우 발생
      # >> AccessDenied : 호출 주체(IAM User/Role)에 s3:GetBucketCORS 권한이 없는 경우      
      # >> NoSuchCORSConfiguration : 버킷에 CORS 설정이 전혀 존재하지 않을 때 발생      
      # >> URI/Parameter Errors (URL Encoding 이슈) : 인코딩이 올바르지 않으면 요청이 거부될 수 있음
      # ---------------------------------------------


      # [요청 파라미터 생성]
      bucket = 'service'
      

      # [요청 수행]
      aws_res = aws_client.get_bucket_cors(Bucket=bucket)

      print(f"DLOG = aws_res : {aws_res}")      


      # [응답 데이터 파싱]
      cors_rules = aws_res.get("CORSRules", [])


      # [리턴 변수 삽입] : ApiGateWay 응답 반환 설정 : Lambda 통합 요청 사용
      response["statusCode"] = 200 
      response["headers"] = {
        "Content-Type": "application/json",
        'Access-Control-Allow-Origin': '*',  # CORS 허용 (필요 시)
      }
      response["body"] = json.dumps({        
        "bucket": bucket,
        "corsRules": cors_rules
      })
        
    except ClientError as e: # AWS 서비스 호출 중 오류 발생 처리
        error_code = e.response['Error']['Code']
        error_message = e.response['Error']['Message']

        # [리턴 변수 삽입]
        response["statusCode"] = 400
        response["headers"] = {
          "Content-Type": "application/json",
          'Access-Control-Allow-Origin': '*',  # CORS 허용 (필요 시)
        }
        response["body"] = json.dumps(
          {
            "exception" : "ClientError",
            "error_code" : error_code,
            "error_message" : error_message
          }
        )


    # [리턴 반환 수행]
    return response

# ========================================================================
"""
{
  "statusCode": 200,
  "headers": {
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*"
  },
  "body": "{\"bucket\": \"service\", \"corsRules\": [{\"AllowedHeaders\": [\"*\"], \"AllowedMethods\": [\"GET\"], \"AllowedOrigins\": [\"*\"], \"ExposeHeaders\": [\"ETag\", \"x-amz-meta-custom-header\"]}]}"
}
"""
# ========================================================================

// --------------------------------------------------------------------------------------






// --------------------------------------------------------------------------------------
[참고 사이트]
// --------------------------------------------------------------------------------------

[Aws S3 Storage] AWS S3 특정 버킷 CORS (Cross-Origin) 규칙 조회 GetBucketCors API 설명 정리

https://kkh0977.tistory.com/8611

https://blog.naver.com/kkh0977/224173109886


[Amazon API Gateway] Aws API Gateway 게이트웨이 설명 정리 - 중개 서버

https://blog.naver.com/kkh0977/223827753479


[Amazon API Gateway] Aws API Gateway 게이트웨이 API 엔드포인트 유형 정리

https://blog.naver.com/kkh0977/223911565693


[Aws Lambda] Aws 사이트에서 생성 된 Lambda 람다 검증 함수 리스트 및 내용 소스 코드 확인 방법

https://blog.naver.com/kkh0977/223765198383


[AWS] Lambda 람다 함수 수행 errorType Sandbox.Timedout 에러 발생

https://blog.naver.com/kkh0977/223962778768

// --------------------------------------------------------------------------------------
 
728x90
반응형
Comments