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

Boto3로 AWS Glue 작업(Job) 존재 여부 확인하기

문제 상황

Python의 boto3 라이브러리를 사용하여 AWS Glue에 특정 Glue 작업이 존재하는지 확인해야 합니다. 예를 들어, run_s3_file_job이라는 이름의 작업이 AWS Glue에 등록되어 있는지 검사한다고 가정해 보겠습니다.

해결 접근 방식 및 알고리즘

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

2단계 – 함수의 매개변수로 job_name(작업 이름)을 받습니다.

3단계 – boto3 라이브러리를 사용하여 AWS 세션을 생성합니다. 기본 프로필에 region_name이 설정되어 있어야 하며, 설정되어 있지 않다면 세션 생성 시 region_name을 명시적으로 전달해야 합니다.

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

5단계get_job 함수를 호출하고 JobName 파라미터를 전달합니다.

6단계 – 작업이 존재하면 응답에 해당 작업의 모든 세부 정보가 포함되어 반환되고, 존재하지 않으면 예외가 발생합니다.

7단계 – 작업 확인 과정에서 문제가 발생했을 경우를 대비해 일반 예외(generic exception)도 함께 처리합니다.

예제 코드

아래 코드를 사용하면 Glue 작업의 존재 여부를 확인할 수 있습니다.

import boto3
from botocore.exceptions import ClientError

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

#존재하는 작업 확인
print(check_glue_job_exists("run_s3_file_job"))
#존재하지 않는 작업 확인
print(check_glue_job_exists("run_s3_file_job_not_exist"))

실행 결과

#존재하는 작업 확인 시
{'Job': {'Name': 'run_s3_file_job', 'Description': 'Glue job for the
test', 'Role': 'arn:aws:iam::12345:role/delegated/glue-service-role',
'CreatedOn': datetime.datetime(2021, 02, 10, 15, 7, 3, 638000,
tzinfo=tzlocal()), 'LastModifiedOn': datetime.datetime(2021, 02, 10, 15,
7, 3, 638000, tzinfo=tzlocal()), 'ExecutionProperty':
{'MaxConcurrentRuns': 1}, 'Command': {'Name': 'glueetl',
'ScriptLocation': 's3://test/pipeline.py', 'PythonVersion': '3'},
'DefaultArguments': {'--job-language': 'python', 'Step': '0'},
'MaxRetries': 0, 'AllocatedCapacity': 4, 'Timeout': 2880, 'MaxCapacity':
4.0, 'WorkerType': 'G.1X', 'NumberOfWorkers': 4, 'GlueVersion': '2.0'},
'ResponseMetadata': {'RequestId': 'e3ec9e2c-e75d-4443-bfeafef674fff7e9',
'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sat, 13 Feb 2021
13:20:27 GMT', 'content-type': 'application/x-amz-json-1.1',
'content-length': '1501', 'connection': 'keep-alive',
'x-amznrequestid': 'e3ec9e2c-e75d-4443-bfea-fef674fff7e9'},
'RetryAttempts': 0}}

#존재하지 않는 작업 확인 시
botocore.errorfactory.EntityNotFoundException: An error occurred
(EntityNotFoundException) when calling the GetJob operation: Job with
name: run_s3_file_job_not_exist not found.