Create secret with label

Creates a new secret with label

Code sample

Python

To learn how to install and use the client library for Secret Manager, see Secret Manager client libraries.

To authenticate to Secret Manager, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.