如何使用 Boto3 在 AWS Glue 資源中新增標籤


在本文中,我們將瞭解使用者如何新增 AWS Glue 資源中的標籤。

示例

在 AWS Glue 資料庫中新增標籤“glue-db: tests”。

問題陳述:使用 Python 中的 boto3 庫在 AWS Glue 資源中新增標籤。

解決此問題的方法/演算法

  • 步驟 1:匯入 boto3botocore 異常以處理異常。

  • 步驟 2:resource_arntags_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 庫建立 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 error in 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}}

更新於: 2021年4月15日

1K+ 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告