이 글에서는 AWS 계정에 존재하는 AWS Glue 크롤러(Crawler)의 스케줄러를 업데이트하는 방법을 살펴보겠습니다. Python의 boto3 라이브러리를 활용하면 별도의 콘솔 작업 없이 코드만으로 크롤러의 실행 일정을 손쉽게 변경할 수 있습니다.
문제 정의
Python에서 boto3 라이브러리를 사용하여 특정 크롤러의 스케줄러(실행 일정)를 업데이트하는 것이 목표입니다.
문제 해결 접근 방식
1단계: 예외 처리를 위해 boto3와 botocore.exceptions 모듈을 임포트합니다.
2단계: 함수에는 crawler_name(크롤러 이름)과 scheduler(스케줄) 두 가지 필수 파라미터가 필요합니다.
scheduler는 반드시
cron(cron_표현식)형식으로 작성해야 합니다. 예를 들어 cron 표현식을(15 12 * * ? *)로 지정하면 크롤러가 매일 UTC 기준 12시 15분에 실행됩니다.3단계: boto3 라이브러리로 AWS 세션을 생성합니다. 기본 프로필에 region_name이 설정되어 있지 않다면, 세션 생성 시 명시적으로 리전을 전달해야 합니다.
4단계: AWS Glue 서비스를 위한 클라이언트를 생성합니다.
5단계: update_crawler_schedule 함수를 호출하면서 crawler_name은 CrawlerName 파라미터로, scheduler는 Schedule 파라미터로 전달합니다.
6단계: 함수는 응답 메타데이터(ResponseMetadata)를 반환하고, 크롤러의 스케줄 상태를 성공적으로 갱신합니다.
7단계: 스케줄러 업데이트 과정에서 오류가 발생할 경우를 대비해 일반 예외(generic exception)까지 처리합니다.
예제 코드
아래 코드는 크롤러의 스케줄러를 업데이트하는 전체 예제입니다.
import boto3
from botocore.exceptions import ClientError
def update_scheduler_of_a_crawler(crawler_name, scheduler):
session = boto3.session.Session()
glue_client = session.client('glue')
try:
response = glue_client.update_crawler_schedule(
CrawlerName=crawler_name,
Schedule=scheduler
)
return response
except ClientError as e:
raise Exception("boto3 client error in update_scheduler_of_a_crawler: " + e.__str__())
except Exception as e:
raise Exception("Unexpected error in update_scheduler_of_a_crawler: " + e.__str__())
print(update_scheduler_of_a_crawler("Data Dimension", "cron(15 12 * * ? *)"))실행 결과
코드를 실행하면 아래와 같이 응답 메타데이터가 반환되며, 크롤러의 스케줄이 새로운 cron 표현식으로 업데이트됩니다.
{'ResponseMetadata': {'RequestId': '73e50130-*****************8e', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sun, 28 Mar 2021 07:26:55 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '2', 'connection': 'keep-alive', 'x-amzn-requestid': '73e50130-***************8e'}, 'RetryAttempts': 0}}정리
boto3의 update_crawler_schedule API를 사용하면 AWS Glue 데이터 카탈로그의 크롤러 실행 일정을 프로그래밍 방식으로 간편하게 관리할 수 있습니다. cron 표현식 형식만 올바르게 지정하면 매일, 매주 등 원하는 주기로 크롤링 작업을 자동화할 수 있습니다.