如何使用 Boto3 獲取 AWS Glue 資源的標籤


在本文中,我們將瞭解使用者如何獲取與 AWS Glue 資源關聯的標籤。

示例

從 AWS Glue 資料庫獲取標籤“glue-db: tests”。

問題陳述:使用 Python 中的 boto3 庫從 AWS Glue 資源獲取標籤。

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

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

  • 步驟 2:resource_arn 是此函式中所需的引數。

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
  • 步驟 3:使用 boto3 庫建立 AWS 會話。確保在預設配置檔案中提到了 region_name。如果未提及,則在建立會話時顯式傳遞 region_name

  • 步驟 4:glue 建立 AWS 客戶端。

  • 步驟 5:現在使用 get_tags 函式並將引數 resource_arn 作為 ResourceArn 傳遞。

  • 步驟 6:它返回資源的標籤和響應元資料。

  • 步驟 7:如果在獲取標籤時出現錯誤,則處理通用異常。

示例程式碼

使用以下程式碼獲取標籤:

import boto3
from botocore.exceptions import ClientError

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

輸出

{'Tags': {'glue-job': 'test'}, 'ResponseMetadata': {'RequestId': 'c9f418b0-8d02-4a26-*************', '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-8d02-4a26-**************'}, 'RetryAttempts': 0}}

更新於:2021年4月15日

1K+ 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.