Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Boto3로 AWS Glue 데이터 카탈로그의 모든 분류자(Classifier) 세부 정보 조회하기

문제 상황

Python의 boto3 라이브러리를 사용하여 AWS Glue 데이터 카탈로그에 등록된 모든 분류자(Classifier)의 세부 정보를 조회하는 방법을 알아보겠습니다. 예를 들어, 사용자 계정에 존재하는 전체 분류자 목록과 각 분류자의 상세 정보를 한 번에 가져오는 것이 목표입니다.

해결 접근 방식 및 알고리즘

1단계 – 예외 처리를 위해 boto3와 botocore의 예외 모듈을 임포트합니다.

2단계 – 이 작업에는 별도의 요청 파라미터가 필요하지 않습니다.

3단계 – boto3 라이브러리로 AWS 세션을 생성합니다. 기본 프로필(default profile)에 region_name이 설정되어 있는지 확인하세요. 만약 설정되어 있지 않다면, 세션 생성 시 region_name을 명시적으로 전달해야 합니다.

4단계 – AWS Glue 서비스를 위한 클라이언트를 생성합니다.

5단계 – 클라이언트의 get_classifiers() 메서드를 호출합니다.

6단계 – 해당 호출은 AWS Glue 데이터 카탈로그에 존재하는 모든 분류자의 세부 정보를 반환합니다.

7단계 – 작업 실행 중 오류가 발생할 경우를 대비해 일반 예외(generic exception) 처리 로직을 추가합니다.

코드 예제

다음 코드를 사용하면 AWS Glue 데이터 카탈로그의 모든 분류자 세부 정보를 조회할 수 있습니다.

import boto3
from botocore.exceptions import ClientError

def get_all_classifier_details():
    session = boto3.session.Session()
    glue_client = session.client('glue')
    try:
        response = glue_client.get_classifiers()
        return response
    except ClientError as e:
        raise Exception("boto3 client error in get_all_classifier_details: " + e.__str__())
    except Exception as e:
        raise Exception("Unexpected error in get_all_classifier_details: " + e.__str__())

print(get_all_classifier_details())

실행 결과

위 코드를 실행하면 XMLClassifier, GrokClassifier, CsvClassifier 등 다양한 유형의 분류자 정보가 딕셔너리 형태로 반환됩니다. 각 분류자 항목에는 이름(Name), 분류 유형(Classification), 생성 시간(CreationTime), 마지막 업데이트 시간(LastUpdated), 버전(Version) 등의 메타데이터가 포함되어 있습니다.

{'Classifiers': [
{'XMLClassifier': {'Name': 'aiml-linkup', 'Classification': 'xml',
'CreationTime': datetime.datetime(2020, 4, 17, 13, 26, 50,
tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2020, 4, 17, 13, 26,
50, tzinfo=tzlocal()), 'Version': 1, 'RowTag': 'job'}},
{'XMLClassifier': {'Name': 'aiml-test1', 'Classification': 'xml',
'CreationTime': datetime.datetime(2019, 10, 7, 20, 48, 44,
tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2019, 10, 7, 20, 48,
44, tzinfo=tzlocal()), 'Version': 1, 'RowTag': 'nitf'}},
{'GrokClassifier': {'Name': 'classifier1', 'Classification':
'classifier1', 'CreationTime': datetime.datetime(2018, 6, 21, 4, 7, 4,
tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2018, 6, 21, 4, 7,
11, tzinfo=tzlocal()), 'Version': 2, 'GrokPattern': 'SYSLOGTIMESTAMP
%{MONTH} +%{MONTHDAY} %{TIME}'}}, {'CsvClassifier': {'Name': 'csvquotes',
'CreationTime': datetime.datetime(2020, 9, 10, 5, 6, 29,
tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2020, 9, 10, 5, 6,
29, tzinfo=tzlocal()), 'Version': 1, 'Delimiter': ',', 'QuoteSymbol':
'"', 'ContainsHeader': 'UNKNOWN', 'DisableValueTrimming': False,
'AllowSingleColumn': False}},
{'XMLClassifier': {'Name': 'xml-test', 'Classification': 'xml',
'CreationTime': datetime.datetime(2020, 4, 10, 18, 26, 50,
tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2020, 4, 15, 0, 3,
8, tzinfo=tzlocal()), 'Version': 2, 'RowTag': 'job'}}],
'ResponseMetadata': {'RequestId': '7fa7a78e-…………e4261bfd1',
'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sun, 21 Feb 2021
08:02:30 GMT', 'content-type': 'application/x-amz-json-1.1',
'contentlength': '885', 'connection': 'keep-alive', 'x-amzn-requestid':
'7fa7a78e-………………..e4261bfd1'}, 'RetryAttempts': 0}}

정리

boto3의 get_classifiers() API는 단 한 번의 호출로 계정 내 모든 분류자 정보를 손쉽게 조회할 수 있는 강력한 도구입니다. 반환된 결과에는 XML, Grok, CSV 등 다양한 유형의 분류자가 포함될 수 있으며, 각 분류자의 구성 세부 사항과 응답 메타데이터(HTTP 상태 코드, 요청 ID 등)까지 함께 제공되므로 데이터 카탈로그 관리 및 자동화 스크립트 작성에 매우 유용하게 활용할 수 있습니다.