Create a secret

This page describes how to create a secret. A secret contains one or more secret versions, alongwith metadata such as labels and replication policies. The actual contents of a secret are storedin asecret version.

Important: To use Secret Manager with workloads running on Compute Engine or Google Kubernetes Engine, the underlying instance or node must have thecloud-platform OAuth scope. Seeaccessing the Secret Manager API for more information.

Before you begin

  1. Enable the Secret Manager API.

  2. Set up authentication.

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

    In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, aCloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

    REST

    To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.

      Install the Google Cloud CLI. After installation,initialize the Google Cloud CLI by running the following command:

      gcloudinit

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    For more information, seeAuthenticate for using REST in the Google Cloud authentication documentation.

Required roles

To get the permissions that you need to create a secret, ask your administrator to grant you theSecret Manager Admin (roles/secretmanager.admin) IAM role on the project, folder, or organization. For more information about granting roles, seeManage access to projects, folders, and organizations.

You might also be able to get the required permissions throughcustom roles or otherpredefined roles.

Create a secret

You can create secrets using the Google Cloud console, the Google Cloud CLI, the Secret Manager API, or theSecret Manager client libraries.

Console

  1. In the Google Cloud console, go to theSecret Manager page.

    Go to Secret Manager

  2. On theSecret Manager page, clickCreate secret.

  3. On theCreate secret page, enter a name for the secret in theName field. A secret name can contain uppercase and lowercase letters, numerals, hyphens, and underscores. The maximum allowed length for a name is 255 characters.

  4. Enter a value for the secret (for example,abcd1234). The secret value can be in any format but must not be larger than 64 KiB. You can also upload a text file containing the secret value using theUpload file option. This action automatically creates the secret version.

  5. ClickCreate secret.

gcloud

Before using any of the command data below, make the following replacements:

  • SECRET_ID: the ID of the secret.
  • REPLICATION_POLICY: the replication policy for the secret, which can be either automatic or user-managed.

Execute the following command:

Linux, macOS, or Cloud Shell

Note: Ensure you have initialized the Google Cloud CLI with authentication and a project by running eithergcloud init; orgcloud auth login andgcloud config set project.
gcloudsecretscreateSECRET_ID\--replication-policy="REPLICATION_POLICY"

Windows (PowerShell)

