Usar etiquetas de entidad para el control de simultaneidad optimista

Secret Manager admite el uso de etiquetas de entidad (ETags) para el control de simultaneidad optimista.

En algunos casos, dos procesos que actualizan el mismo recurso en paralelo pueden interferir entre sí, de forma que el último proceso sobrescribe el trabajo del primero.

Los ETags proporcionan un medio para controlar la simultaneidad optimista, ya que permiten que los procesos comprueben si un recurso se ha modificado antes de tomar medidas en él.

Usar ETags con Secret Manager

Las siguientes solicitudes de modificación de recursos admiten ETags:

En una solicitud secrets.patch, el ETag de la solicitud se inserta en los datos de Secret. El resto de las solicitudes aceptan un parámetro etag opcional.

Si se proporciona un ETag y coincide con el ETag del recurso actual, la solicitud se realiza correctamente. De lo contrario, se produce un error FAILED_PRECONDITION y se devuelve el código de estado HTTP 400. Si no se proporciona un ETag, la solicitud continúa sin comprobar el valor de ETag almacenado.

Los ETags de recursos se generan al crear el recurso (projects.secrets.create y projects.secrets.addVersion) y se actualizan con cada una de las solicitudes de modificación indicadas anteriormente. Una solicitud de modificación solo actualiza el ETag del recurso al que se aplica. Es decir, al actualizar una versión de un secreto, no se modifica la etiqueta ETag del secreto y, del mismo modo, al actualizar la etiqueta ETag, no se modifica la versión del secreto.

Aunque una actualización no cambie el estado de un recurso, se actualiza su ETag.

Veamos un ejemplo:

  • El usuario 1 intenta habilitar una versión de un secreto sin saber que ya está habilitada. El sistema procesa esto sin cambiar nada, excepto el ETag de la versión.

  • El usuario 2, que usa el ETag antiguo, intenta inhabilitar la versión.

  • Se produce un error porque el sistema reconoce el ETag más reciente, que indica una intención más reciente de mantener la versión habilitada.

Incluso las actualizaciones aparentemente menores son importantes debido a los cambios en las etiquetas ETag. De esta forma, se garantiza la coherencia de los datos, sobre todo cuando varios usuarios o sistemas interactúan con el mismo recurso.

El recurso etag se devuelve en la respuesta siempre que se incluya un recurso (Secret o SecretVersion).

Eliminar un secreto con ETags

En esta sección se describe cómo usar ETags al eliminar un secreto. Si otro proceso ha modificado el secreto, la operación de eliminación fallará.

gcloud

Antes de usar los datos de los comandos que se indican a continuación, haz los siguientes cambios:

  • SECRET_ID: el ID del secreto.
  • LOCATION: la Google Cloud ubicación del secreto.
  • ETAG: la etiqueta de entidad del secreto. El ETag debe incluir las comillas. Por ejemplo, si el valor de ETag era "abc", el valor con escape de shell sería "\"abc\"".

Ejecuta el siguiente comando:

Linux, macOS o Cloud Shell

gcloud secrets delete SECRET_ID --location=LOCATION \
    --etag "ETAG"

Windows (PowerShell)

