Secret Manager 用戶端程式庫

本頁說明如何開始使用 Secret Manager API 適用的 Cloud 用戶端程式庫。用戶端程式庫可讓您從支援的語言輕鬆存取Google Cloud API。雖然您可以直接向伺服器發出原始要求來使用Google Cloud API,但用戶端程式庫提供簡化功能,可大幅減少您需要編寫的程式碼數量。

如要進一步瞭解 Cloud 用戶端程式庫和舊版 Google API 用戶端程式庫,請參閱用戶端程式庫說明

安裝用戶端程式庫

C++

如要瞭解這個用戶端程式庫的需求和安裝依附元件,請參閱「設定 C++ 開發環境」。

C#

如果您使用 Visual Studio 2017 以上版本,請開啟 NuGet 套件管理員視窗,然後輸入下列內容:

Install-Package Google.Apis

如果您使用 .NET Core 指令列介面工具安裝依附元件,請執行下列指令:

dotnet add package Google.Apis

詳情請參閱設定 C# 開發環境

Go

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

詳情請參閱「設定 Go 開發環境」。

Java

If you are using Maven, add the following to your pom.xml file. For more information about BOMs, see The Google Cloud Platform Libraries BOM.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.61.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 using Gradle, add the following to your dependencies:

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

If you are using sbt, add the following to your dependencies:

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

If you're using Visual Studio Code, IntelliJ, or Eclipse, 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.

詳情請參閱「設定 Java 開發環境」。

Node.js

$ npm install @google-cloud/secret-manager

詳情請參閱「設定 Node.js 開發環境」。

PHP

composer require google/apiclient

詳情請參閱「在 Google Cloud 上使用 PHP」。

Python

$ pip install google-cloud-secret-manager

詳情請參閱「設定 Python 開發環境」。

Ruby

gem install google-api-client

詳情請參閱「設定 Ruby 開發環境」。

設定驗證方法

為驗證對 Google Cloud API 的呼叫,用戶端程式庫支援應用程式預設憑證 (ADC);程式庫會在定義的一組位置中尋找憑證,並使用這些憑證驗證對 API 的要求。使用 ADC,您可以在各種環境 (例如本機開發或正式版) 中,為應用程式提供憑證,不必修改應用程式程式碼。

在實際工作環境中,設定 ADC 的方式取決於服務和環境。詳情請參閱「設定應用程式預設憑證」。

在本地開發環境中,您可以使用與 Google 帳戶相關聯的憑證設定 ADC:

  1. After installing the Google Cloud CLI, initialize it by running the following command:

    gcloud init

    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:

    gcloud auth application-default login

    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.

    畫面上會顯示登入畫面。登入後,您的憑證會儲存在 ADC 使用的 本機憑證檔案中。

使用用戶端程式庫

以下範例將說明用戶端程式庫的使用方法。

Go


// Sample quickstart is a basic program that uses Secret Manager.
package main

import (
	"context"
	"fmt"
	"log"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
	"google.golang.org/api/option"
)

func main() {
	// GCP project in which to store secrets in Secret Manager.
	projectID := "your-project-id"
	// Location at which you want to store your secrets
	locationID := "your-location-id"

	// Create the client.
	ctx := context.Background()
	endpoint := fmt.Sprintf("secretmanager.%s.rep.googleapis.com:443", locationID)
	client, err := secretmanager.NewClient(ctx, option.WithEndpoint(endpoint))

	if err != nil {
		log.Fatalf("failed to setup client: %v", err)
	}
	defer client.Close()

	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)

	// Create the request to create the secret.
	createSecretReq := &secretmanagerpb.CreateSecretRequest{
		Parent:   parent,
		SecretId: "my-secret",
	}

	secret, err := client.CreateSecret(ctx, createSecretReq)
	if err != 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)
	if err != 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)
	if err != 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

import com.google.cloud.secretmanager.v1.AccessSecretVersionResponse;
import com.google.cloud.secretmanager.v1.LocationName;
import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import com.google.cloud.secretmanager.v1.SecretPayload;
import com.google.cloud.secretmanager.v1.SecretVersion;
import com.google.protobuf.ByteString;

public class RegionalQuickstart {

  public void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.