Note: Ensure you have initialized the Google Cloud CLI with authentication and a project by running eithergcloud init; orgcloud auth login andgcloud config set project.
gcloudsecretscreateSECRET_ID`--replication-policy="REPLICATION_POLICY"

Windows (cmd.exe)

Note: Ensure you have initialized the Google Cloud CLI with authentication and a project by running eithergcloud init; orgcloud auth login andgcloud config set project.
gcloudsecretscreateSECRET_ID^--replication-policy="REPLICATION_POLICY"

REST

Before using any of the request data, make the following replacements:

  • PROJECT_ID: the Google Cloud project ID.
  • SECRET_ID: the ID of the secret.
  • REPLICATION_POLICY: the replication policy for the secret, which can be either automatic or user-managed.

HTTP method and URL:

POST https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID

Request JSON body:

{  "replication": {    "REPLICATION_POLICY": {}  }}

To send your request, choose one of these options:

curl

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID"

PowerShell

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID" | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{  "name": "projects/PROJECT_ID/secrets/SECRET_ID",  "createTime": "2024-03-25T08:24:13.153705Z",  "etag": "\"161477e6071da9\""}

C#

To run this code, firstset up a C# development environment andinstall the Secret Manager C# SDK. On Compute Engine or GKE, you mustauthenticate with thecloud-platform scope.

usingGoogle.Api.Gax.ResourceNames;usingGoogle.Cloud.SecretManager.V1;publicclassCreateSecretSample{publicSecretCreateSecret(stringprojectId="my-project",stringsecretId="my-secret"){// Create the client.SecretManagerServiceClientclient=SecretManagerServiceClient.Create();// Build the parent resource name.ProjectNameprojectName=newProjectName(projectId);// Build the secret.Secretsecret=newSecret{Replication=newReplication{Automatic=newReplication.Types.Automatic(),},};// Call the API.SecretcreatedSecret=client.CreateSecret(projectName,secretId,secret);returncreatedSecret;}}

Go

To run this code, firstset up a Go development environment andinstall the Secret Manager Go SDK. On Compute Engine or GKE, you mustauthenticate with thecloud-platform scope.

import("context""fmt""io"secretmanager"cloud.google.com/go/secretmanager/apiv1""cloud.google.com/go/secretmanager/apiv1/secretmanagerpb")// createSecret creates 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.funccreateSecret(wio.Writer,parent,idstring)error{// parent := "projects/my-project"// id := "my-secret"// Create the client.ctx:=context.Background()client,err:=secretmanager.NewClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create secretmanager client: %w",err)}deferclient.Close()// Build the request.req:=&secretmanagerpb.CreateSecretRequest{Parent:parent,SecretId:id,Secret:&secretmanagerpb.Secret{Replication:&secretmanagerpb.Replication{Replication:&secretmanagerpb.Replication_Automatic_{Automatic:&secretmanagerpb.Replication_Automatic{},},},},}// Call the API.result,err:=client.CreateSecret(ctx,req)iferr!=nil{returnfmt.Errorf("failed to create secret: %w",err)}fmt.Fprintf(w,"Created secret: %s\n",result.Name)returnnil}

Java

To run this code, firstset up a Java development environment andinstall the Secret Manager Java SDK. On Compute Engine or GKE, you mustauthenticate with thecloud-platform scope.

importcom.google.cloud.secretmanager.v1.ProjectName;importcom.google.cloud.secretmanager.v1.Replication;importcom.google.cloud.secretmanager.v1.Secret;importcom.google.cloud.secretmanager.v1.SecretManagerServiceClient;importcom.google.protobuf.Duration;importjava.io.IOException;publicclassCreateSecret{publicstaticvoidcreateSecret()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringsecretId="your-secret-id";createSecret(projectId,secretId);}// Create a new secret with automatic replication.publicstaticvoidcreateSecret(StringprojectId,StringsecretId)throwsIOException{// Initialize the client that will be used to send requests. This client only needs to be// created once, and can be reused for multiple requests. After completing all of your requests,// call the "close" method on the client to safely clean up any remaining background resources.try(SecretManagerServiceClientclient=SecretManagerServiceClient.create()){// Build the parent name from the project.ProjectNameprojectName=ProjectName.of(projectId);// Optionally set a TTL for the secret. This demonstrates how to configure// a secret to be automatically deleted after a certain period. The TTL is// specified in seconds (e.g., 900 for 15 minutes). This can be useful// for managing sensitive data and reducing storage costs.Durationttl=Duration.newBuilder().setSeconds(900).build();// Build the secret to create.Secretsecret=Secret.newBuilder().setReplication(Replication.newBuilder().setAutomatic(Replication.Automatic.newBuilder().build()).build()).setTtl(ttl).build();// Create the secret.SecretcreatedSecret=client.createSecret(projectName,secretId,secret);System.out.printf("Created secret %s\n",createdSecret.getName());}}}

Node.js

To run this code, firstset up a Node.js development environment andinstall the Secret Manager Node.js SDK. On Compute Engine or GKE, you mustauthenticate with thecloud-platform scope.

/** * TODO(developer): Uncomment these variables before running the sample. */// const parent = 'projects/my-project';// const secretId = 'my-secret';// const ttl = undefined // Optional: Specify TTL in seconds (e.g., '900s' for 15 minutes).// Imports the Secret Manager libraryconst{SecretManagerServiceClient}=require('@google-cloud/secret-manager');// Instantiates a clientconstclient=newSecretManagerServiceClient();asyncfunctioncreateSecret(){constsecretConfig={replication:{automatic:{},},};// Add TTL to the secret configuration if providedif(ttl){secretConfig.ttl={seconds:parseInt(ttl.replace('s',''),10),};console.log(`Secret TTL set to${ttl}`);}const[secret]=awaitclient.createSecret({parent:parent,secretId:secretId,secret:secretConfig,});console.log(`Created secret${secret.name}`);}createSecret();

PHP

To run this code, first learn aboutusing PHP on Google Cloud andinstall the Secret Manager PHP SDK. On Compute Engine or GKE, you mustauthenticate with thecloud-platform scope.

// Import the Secret Manager client library.use Google\Cloud\SecretManager\V1\CreateSecretRequest;use Google\Cloud\SecretManager\V1\Replication;use Google\Cloud\SecretManager\V1\Replication\Automatic;use Google\Cloud\SecretManager\V1\Secret;use Google\Cloud\SecretManager\V1\Client\SecretManagerServiceClient;/** * @param string $projectId Your Google Cloud Project ID (e.g. 'my-project') * @param string $secretId  Your secret ID (e.g. 'my-secret') */function create_secret(string $projectId, string $secretId): void{    // Create the Secret Manager client.    $client = new SecretManagerServiceClient();    // Build the resource name of the parent project.    $parent = $client->projectName($projectId);    $secret = new Secret([        'replication' => new Replication([            'automatic' => new Automatic(),        ]),    ]);    // Build the request.    $request = CreateSecretRequest::build($parent, $secretId, $secret);    // Create the secret.    $newSecret = $client->createSecret($request);    // Print the new secret name.    printf('Created secret: %s', $newSecret->getName());}

Python

To run this code, firstset up a Python development environment andinstall the Secret Manager Python SDK. On Compute Engine or GKE, you mustauthenticate with thecloud-platform scope.

# Import the Secret Manager client library.fromgoogle.cloudimportsecretmanagerdefcreate_secret(project_id:str,secret_id:str,ttl: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.     Args:        project_id (str): The project ID where the secret is to be created.        secret_id (str): The ID to assign to the new secret. This ID must be unique within the project.        ttl (Optional[str]): An optional string that specifies the secret's time-to-live in seconds with                             format (e.g., "900s" for 15 minutes). If specified, the secret                             versions will be automatically deleted upon reaching the end of the TTL period.    Returns:        secretmanager.Secret: An object representing the newly created secret, containing details like the                              secret's name, replication settings, and optionally its TTL.    Example:        # Create a secret with automatic replication and no TTL        new_secret = create_secret("my-project", "my-new-secret")        # Create a secret with a TTL of 30 days        new_secret_with_ttl = create_secret("my-project", "my-timed-secret", "7776000s")    """# 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},})# Print the new secret name.print(f"Created secret:{response.name}")

Ruby

To run this code, firstset up a Ruby development environment andinstall the Secret Manager Ruby SDK. On Compute Engine or GKE, you mustauthenticate with thecloud-platform scope.

# project_id = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")# secret_id  = "YOUR-SECRET-ID"             # (e.g. "my-secret")# Require the Secret Manager client library.require"google/cloud/secret_manager"# Create a Secret Manager client.client=Google::Cloud::SecretManager.secret_manager_service# Build the resource name of the parent project.parent=client.project_pathproject:project_id# Create the secret.secret=client.create_secret(parent:parent,secret_id:secret_id,secret:{replication:{automatic:{}}})# Print the new secret name.puts"Created secret:#{secret.name}"

To select the right replication policy for your secret, seeChoose a replication policy.

Add a secret version

Secret Manager automatically versions secret data using secret versions. Key operations, suchas access, destroy, disable, and enable, are applied to specific secret versions. With Secret Manager, youcan associate secrets with specific versions such as42 or with dynamic aliasessuch aslatest. To learn more, seeAdd a secret version.

Access a secret version

To access the secret data from a particular secret version for successful authentication, seeAccess a secret version.

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-02-05 UTC.