gcloud secrets delete SECRET_ID --location=LOCATION `
    --etag "ETAG"

Windows (cmd.exe)

gcloud secrets delete SECRET_ID --location=LOCATION ^
    --etag "ETAG"

REST

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • LOCATION: la Google Cloud ubicación del secreto.
  • PROJECT_ID: el ID del proyecto. Google Cloud
  • SECRET_ID: el ID del secreto.
  • ETAG: la etiqueta de entidad del secreto. El ETag se especifica como parte de la cadena de consulta de la URL y debe codificarse como URL. Por ejemplo, si el valor de ETag es "abc", el valor codificado como URL sería %22abc%22 porque el carácter de comillas se codifica como %22.

Método HTTP y URL:

DELETE https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID?etag=ETAG

Cuerpo JSON de la solicitud:

{}

Para enviar tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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

PowerShell

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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

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

Deberías recibir una respuesta JSON similar a la siguiente:

{}

Go

Para ejecutar este código, primero debes configurar un entorno de desarrollo de Go e instalar el SDK de Go de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito cloud-platform.

import (
	"context"
	"fmt"

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

// deleteSecretWithEtag deletes the secret with the given name and all of its versions.
func DeleteRegionalSecretWithEtag(projectId, locationId, secretId, etag string) error {
	// name := "projects/my-project/locations/my-location/secrets/my-secret"
	// etag := `"123"`

	// Create the client.
	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()

	//Endpoint to send the request to regional server
	name := fmt.Sprintf("projects/%s/locations/%s/secrets/%s", projectId, locationId, secretId)

	// Build the request.
	req := &secretmanagerpb.DeleteSecretRequest{
		Name: name,
		Etag: etag,
	}

	// Call the API.
	if err := client.DeleteSecret(ctx, req); err != nil {
		return fmt.Errorf("failed to delete regional secret: %w", err)
	}
	return nil
}

Java

Para ejecutar este código, primero debes configurar un entorno de desarrollo de Java e instalar el SDK de Java de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito cloud-platform.

import com.google.cloud.secretmanager.v1.DeleteSecretRequest;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import com.google.cloud.secretmanager.v1.SecretName;
import java.io.IOException;

public class DeleteRegionalSecretWithEtag {

  public static void main(String[] args) throws IOException {
    // 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 to delete.
    String secretId = "your-secret-id";
    // Etag associated with the secret. Quotes should be included as part of the string.
    String etag = "\"1234\"";
    deleteRegionalSecretWithEtag(projectId, locationId, secretId, etag);
  }

  // Delete an existing secret with the given name and etag.
  public static void deleteRegionalSecretWithEtag(
      String projectId, String locationId, String secretId, String etag)
      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 secret name.
      SecretName secretName = SecretName.ofProjectLocationSecretName(
          projectId, locationId, secretId);

      // Construct the request.
      DeleteSecretRequest request =
          DeleteSecretRequest.newBuilder()
              .setName(secretName.toString())
              .setEtag(etag)
              .build();

      // Delete the secret.
      client.deleteSecret(request);
      System.out.printf("Deleted regional secret %s\n", secretId);
    }
  }
}

Python

Para ejecutar este código, primero debes configurar un entorno de desarrollo de Python e instalar el SDK de Python de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito cloud-platform.

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


def delete_regional_secret_with_etag(
    project_id: str,
    location_id: str,
    secret_id: str,
    etag: str,
) -> None:
    """
    Deletes the regional secret with the given name, etag, and all of its versions.
    """

    # 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 secret.
    name = f"projects/{project_id}/locations/{location_id}/secrets/{secret_id}"

    # Build the request
    request = secretmanager_v1.types.service.DeleteSecretRequest(
        name=name,
        etag=etag,
    )

    # Delete the secret.
    client.delete_secret(request=request)

Actualizar un secreto con ETags

En esta sección se describe cómo usar ETags al actualizar un secreto. Si otro proceso ha modificado el secreto, la operación de actualización no se llevará a cabo.

gcloud

Antes de usar los datos de los comandos que se indican a continuación, haz los siguientes cambios:

  • SECRET_ID: el ID del secreto.
  • LOCATION: la Google Cloud ubicación del secreto.
  • KEY: nombre de la etiqueta.
  • VALUE: el valor de etiqueta correspondiente.
  • ETAG: la etiqueta de entidad del secreto. El ETag debe incluir las comillas. Por ejemplo, si el valor de ETag era "abc", el valor con escape de shell sería "\"abc\"".

Ejecuta el siguiente comando:

Linux, macOS o Cloud Shell

gcloud secrets update SECRET_ID --location=LOCATION \
    --update-labels "KEY=VALUE" \
    --etag "ETAG"

Windows (PowerShell)

gcloud secrets update SECRET_ID --location=LOCATION `
    --update-labels "KEY=VALUE" `
    --etag "ETAG"

Windows (cmd.exe)

gcloud secrets update SECRET_ID --location=LOCATION ^
    --update-labels "KEY=VALUE" ^
    --etag "ETAG"

La respuesta devuelve el secreto.

REST

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • LOCATION: la Google Cloud ubicación del secreto.
  • PROJECT_ID: el ID del proyecto. Google Cloud
  • SECRET_ID: el ID del secreto.
  • ETAG: la etiqueta de entidad del secreto. El ETag se especifica como un campo en el secreto y debe incluir las comillas correspondientes. Por ejemplo, si el valor de ETag era "abc", el valor con caracteres de escape JSON sería {"etag":"\"abc\""}.
  • KEY: nombre de la etiqueta.
  • VALUE: el valor de etiqueta correspondiente.

Método HTTP y URL:

PATCH https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID?updateMask=labels

Cuerpo JSON de la solicitud:

{"etag":"ETAG", "labels":{"KEY": "VALUE"}}

Para enviar tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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

PowerShell

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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

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

Deberías recibir una respuesta JSON similar a la siguiente:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID",
  "createTime": "2024-09-04T04:06:00.660420Z",
  "labels": {
    "KEY": "VALUE"
  },
  "etag": "\"162145a4f894d5\""
}

Go

Para ejecutar este código, primero debes configurar un entorno de desarrollo de Go e instalar el SDK de Go de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito cloud-platform.

import (
	"context"
	"fmt"
	"io"

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

// updateSecretWithEtag updates the metadata about an existing secret.
func UpdateRegionalSecretWithEtag(w io.Writer, projectId, locationId, secretId, etag string) error {
	// name := "projects/my-project/locations/my-location/secrets/my-secret"
	// etag := `"123"`

	// Create the client.
	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 regional secretmanager client: %w", err)
	}
	defer client.Close()

	name := fmt.Sprintf("projects/%s/locations/%s/secrets/%s", projectId, locationId, secretId)
	// Build the request.
	req := &secretmanagerpb.UpdateSecretRequest{
		Secret: &secretmanagerpb.Secret{
			Name: name,
			Etag: etag,
			Labels: map[string]string{
				"secretmanager": "rocks",
			},
		},
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"labels"},
		},
	}

	// Call the API.
	result, err := client.UpdateSecret(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to update regional secret: %w", err)
	}
	fmt.Fprintf(w, "Updated regional secret: %s\n", result.Name)
	return nil
}

Java

Para ejecutar este código, primero debes configurar un entorno de desarrollo de Java e instalar el SDK de Java de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito cloud-platform.

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.SecretName;
import com.google.protobuf.FieldMask;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;

public class UpdateRegionalSecretWithEtag {

  public static void main(String[] args) throws IOException {
    // 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 to update.
    String secretId = "your-secret-id";
    // Etag associated with the secret. Quotes should be included as part of the string.
    String etag = "\"1234\"";
    updateRegionalSecretWithEtag(projectId, locationId, secretId, etag);
  }

  // Update an existing secret with etag.
  public static Secret updateRegionalSecretWithEtag(
      String projectId, String locationId, String secretId, String etag)
      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 name.
      SecretName secretName = 
          SecretName.ofProjectLocationSecretName(projectId, locationId, secretId);

      // Build the updated secret.
      Secret secret =
          Secret.newBuilder()
              .setName(secretName.toString())
              .setEtag(etag)
              .putLabels("secretmanager", "rocks")
              .build();

      // Build the field mask.
      FieldMask fieldMask = FieldMaskUtil.fromString("labels");

      // Update the secret.
      Secret updatedSecret = client.updateSecret(secret, fieldMask);
      System.out.printf("Updated regional secret %s\n", updatedSecret.getName());

      return updatedSecret;
    }
  }
}

Python

Para ejecutar este código, primero debes configurar un entorno de desarrollo de Python e instalar el SDK de Python de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito cloud-platform.

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


def update_regional_secret_with_etag(
    project_id: str,
    location_id: str,
    secret_id: str,
    etag: str,
) -> secretmanager_v1.UpdateSecretRequest:
    """
    Update the metadata about an existing secret, using etag.
    """

    # 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 secret.
    name = f"projects/{project_id}/locations/{location_id}/secrets/{secret_id}"

    # Update the secret.
    secret = {"name": name, "labels": {"secretmanager": "rocks"}, "etag": etag}
    update_mask = {"paths": ["labels"]}
    response = client.update_secret(
        request={"secret": secret, "update_mask": update_mask}
    )

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

    return response

Actualizar una versión de un secreto con etiquetas ETag

En esta sección se describe cómo usar ETags al actualizar una versión de un secreto. Si otro proceso ha modificado la versión del secreto, no se podrá realizar la operación de actualización.

En este ejemplo de código se describe cómo inhabilitar una versión secreta con ETags. También puede especificar ETags durante otras operaciones de mutación de secretos, como cuando habilita versiones inhabilitadas o destruye versiones de secretos. Consulta los códigos de ejemplo de Secret Manager.

gcloud

Antes de usar los datos de los comandos que se indican a continuación, haz los siguientes cambios:

  • VERSION_ID: el ID de la versión del secreto.
  • SECRET_ID: el ID del secreto.
  • LOCATION: la Google Cloud ubicación del secreto.
  • ETAG: la etiqueta de entidad. El ETag debe incluir las comillas. Por ejemplo, si el valor de ETag era "abc", el valor con escape de shell sería "\"abc\"".

Ejecuta el siguiente comando:

Linux, macOS o Cloud Shell

gcloud secrets versions disable VERSION_ID \
  --secret SECRET_ID \
  --location=LOCATION \
  --etag "ETAG"

Windows (PowerShell)

gcloud secrets versions disable VERSION_ID `
  --secret SECRET_ID `
  --location=LOCATION `
  --etag "ETAG"