    // Your GCP project ID.
    String projectId = "your-project-id";
    // Location of the secret.
    String locationId = "your-location-id";
    // Resource ID of the secret.
    String secretId = "your-secret-id";
    regionalQuickstart(projectId, locationId, secretId);
  }

  // Demonstrates basic capabilities in the regional Secret Manager API.
  public SecretPayload regionalQuickstart(
      String projectId, String locationId, String secretId) 
      throws Exception {

    // Endpoint to call the regional secret manager sever
    String apiEndpoint = String.format("secretmanager.%s.rep.googleapis.com:443", locationId);
    SecretManagerServiceSettings secretManagerServiceSettings =
        SecretManagerServiceSettings.newBuilder().setEndpoint(apiEndpoint).build();

    // 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.
    try (SecretManagerServiceClient client = 
        SecretManagerServiceClient.create(secretManagerServiceSettings)) {
      // Build the parent name from the project.
      LocationName parent = LocationName.of(projectId, locationId);

      // Create the parent secret.
      Secret secret =
          Secret.newBuilder()
              .build();

      Secret createdSecret = client.createSecret(parent, secretId, secret);

      // Add a secret version.
      SecretPayload payload =
          SecretPayload.newBuilder().setData(ByteString.copyFromUtf8("Secret data")).build();
      SecretVersion addedVersion = client.addSecretVersion(createdSecret.getName(), payload);

      // Access the secret version.
      AccessSecretVersionResponse response = 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.
      String data = response.getPayload().getData().toStringUtf8();
      // System.out.printf("Plaintext: %s\n", data);

      return payload;
    }
  }
}

Node.js


// Adding the endpoint to call the regional secret manager sever
const options = {};
options.apiEndpoint = `secretmanager.${locationId}.rep.googleapis.com`;

// Import the Secret Manager client and instantiate it:
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');
const client = new SecretManagerServiceClient(options);

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project', // Project for which to manage secrets.
// locationID = 'my-location', // Region location to store secrets in
// secretId = 'foo', // Secret ID.
// payload = 'hello world!' // String source data.

const parent = `projects/${projectId}/locations/${locationId}`;

async function createAndAccessSecret() {
  // Create the secret.
  const [secret] = await client.createSecret({
    parent: parent,
    secret: {
      name: secretId,
    },
    secretId,
  });

  console.info(`Created regional secret ${secret.name}`);

  // Add a version with a payload onto the secret.
  const [version] = await client.addSecretVersion({
    parent: secret.name,
    payload: {
      data: Buffer.from(payload, 'utf8'),
    },
  });

  console.info(`Added regional secret version ${version.name}`);

  // Access the secret.
  const [accessResponse] = await client.accessSecretVersion({
    name: version.name,
  });

  const responsePayload = accessResponse.payload.data.toString('utf8');
  console.info(`Payload: ${responsePayload}`);
}
createAndAccessSecret();

Python

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

# TODO (developer): uncomment variables and assign a value.

# GCP project in which to store secrets in Secret Manager.
# project_id = "YOUR_PROJECT_ID"

# Location where the secret is to be stored
# location_id = "YOUR_LOCATION_ID"

# ID of the secret to create.
# secret_id = "YOUR_SECRET_ID"

# Endpoint to call the regional secret manager sever
api_endpoint = f"secretmanager.{location_id}.rep.googleapis.com"

# Create the Secret Manager client.
client = secretmanager_v1.SecretManagerServiceClient(
    client_options={"api_endpoint": api_endpoint},
)

# Build the parent name from the project.
parent = f"projects/{project_id}/locations/{location_id}"

# Create the parent secret.
secret = client.create_secret(
    request={
        "parent": parent,
        "secret_id": secret_id,
    }
)

# 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}")

其他資源

C++

以下清單列出與 C++ 用戶端程式庫相關的更多資源連結:

C#

以下清單列出與 C# 用戶端程式庫相關的更多資源連結:

Go

下列清單包含與 Go 專用用戶端程式庫相關的更多資源連結:

Java

以下列出與 Java 用戶端程式庫相關的更多資源連結:

Node.js

以下清單列出與 Node.js 用戶端程式庫相關的更多資源連結:

PHP

下列清單包含與 PHP 用戶端程式庫相關的更多資源連結:

Python

以下清單包含適用於 Python 的用戶端程式庫相關資源連結:

Ruby

以下清單提供與 Ruby 用戶端程式庫相關的更多資源連結: