如何使用 Boto3 為指定的 AWS Secrets 新增標籤


問題陳述: 使用 Python 中的 boto3 庫為 AWS Secret 新增標籤。

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

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

  • 步驟 2: secret_locationtags_dict 是此函式所需的必需引數。tags_dict 應為 {“key”:”value”,..} 的格式。

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

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

  • 步驟 5: 現在使用 tag_resource 函式並將引數 secret_location 作為 SecretId 和 tags_dict 作為 Tags 傳遞。

  • 步驟 6: 它返回響應元資料並在資源中新增標籤。

  • 步驟 7: 如果在新增標籤時出現問題,則處理通用異常。

示例程式碼

使用以下程式碼新增標籤:

import boto3
from botocore.exceptions import ClientError

def add_tags_in_resource(secret_location, tags_dict)
   session = boto3.session.Session()
   client = session.client('secretmanager')
   try:
      response = client.tag_resource(SecretId= secret_location,Tags=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 = [{"Key":"secret-test","Value":"test"}]
print(add_tags_in_resource("secrets/aws",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月16日

749 次檢視

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.