Windows (cmd.exe)

gcloud secrets versions disable VERSION_ID ^
  --secret SECRET_ID ^
  --location=LOCATION ^
  --etag "ETAG"

La respuesta devuelve el secreto.

REST

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • LOCATION: la Google Cloud ubicación del secreto.
  • PROJECT_ID: el ID del proyecto. Google Cloud
  • SECRET_ID: el ID del secreto.
  • VERSION_ID: el ID de la versión del secreto.
  • ETAG: la etiqueta de entidad de la versión del secreto. El ETag se especifica como un campo en SecretVersion y debe incluir las comillas. Por ejemplo, si el valor de ETag era "abc", el valor con caracteres de escape JSON sería {"etag":"\"abc\""}.

Método HTTP y URL:

POST https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID/versions/VERSION_ID:disable

Cuerpo JSON de la solicitud:

{"etag":"ETAG"}

Para enviar tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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

PowerShell

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

$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.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID/versions/VERSION_ID:disable" | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la siguiente:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID/versions/VERSION_ID",
  "createTime": "2024-09-04T06:41:57.859674Z",
  "state": "DISABLED",
  "etag": "\"1621457b3c1459\""
}

Go

Para ejecutar este código, primero debes configurar un entorno de desarrollo de Go e instalar el SDK de Go de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito cloud-platform.

