Secret Manager client libraries

This page shows how to get started with the Cloud Client Libraries for theSecret Manager API. Client libraries make it easier to accessGoogle Cloud APIs from a supported language. Although you can useGoogle Cloud APIs directly by making raw requests to the server, clientlibraries provide simplifications that significantly reduce the amount of codeyou need to write.

Read more about the Cloud Client Librariesand the older Google API Client Libraries inClient libraries explained.

Install the client library

C++

SeeSetting up a C++ development environmentfor details about this client library's requirements and install dependencies.

C#

Using PowerShell:

$Install-Package Google.Cloud.SecretManager.V1 -Version 2.5.0

Using the dotnet CLI:

$dotnet add package Google.Cloud.SecretManager.V1 --version 2.5.0

For more information, seeSetting Up a C# Development Environment.

Go

$go get cloud.google.com/go/secretmanager/apiv1$go get google.golang.org/genproto/googleapis/cloud/secretmanager/v1

For more information, seeSetting Up a Go Development Environment.

Java

If you are usingMaven, addthe following to yourpom.xml file. For more information aboutBOMs, seeThe Google Cloud Platform Libraries BOM.

<dependencyManagement><dependencies><dependency><groupId>com.google.cloud</groupId><artifactId>libraries-bom</artifactId><version>26.76.0</version><type>pom</type><scope>import</scope></dependency>  </dependencies></dependencyManagement><dependencies>  <dependency>    <groupId>com.google.cloud</groupId><artifactId>google-cloud-secretmanager</artifactId></dependency></dependencies>

If you are usingGradle,add the following to your dependencies:

implementation'com.google.cloud:google-cloud-secretmanager:2.85.0'

If you are usingsbt, addthe following to your dependencies:

libraryDependencies+="com.google.cloud"%"google-cloud-secretmanager"%"2.85.0"

If you're using Visual Studio Code or IntelliJ, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

Note: Cloud Java client libraries do not currently support Android.

For more information, seeSetting Up a Java Development Environment.

Node.js

$npm install @google-cloud/secret-manager

For more information, seeSetting Up a Node.js Development Environment.

PHP

$composer require google/cloud-secret-manager

For more information, seeUsing PHP on Google Cloud.

Python

$pip install google-cloud-secret-manager

For more information, seeSetting Up a Python Development Environment.

Ruby

$gem install google-cloud-secret_manager

For more information, seeSetting Up a Ruby Development Environment.

Set up authentication

To authenticate calls to Google Cloud APIs, client libraries supportApplication Default Credentials (ADC);the libraries look for credentials in a set of defined locations and use those credentialsto authenticate requests to the API. With ADC, you can makecredentials available to your application in a variety of environments, such as localdevelopment or production, without needing to modify your application code.

For production environments, the way you set up ADC depends on the serviceand context. For more information, seeSet up Application Default Credentials.

For a local development environment, you can set up ADC with the credentialsthat are associated with your Google Account:

  1. 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.

  2. If you're using a local shell, then create local authentication credentials for your user account:

    gcloudauthapplication-defaultlogin

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    A sign-in screen appears. After you sign in, your credentials are stored in the local credential file used by ADC.

Use the client library

The following example shows how to use the client library.

C++

#include"google/cloud/secretmanager/v1/secret_manager_client.h"#include <iostream>intmain(intargc,char*argv[])try{if(argc!=2){std::cerr <<"Usage: " <<argv[0] <<" project-id\n";return1;}namespacesecretmanager=::google::cloud::secretmanager_v1;autoclient=secretmanager::SecretManagerServiceClient(secretmanager::MakeSecretManagerServiceConnection());autoconstparent=std::string("projects/")+argv[1];for(autosecret:client.ListSecrets(parent)){if(!secret)throwstd::move(secret).status();std::cout <<secret->DebugString() <<"\n";}return0;}catch(google::cloud::Statusconst&status){std::cerr <<"google::cloud::Status thrown: " <<status <<"\n";return1;}

C#

