如何使用Python在Google Secret Manager中创建带标签的密钥?
在Google Secret Manager中用Python创建带标签的密钥
要创建带标签的密钥,只需在调用create_secret接口时,给secret参数添加labels字段(键值对格式的字典)即可。标签可用于分类、筛选密钥,方便后续管理。
修改创建密钥的函数(支持标签)
基于你提供的现有代码,修改后支持传入标签的函数如下:
from google.cloud import secretmanager def create_secret_with_labels(secret_id, labels): # 创建Secret Manager客户端 client = secretmanager.SecretManagerServiceClient() # 构建项目父资源名称 PROJECT_ID = "xxxx" parent = f"projects/{PROJECT_ID}" # 配置密钥参数:包含自动复制策略和自定义标签 secret = { 'replication': {'automatic': {}}, 'labels': labels # 新增标签字段 } # 创建带标签的密钥容器 response = client.create_secret(secret_id=secret_id, parent=parent, secret=secret) print(f'已创建带标签的密钥: {response.name}') return response
调用示例
定义标签字典(键值均为字符串),然后调用函数创建密钥:
# 定义标签,用于标识密钥的环境、所属服务等信息 secret_labels = { "environment": "production", "service": "cloud-run-app", "owner": "dev-team" } # 创建带标签的密钥 create_secret_with_labels("my-production-api-key", secret_labels)
给已存在的密钥更新标签
如果需要给已创建的密钥添加或更新标签,可使用update_secret接口:
def update_secret_labels(secret_id, new_labels): client = secretmanager.SecretManagerServiceClient() PROJECT_ID = "xxxx" secret_name = f"projects/{PROJECT_ID}/secrets/{secret_id}" # 获取当前密钥的元数据 secret = client.get_secret(name=secret_name) # 合并新标签到原有标签(若直接赋值会覆盖原有所有标签) secret.labels.update(new_labels) # 指定更新掩码,仅更新labels字段 update_mask = {"paths": ["labels"]} # 执行标签更新 updated_secret = client.update_secret(secret=secret, update_mask=update_mask) print(f'已更新密钥标签: {updated_secret.name}') return updated_secret
调用示例:
# 给已有密钥追加新标签 update_secret_labels("my-production-api-key", {"expiry-date": "2025-12-31"})
标签规则说明
标签的键值对需符合Google Cloud的命名规范:
- 键只能包含小写字母、数字、连字符(-)、下划线(_)和点(.),长度不超过63字符
- 值的格式限制与键类似,且不能为空字符串
内容的提问来源于stack exchange,提问作者Europa
相关产品推荐
相关产品推荐

