Crea un secret regionale con annotazioni

Crea un secret regionale con annotazioni

Esempio di codice

C#

Per scoprire come installare e utilizzare la libreria client per Secret Manager, consulta la sezione Librerie client di Secret Manager.

Per autenticarti in Secret Manager, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecretManager.V1;
using System.Collections.Generic;

public class CreateRegionalSecretWithAnnotationsSample
{
    public Secret CreateRegionalSecretWithAnnotations(
      string projectId = "my-project",
      string locationId = "my-location",
      string secretId = "my-secret",
      string annotationKey = "my-annotation-key",
      string annotationValue = "my-annotation-value"
    )
    {
        // Create the Regional Secret Manager Client.
        SecretManagerServiceClient client = new SecretManagerServiceClientBuilder
        {
            Endpoint = $"secretmanager.{locationId}.rep.googleapis.com"
        }.Build();

        // Build the parent resource name.
        LocationName location = new LocationName(projectId, locationId);

        // Build the secret.
        Secret secret = new Secret
        {
            Annotations =
          {
              { annotationKey, annotationValue }
          },
        };

        // Call the API.
        Secret createdSecret = client.CreateSecret(location, secretId, secret);
        return createdSecret;
    }
}

Go

Per scoprire come installare e utilizzare la libreria client per Secret Manager, consulta la sezione Librerie client di Secret Manager.

Per autenticarti in Secret Manager, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

import (
	"context"
	"fmt"
	"io"

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

// createRegionalSecretWithAnnotations creates a new secret with the given name and annotations.
func createRegionalSecretWithAnnotations(w io.Writer, projectId, locationId, secretId string) error {
	// parent := "projects/my-project"
	// id := "my-secret"

	annotationKey := "annotationkey"
	annotationValue := "annotationvalue"

	ctx := context.Background()

	//Endpoint to send the request to regional server
	endpoint := fmt.Sprintf("secretmanager.%s.rep.googleapis.com:443", locationId)
	client, err := secretmanager.NewClient(ctx, option.WithEndpoint(endpoint))
	if err != nil {
		return fmt.Errorf("failed to create secretmanager client: %w", err)
	}
	defer client.Close()

	parent := fmt.Sprintf("projects/%s/locations/%s", projectId, locationId)

	// Build the request.
	req := &secretmanagerpb.CreateSecretRequest{
		Parent:   parent,
		SecretId: secretId,
		Secret: &secretmanagerpb.Secret{
			Annotations: map[string]string{
				annotationKey: annotationValue,
			},
		},
	}

	result, err := client.CreateSecret(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create secret: %w", err)
	}
	fmt.Fprintf(w, "Created secret with annotations: %s\n", result.Name)
	return nil
}

Java

Per scoprire come installare e utilizzare la libreria client per Secret Manager, consulta la sezione Librerie client di Secret Manager.

Per autenticarti in Secret Manager, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

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 java.io.IOException;

public class CreateRegionalSecretWithAnnotations {

  public static void createRegionalSecretWithAnnotations() throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // This is the id of the GCP project
    String projectId = "your-project-id";
    // Location of the secret.
    String locationId = "your-location-id";
    // This is the id of the secret to act on
    String secretId = "your-secret-id";
    // This is the key of the annotation to be added
    String annotationKey = "your-annotation-key";
    // This is the value of the annotation to be added
    String annotationValue = "your-annotation-value";
    createRegionalSecretWithAnnotations(
        projectId, locationId, secretId, annotationKey, annotationValue
    );
  }

  // Create a secret with annotations.
  public static Secret createRegionalSecretWithAnnotations(
        String projectId,
        String locationId,
        String secretId,
        String annotationKey,
        String annotationValue
  ) throws IOException {

    // 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 location = LocationName.of(projectId, locationId);

      // Build the secret to create with labels.
      Secret secret =
          Secret.newBuilder()
                .putAnnotations(annotationKey, annotationValue)
                .build();

      // Create the secret.
      Secret createdSecret = client.createSecret(location.toString(), secretId, secret);
      System.out.printf("Created secret %s\n", createdSecret.getName());
      return createdSecret;
    }
  }
}

