创建带有标签的 Secret

创建带有标签的新 Secret

代码示例

Python

如需了解如何安装和使用 Secret Manager 客户端库,请参阅 Secret Manager 客户端库

如需向 Secret Manager 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import argparse
import typing

# Import the Secret Manager client library.
from google.cloud import secretmanager


def create_secret_with_labels(
    project_id: str,
    secret_id: str,
    labels: typing.Dict[str, str],
    ttl: typing.Optional[str] = None,
) -> secretmanager.Secret:
    """
    Create a new secret with the given name. A secret is a logical wrapper
    around a collection of secret versions. Secret versions hold the actual
    secret material.
    """

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the parent project.
    parent = f"projects/{project_id}"

    # Create the secret.
    response = client.create_secret(
        request={
            "parent": parent,
            "secret_id": secret_id,
            "secret": {"replication": {"automatic": {}}, "ttl": ttl, "labels": labels},
        }
    )

    # Print the new secret name.
    print(f"Created secret: {response.name}")

    return response

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器