usingSystem;usingSystem.Text;usingGoogle.Api.Gax.ResourceNames;usingGoogle.Cloud.SecretManager.V1;usingGoogle.Protobuf;publicclassQuickstartSample{publicvoidQuickstart(stringprojectId="my-project",stringsecretId="my-secret"){// Create the client.SecretManagerServiceClientclient=SecretManagerServiceClient.Create();// Build the parent project name.ProjectNameprojectName=newProjectName(projectId);// Build the secret to create.Secretsecret=newSecret{Replication=newReplication{Automatic=newReplication.Types.Automatic(),},};SecretcreatedSecret=client.CreateSecret(projectName,secretId,secret);// Build a payload.SecretPayloadpayload=newSecretPayload{Data=ByteString.CopyFrom("my super secret data",Encoding.UTF8),};// Add a secret version.SecretVersioncreatedVersion=client.AddSecretVersion(createdSecret.SecretName,payload);// Access the secret version.AccessSecretVersionResponseresult=client.AccessSecretVersion(createdVersion.SecretVersionName);// Print the results//// WARNING: Do not print secrets in production environments. This// snippet is for demonstration purposes only.stringdata=result.Payload.Data.ToStringUtf8();Console.WriteLine($"Plaintext: {data}");}}

Go

// Sample quickstart is a basic program that uses Secret Manager.packagemainimport("context""fmt""log"secretmanager"cloud.google.com/go/secretmanager/apiv1""cloud.google.com/go/secretmanager/apiv1/secretmanagerpb")funcmain(){// GCP project in which to store secrets in Secret Manager.projectID:="your-project-id"// Create the client.ctx:=context.Background()client,err:=secretmanager.NewClient(ctx)iferr!=nil{log.Fatalf("failed to setup client: %v",err)}deferclient.Close()// Create the request to create the secret.createSecretReq:=&secretmanagerpb.CreateSecretRequest{Parent:fmt.Sprintf("projects/%s",projectID),SecretId:"my-secret",Secret:&secretmanagerpb.Secret{Replication:&secretmanagerpb.Replication{Replication:&secretmanagerpb.Replication_Automatic_{Automatic:&secretmanagerpb.Replication_Automatic{},},},},}secret,err:=client.CreateSecret(ctx,createSecretReq)iferr!=nil{log.Fatalf("failed to create secret: %v",err)}// Declare the payload to store.payload:=[]byte("my super secret data")// Build the request.addSecretVersionReq:=&secretmanagerpb.AddSecretVersionRequest{Parent:secret.Name,Payload:&secretmanagerpb.SecretPayload{Data:payload,},}// Call the API.version,err:=client.AddSecretVersion(ctx,addSecretVersionReq)iferr!=nil{log.Fatalf("failed to add secret version: %v",err)}// Build the request.accessRequest:=&secretmanagerpb.AccessSecretVersionRequest{Name:version.Name,}// Call the API.result,err:=client.AccessSecretVersion(ctx,accessRequest)iferr!=nil{log.Fatalf("failed to access secret version: %v",err)}// Print the secret payload.//// WARNING: Do not print the secret in a production environment - this// snippet is showing how to access the secret material.log.Printf("Plaintext: %s",result.Payload.Data)}

Java

importcom.google.cloud.secretmanager.v1.AccessSecretVersionResponse;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.cloud.secretmanager.v1.SecretPayload;importcom.google.cloud.secretmanager.v1.SecretVersion;importcom.google.protobuf.ByteString;publicclassQuickstart{publicvoidquickstart()throwsException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringsecretId="your-secret-id";quickstart(projectId,secretId);}publicvoidquickstart(StringprojectId,StringsecretId)throwsException{// Initialize 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);// Create the parent secret.Secretsecret=Secret.newBuilder().setReplication(Replication.newBuilder().setAutomatic(Replication.Automatic.newBuilder().build()).build()).build();SecretcreatedSecret=client.createSecret(projectName,secretId,secret);// Add a secret version.SecretPayloadpayload=SecretPayload.newBuilder().setData(ByteString.copyFromUtf8("hello world!")).build();SecretVersionaddedVersion=client.addSecretVersion(createdSecret.getName(),payload);// Access the secret version.AccessSecretVersionResponseresponse=client.accessSecretVersion(addedVersion.getName());// Print the secret payload.//// WARNING: Do not print the secret in a production environment - this// snippet is showing how to access the secret material.Stringdata=response.getPayload().getData().toStringUtf8();System.out.printf("Plaintext: %s\n",data);}}}

Node.js

// Import the Secret Manager client and instantiate it:const{SecretManagerServiceClient}=require('@google-cloud/secret-manager');constclient=newSecretManagerServiceClient();/** * TODO(developer): Uncomment these variables before running the sample. */// parent = 'projects/my-project', // Project for which to manage secrets.// secretId = 'foo', // Secret ID.// payload = 'hello world!' // String source data.asyncfunctioncreateAndAccessSecret(){// Create the secret with automation replication.const[secret]=awaitclient.createSecret({parent:parent,secret:{name:secretId,replication:{automatic:{},},},secretId,});console.info(`Created secret${secret.name}`);// Add a version with a payload onto the secret.const[version]=awaitclient.addSecretVersion({parent:secret.name,payload:{data:Buffer.from(payload,'utf8'),},});console.info(`Added secret version${version.name}`);// Access the secret.const[accessResponse]=awaitclient.accessSecretVersion({name:version.name,});constresponsePayload=accessResponse.payload.data.toString('utf8');console.info(`Payload:${responsePayload}`);}createAndAccessSecret();

PHP

// Import the Secret Manager client library.use Google\Cloud\SecretManager\V1\AccessSecretVersionRequest;use Google\Cloud\SecretManager\V1\AddSecretVersionRequest;use Google\Cloud\SecretManager\V1\Client\SecretManagerServiceClient;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\SecretPayload;/** Uncomment and populate these variables in your code */// $projectId = 'YOUR_GOOGLE_CLOUD_PROJECT' (e.g. 'my-project');// $secretId = 'YOUR_SECRET_ID' (e.g. 'my-secret');// Create the Secret Manager client.$client = new SecretManagerServiceClient();// Build the parent name from the project.$parent = $client->projectName($projectId);// Create the parent secret.$createSecretRequest = (new CreateSecretRequest())    ->setParent($parent)    ->setSecretId($secretId)    ->setSecret(new Secret([        'replication' => new Replication([            'automatic' => new Automatic(),        ]),    ]));$secret = $client->createSecret($createSecretRequest);// Add the secret version.$addSecretVersionRequest = (new AddSecretVersionRequest())    ->setParent($secret->getName())    ->setPayload(new SecretPayload([    'data' => 'hello world',]));$version = $client->addSecretVersion($addSecretVersionRequest);// Access the secret version.$accessSecretVersionRequest = (new AccessSecretVersionRequest())    ->setName($version->getName());$response = $client->accessSecretVersion($accessSecretVersionRequest);// Print the secret payload.//// WARNING: Do not print the secret in a production environment - this// snippet is showing how to access the secret material.$payload = $response->getPayload()->getData();printf('Plaintext: %s' . PHP_EOL, $payload);

Python

# Import the Secret Manager client library.fromgoogle.cloudimportsecretmanager# GCP project in which to store secrets in Secret Manager.project_id="YOUR_PROJECT_ID"# ID of the secret to create.secret_id="YOUR_SECRET_ID"# Create the Secret Manager client.client=secretmanager.SecretManagerServiceClient()# Build the parent name from the project.parent=f"projects/{project_id}"# Create the parent secret.secret=client.create_secret(request={"parent":parent,"secret_id":secret_id,"secret":{"replication":{"automatic":{}}},})# Add the secret version.version=client.add_secret_version(request={"parent":secret.name,"payload":{"data":b"hello world!"}})# Access the secret version.response=client.access_secret_version(request={"name":version.name})# Print the secret payload.## WARNING: Do not print the secret in a production environment - this# snippet is showing how to access the secret material.payload=response.payload.data.decode("UTF-8")print(f"Plaintext:{payload}")

Ruby

require"google/cloud/secret_manager"### Secret manager quickstart## @param project_id [String] Your Google Cloud project (e.g. "my-project")# @param secret_id [String] Your secret name (e.g. "my-secret")#defquickstartproject_id:,secret_id:# Create the Secret Manager client.client=Google::Cloud::SecretManager.secret_manager_service# Build the parent name from the project.parent="projects/#{project_id}"# Create the parent secret.secret=client.create_secret(parent:parent,secret_id:secret_id,secret:{replication:{automatic:{}}})# Add a secret version.version=client.add_secret_version(parent:secret.name,payload:{data:"hello world!"})# Access the secret version.response=client.access_secret_versionname:version.name# Print the secret payload.## WARNING: Do not print the secret in a production environment - this# snippet is showing how to access the secret material.payload=response.payload.dataputs"Plaintext:#{payload}"end

Additional resources

C++

The following list contains links to more resources related to theclient library for C++:

C#

The following list contains links to more resources related to theclient library for C#:

Go

The following list contains links to more resources related to theclient library for Go:

Java

The following list contains links to more resources related to theclient library for Java:

Node.js

The following list contains links to more resources related to theclient library for Node.js:

PHP

The following list contains links to more resources related to theclient library for PHP:

Python

The following list contains links to more resources related to theclient library for Python:

Ruby

The following list contains links to more resources related to theclient library for Ruby:

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-19 UTC.