如何使用Boto3在指定的AWS Secrets中添加标签
问题陈述: 使用Python中的 boto3 库在AWS Secrets中添加标签。
更多Python相关文章,请阅读:Python 教程
解决此问题的方法/算法
- 步骤1: 导入 boto3 和 botocore 异常以处理异常。
-
步骤2: 此函数中需要 secret_location 和 tags_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}}
极客教程