import (
	"context"
	"fmt"

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

// disableSecretVersionWithEtag disables the given secret version. Future requests will
// throw an error until the secret version is enabled. Other secrets versions
// are unaffected.
func DisableRegionalSecretVersionWithEtag(projectId, locationId, secretId, versionId, etag string) error {
	// name := "projects/my-project/locations/my-location/secrets/my-secret/versions/5"
	// etag := `"123"`

	// Create the client.
	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 regional secretmanager client: %w", err)
	}
	defer client.Close()

	name := fmt.Sprintf("projects/%s/locations/%s/secrets/%s/versions/%s", projectId, locationId, secretId, versionId)
	// Build the request.
	req := &secretmanagerpb.DisableSecretVersionRequest{
		Name: name,
		Etag: etag,
	}

	// Call the API.
	if _, err := client.DisableSecretVersion(ctx, req); err != nil {
		return fmt.Errorf("failed to disable regional secret version: %w", err)
	}
	return nil
}

Java

Para ejecutar este código, primero debes configurar un entorno de desarrollo de Java e instalar el SDK de Java de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito cloud-platform.

import com.google.cloud.secretmanager.v1.DisableSecretVersionRequest;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import com.google.cloud.secretmanager.v1.SecretVersion;
import com.google.cloud.secretmanager.v1.SecretVersionName;
import java.io.IOException;

public class DisableRegionalSecretVersionWithEtag {

  public static void main(String[] args) throws IOException {
    // 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";
    // Version of the Secret ID you want to disable.
    String versionId = "your-version-id";
    // Etag associated with the secret. Quotes should be included as part of the string.
    String etag = "\"1234\"";
    disableRegionalSecretVersionWithEtag(projectId, locationId, secretId, versionId, etag);
  }

  // Disable an existing secret version.
  public static SecretVersion disableRegionalSecretVersionWithEtag(
      String projectId, String locationId, String secretId, String versionId, String etag)
      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 name from the version.
      SecretVersionName secretVersionName 
            = SecretVersionName.ofProjectLocationSecretSecretVersionName(
            projectId, locationId, secretId, versionId);

      // Build the request.
      DisableSecretVersionRequest request =
          DisableSecretVersionRequest.newBuilder()
              .setName(secretVersionName.toString())
              .setEtag(etag)
              .build();

      // Disable the secret version.
      SecretVersion version = client.disableSecretVersion(request);
      System.out.printf("Disabled regional secret version %s\n", version.getName());

      return version;
    }
  }
}

Python

Para ejecutar este código, primero debes configurar un entorno de desarrollo de Python e instalar el SDK de Python de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito cloud-platform.

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


def disable_regional_secret_version_with_etag(
    project_id: str,
    location_id: str,
    secret_id: str,
    version_id: str,
    etag: str,
) -> secretmanager_v1.DisableSecretVersionRequest:
    """
    Disables the given secret version. Future requests will throw an error until
    the secret version is enabled. Other secrets versions are unaffected.
    """

    # 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 secret version.
    name = f"projects/{project_id}/locations/{location_id}/secrets/{secret_id}/versions/{version_id}"

    # Build the request.
    request = secretmanager_v1.types.service.DisableSecretVersionRequest(
        name=name,
        etag=etag,
    )

    # Disable the secret version.
    response = client.disable_secret_version(request=request)

    print(f"Disabled secret version: {response.name}")

    return response

Siguientes pasos