如何使用 Boto3 在指定的 AWS 密钥中添加标签

awsboto3pythonserver side programmingprogramming

问题陈述:使用 Python 中的 boto3 库在 AWS 密钥中添加标签。

解决此问题的方法/算法

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

  • 步骤 2: secret_locationtags_dict 是此函数中必需的参数。 tags_dict 应为 {“key”:”value”,..

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

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

  • 步骤 5: 现在使用 tag_resource 函数并将参数 secret_location 作为 SecretId 传递,将 tags_dict 作为标签传递。

  • 步骤 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}}

相关文章