Node.js

Per scoprire come installare e utilizzare la libreria client per Secret Manager, consulta la sezione Librerie client di Secret Manager.

Per autenticarti in Secret Manager, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project'
// const locationId = 'locationId';
// const secretId = 'my-secret';
// const annotationKey = 'exampleannotationkey';
// const annotationValue = 'exampleannotationvalue';

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

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Adding the endpoint to call the regional secret manager sever
const options = {};
options.apiEndpoint = `secretmanager.${locationId}.rep.googleapis.com`;
// Instantiates a client
const client = new SecretManagerServiceClient(options);

async function createRegionalSecretWithAnnotations() {
  const [secret] = await client.createSecret({
    parent: parent,
    secretId: secretId,
    secret: {
      annotations: {
        [annotationKey]: annotationValue,
      },
    },
  });

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

createRegionalSecretWithAnnotations();

PHP

Per scoprire come installare e utilizzare la libreria client per Secret Manager, consulta la sezione Librerie client di Secret Manager.

Per autenticarti in Secret Manager, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\CreateSecretRequest;
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 $locationId      Your Google Cloud Location ID (e.g. 'us-central1')
 * @param string $secretId        Your secret ID (e.g. 'my-secret')
 * @param string $annotationKey   Your annotation key (e.g. 'annotation-key')
 * @param string $annotationValue Your annotation value (e.g. 'annotation-value')
 */
function create_regional_secret_with_annotations(string $projectId, string $locationId, string $secretId, string $annotationKey, string $annotationValue): void
{
    // Specify regional endpoint.
    $options = ['apiEndpoint' => "secretmanager.$locationId.rep.googleapis.com"];

    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient($options);

    // Build the resource name of the parent project.
    $parent = $client->locationName($projectId, $locationId);

    $secret = new Secret();

    // set the annotations.
    $annotations = [$annotationKey => $annotationValue];
    $secret->setAnnotations($annotations);

    // 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 with annotations', $newSecret->getName());
}

Python

Per scoprire come installare e utilizzare la libreria client per Secret Manager, consulta la sezione Librerie client di Secret Manager.

Per autenticarti in Secret Manager, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

import argparse
import typing

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


def create_regional_secret_with_annotations(
    project_id: str,
    location_id: str,
    secret_id: str,
    annotations: typing.Dict[str, str],
) -> secretmanager_v1.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.
    """

    # 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 resource name of the parent project.
    parent = f"projects/{project_id}/locations/{location_id}"

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

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

    return response

Ruby

Per scoprire come installare e utilizzare la libreria client per Secret Manager, consulta la sezione Librerie client di Secret Manager.

Per autenticarti in Secret Manager, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

# project_id       = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")
# location_id      = "YOUR-GOOGLE-CLOUD-LOCATION" # (e.g. "us-west1")
# secret_id        = "YOUR-SECRET-ID"             # (e.g. "my-secret")
# annotation_key   = "YOUR-ANNOTATION-KEY"        # (e.g. "my-annotation-key")
# annotation_value = "YOUR-ANNOTATION-VALUE"      # (e.g. "my-annotation-value")

# Require the Secret Manager client library.
require "google/cloud/secret_manager"

# Endpoint for the regional secret manager service.
api_endpoint = "secretmanager.#{location_id}.rep.googleapis.com"

# Create the Secret Manager client.
client = Google::Cloud::SecretManager.secret_manager_service do |config|
  config.endpoint = api_endpoint
end

# Build the resource name of the parent project.
parent = client.location_path project: project_id, location: location_id

# Create the secret.
secret = client.create_secret(
  parent:    parent,
  secret_id: secret_id,
  secret: {
    annotations: {
      annotation_key => annotation_value
    }
  }
)

# Print the new secret name.
puts "Created regional secret with annotations: #{secret.name}"

Passaggi successivi

Per cercare e filtrare gli esempi di codice per altri prodotti Google Cloud , consulta il browser degli esempi diGoogle Cloud .