如何使用 Boto3 检查 Glue Job 是否存在?
boto3pythonserver side programmingprogramming
问题描述 − 使用 Python 中的 boto3 库检查 Glue Job 是否存在。例如,检查 AWS Glue 中是否存在 run_s3_file_job。
解决此问题的方法/算法
步骤 1 − 导入 boto3 和 botocore 异常来处理异常。
步骤 2 − job_name 是函数中的参数。
步骤 3 − 使用 boto3 库创建 AWS 会话。确保默认配置文件中提到了 region_name。如果没有提及,则在创建会话时明确传递 region_name。
步骤 4 − 为 glue 创建 AWS 客户端。
步骤 5 − 现在使用 get_job 函数并传递 JobName。
步骤 6 − 如果作业存在,响应将包含有关该作业的所有详细信息,否则将引发异常。
步骤 7 − 如果检查作业时出现问题,则处理通用异常。
示例
使用以下代码检查 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__()) #To check existing job print(check_glue_job_exists("run_s3_file_job")) #Job doesn’t exist print(check_glue_job_exists("run_s3_file_job_not_exist"))
输出
#To check existing job {'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}} #Job doesn’t exist botocore.errorfactory.EntityNotFoundException: An error occurred (EntityNotFoundException) when calling the GetJob operation: Job with name: run_s3_file_job_not_exist not found.