如何使用Boto3检查Glue作业是否存在?
问题描述 − 使用Python中的boto3库检查Glue作业是否存在。例如,检查AWS Glue是否存在 run_s3_file_job 。
更多Python相关文章,请阅读:Python 教程
解决此问题的方法/算法
第 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__())
#检查现有的工作
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 withname: run_s3_file_job_not_exist not found.
极客教程