如何使用Boto3在AWS Glue资源中添加标签
在本文中,我们将看到用户如何在AWS Glue资源中添加标签。
更多Python相关文章,请阅读:Python 教程
示例
在AWS Glue数据库中添加标签“ glue-db:tests ”。
问题陈述: 使用Python中的boto3库在AWS Glue资源中添加标记。
解决这个问题的方法/算法
- 步骤1: 导入 boto3 和 botocore 异常来处理异常。
-
步骤2: resource_arn和tags_dict是此函数中的所需参数。
resource_arn 的格式应如下所示−
| 目录 | arn:aws:glue:region:account-id:catalog |
|---|---|
| 数据库 | arn:aws:glue:region:account-id:database/database name |
| 表 | arn:aws:glue:region:account-id:table/database name/table name |
| 连接 | arn:aws:glue:region:account-id:connection/connection name |
| 爬虫 | arn:aws:glue:region:account-id:crawler/crawler-name |
| 作业 | arn:aws:glue:region:account-id:job/job-name |
| 触发器 | arn:aws:glue:region:account-id:trigger/trigger-name |
| 开发终端点 | arn:aws:glue:region:account-id:devEndpoint/development-endpoint-name |
| 机器学习变换 | arn:aws:glue:region:account-id:mlTransform/transform-id |
tags_dict 应为{“key”:“value”,..}。
- 步骤3: 使用 boto3 lib 创建AWS会话。确保在默认配置文件中提供了 region_name 。如果没有提供,则在创建会话时显式传递 region_name 。
-
步骤4: 为 glue 创建AWS客户端。
-
步骤5: 现在使用 tag_resource 函数,并将参数 resource_arn 作为ResourceArn和 tags_dict 作为TagsToAdd传递。
-
步骤6: 它返回响应元数据并在资源中添加标记。
-
步骤7: 如果在添加标记时出现问题,请处理通用异常。
示例代码
使用以下代码添加标记−
import boto3
from botocore.exceptions import ClientError
def add_tags_in_resource(resource_arn, tags_dict)
session = boto3.session.Session()
glue_client = session.client('glue')
try:
response = glue_client.tag_resource(ResourceArn= resource_arn,TagsToAdd=tags_dict)
return response
except ClientError as e:
raise Exception("boto3 client error in add_tags_in_resource: " + e.__str__())
except Exception as e:
raise Exception("Unexpected错误在add_tags_in_resource中:" + e.__str__())
tags_dict = {"glue-db":"test"}
print(add_tags_in_resource("arn:aws:glue:us-east-1:1122225*****88:database/test- db",tags_dict))
输出
{'ResponseMetadata': {'RequestId': 'c9f418b0-***************-fb96', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Fri, 02 Apr 2021 08:04:54 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '27', 'connection': 'keep-alive', 'x-amzn-requestid': 'c9f418b0-******************-fb96'}, 'RetryAttempts': 0}}
极客教程