Notice
Recent Posts
Recent Comments
Link
투케이2K
223. (python/파이썬) [AWS] [Lambda] 런타임 Python 3.13 - boto3 모듈 사용해 GetCallerIdentity STS 임시 자격 유효성 검증 본문
Python
223. (python/파이썬) [AWS] [Lambda] 런타임 Python 3.13 - boto3 모듈 사용해 GetCallerIdentity STS 임시 자격 유효성 검증
투케이2K 2026. 1. 14. 20:58728x90
[개발 환경 설정]
개발 툴 : Aws / Lambda / Runtime Python 3.13
개발 언어 : python

[소스 코드]
// --------------------------------------------------------------------------------------
[개발 및 테스트 환경]
// --------------------------------------------------------------------------------------
- 언어 : Python
- 개발 툴 : Aws / Lambda / Runtime Python 3.13
- 개발 기술 : AWS Lambda 이벤트 동작 함수
- 사전) AWS Lambda 설명 :
>> Aws Lambda 는 서버 리스 FaaS 솔루션으로, 함수의 인스턴스를 실행하여 이벤트를 처리할 수 있습니다.
>> Aws Lambda 는 이벤트에 응답하여 코드를 실행 하고 해당 코드에 필요한 컴퓨팅 리소스를 자동으로 관리합니다.
- 사전) STS 임시 보안 자격 증명 설명 정리 :
>> AWS STS 는 AWS 리소스에 대한 액세스를 제어할 수 있는 임시 보안 자격 증명입니다 (신뢰받는 사용자에게 제공)
>> AWS STS 는 단기적 임시 보안 자격 증명이며, 몇 분에서 몇 시간 동안 해당 자격 증명을 사용해 AWS 리소스를 액세스할 수 있습니다
>> AWS STS 임시 보안 자격 증명이 만료 된 경우 AWS는 더는 그 자격 증명을 인식하지 못하거나 그 자격 증명을 사용한 API 요청으로부터 이루어지는 어떤 종류의 액세스도 허용하지 않습니다
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
[소스 코드]
// --------------------------------------------------------------------------------------
# ========================================================================
# [Aws] : [boto3 모듈] : STS 계정 정보 사용해 GetCallerIdentity STS 임시자격 증명 정보 유효성 검증
# ========================================================================
# [참고] : 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 STS 계정 AccessKey, SecretKey, SessionToken 변수 선언]
stsAccessKey = "AS..LR"
stsSecretKey = "hb..aC"
stsSessionToken = "Fwo..77O0="
# [명시적 인증 정보로 세션 생성]
session = boto3.Session(
aws_access_key_id=stsAccessKey,
aws_secret_access_key=stsSecretKey,
aws_session_token=stsSessionToken,
)
# [AWS 클라이언트 생성]
aws_client = session.client('sts')
try:
# ---------------------------------------------
# [STS 임시 자격 증명 유효성 검증]
# ---------------------------------------------
# ✅ [주요 에러 정리]
# ---------------------------------------------
# AccessDenied : 정책 혹은 권한 문제로 호출 실패. HTTP 403.
# InvalidClientTokenId : 제공된 토큰이 AWS 기록에 없거나 잘못된 경우.
# ExpiredToken : 세션 토큰이 만료된 경우. 예: "The security token included in the request is expired".
# IncompleteSignature : 요청 시그니처가 불완전하거나 서명 오류. HTTP 403.
# MissingAuthenticationToken : 인증 토큰이 누락된 경우. HTTP 403.
# RequestExpired : 요청 시간이 유효시간 초과된 경우. HTTP 400.
# InternalFailureAWS : 내부 오류로 인해 처리 실패. HTTP 500.
# ServiceUnavailable : 서비스 일시 중단 상태. HTTP 503.
# ---------------------------------------------
aws_res = aws_client.get_caller_identity()
print(f"DLOG = aws_res : {aws_res}")
# [리턴 변수 삽입] : ApiGateWay 응답 반환 설정 : Lambda 통합 요청 사용
response["statusCode"] = 200
response["headers"] = {
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*', # CORS 허용 (필요 시)
}
response["body"] = json.dumps({
"aws_res": aws_res
})
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
# ========================================================================
"""
Response:
{
"statusCode": 200,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
"body": "{\"aws_res\": {\"UserId\": \"AI..2S\", \"Account\": \"123456789012\", \"Arn\": \"arn:aws:iam::123456789012:user/2k@twok.com-CLI\", \"ResponseMetadata\": {\"RequestId\": \"8102c0c9-0411-4723-8eaf-c276f17466bd\", \"HTTPStatusCode\": 200, \"HTTPHeaders\": {\"x-amzn-requestid\": \"8102c0c9-0411-4723-8eaf-c276f17466bd\", \"x-amz-sts-extended-request-id\": \"MTphcC1ub3J0aGVhc3QtMTpTOjE3NjgyNjI2MjgyMzI6Ujp5Yk1BeXRRdQ==\", \"content-type\": \"text/xml\", \"content-length\": \"416\", \"date\": \"Tue, 13 Jan 2026 00:03:48 GMT\"}, \"RetryAttempts\": 0}}}"
}
"""
# ========================================================================
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
[참고 사이트]
// --------------------------------------------------------------------------------------
[Aws Security Token Service] Aws STS 임시 보안 자격 증명 설명 정리
https://kkh0977.tistory.com/7942
https://blog.naver.com/kkh0977/223846461194?trackingCode=blog_bloghome_searchlist
[AWS] [Lambda] 런타임 Python 3.13 - boto3 모듈 사용해 AWS STS 임시 정보 호출 람다 생성
https://blog.naver.com/kkh0977/223962739399?trackingCode=blog_bloghome_searchlist
[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
반응형
'Python' 카테고리의 다른 글
Comments
