如何使用 Boto3 从 AWS Glue 资源中删除标签

awsboto3pythonserver side programmingprogramming更新于 2023/12/24 18:29:00

在本文中,我们将了解如何从 AWS Glue 资源中删除标签。

示例

删除标签"glue-db: tests"在 AWS glue 数据库中。

 问题陈述:使用 Python 中的 boto3 库删除 AWS Glue 资源中的标签。

解决此问题的方法/算法

  • 步骤 1:导入 boto3botocore 异常来处理异常。

  • 步骤 2: resource_arntags_list 是此函数中必需的参数。

resource_arn 的格式应如下所示 −

Catalogarn:aws:glue:region:account-id:catalog
Databasearn:aws:glue:region:account-id:database/database name
Tablearn:aws:glue:region:account-id:table/database name/table name
Connectionarn:aws:glue:region:account-id:connection/connection name
Crawlerarn:aws:glue:region:account-id:crawler/crawler-name
Jobarn:aws:glue:region:account-id:job/job-name
Triggerarn:aws:glue:region:account-id:trigger/trigger-name
Development endpointarn:aws:glue:region:account-id:devEndpoint/development-endpoint-name
Machine learning transformarn:aws:glue:region:account-id:mlTransform/transform-id

tags_list 应为 [“key1,key2…]

  • 步骤 3:使用 boto3 lib 创建 AWS 会话。确保默认配置文件中提到了 region_name。如果没有提及,则在创建会话时明确传递 region_name

  • 步骤 4:glue 创建 AWS 客户端。

  • 步骤 5: 现在使用 untag_resource 函数并将参数 resource_arn 作为 ResourceArn 传递,将 tags_list 作为 TagsToRemove 传递。

  • 步骤 6: 它返回响应元数据并删除资源中的标签。

  • 步骤 7: 如果在删除标签时出现问题,处理通用异常。

示例代码

使用以下代码删除标签 −

import boto3
from botocore.exceptions import ClientError

def remove_tags_in_resource(resource_arn, tags_list)
   session = boto3.session.Session()
   glue_client = session.client('glue')
   try:
      response = glue_client.untag_resource(ResourceArn= resource_arn,TagsToRemove=tags_list)
      return response
   except ClientError as e:
      raise Exception("boto3 client error in remove_tags_in_resource: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in remove_tags_in_resource: " + e.__str__())
tags_dict = ["glue-db"]
print(remove_tags_in_resource("arn:aws:glue:us-east-1:1122225*****88:database/test- db",tags_list))

输出

{'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}}

相关文章