Use etiquetas de entidade para o controlo de concorrência otimista

O Secret Manager suporta a utilização de etiquetas de entidade (ETags) para o controlo de simultaneidade otimista.

Em alguns casos, dois processos que atualizam o mesmo recurso em paralelo podem interferir entre si, em que o último processo substitui o esforço do primeiro.

As ETags oferecem um meio de controlo de simultaneidade otimista, permitindo que os processos verifiquem se um recurso foi modificado antes de tomar medidas nesse recurso.

Use ETags com o Secret Manager

Os seguintes pedidos de modificação de recursos suportam ETags:

Num pedido secrets.patch, o ETag do pedido está incorporado nos dados Secret. Todos os outros pedidos aceitam um parâmetro etag opcional.

Se for fornecido um ETag e este corresponder ao ETag do recurso atual, o pedido é bem-sucedido. Caso contrário, falha com um erro FAILED_PRECONDITION e um código de estado HTTP 400. Se não for fornecido um ETag, o pedido prossegue sem verificar o valor ETag armazenado atualmente.

As ETags de recursos são geradas na criação de recursos (projects.secrets.create, projects.secrets.addVersion) e atualizadas para cada um dos pedidos de modificação indicados acima. Um pedido de modificação apenas atualiza o ETag do recurso ao qual se aplica. Ou seja, a atualização de uma versão do segredo não afeta o ETag do segredo e, da mesma forma, a atualização do ETag não afeta a versão do segredo.

Mesmo quando uma atualização não altera o estado de um recurso, continua a atualizar o ETag do recurso.

Considere o seguinte exemplo:

  • O utilizador 1 tenta ativar uma versão secreta sem saber que já está ativada. O sistema processa esta ação, não alterando nada além do ETag da versão.

  • O utilizador 2, que usa o ETag antigo, tenta desativar a versão.

  • Esta ação falha porque o sistema reconhece o ETag mais recente, que indica uma intenção mais recente de manter a versão ativada.

Mesmo as atualizações aparentemente menores são importantes devido às alterações da ETag. Isto garante a consistência dos dados, especialmente com vários utilizadores ou sistemas a interagir com o mesmo recurso.

O recurso etag é devolvido na resposta sempre que um recurso (Secret ou SecretVersion) é incluído.

Elimine um segredo com ETags

Esta secção descreve a utilização de ETags quando elimina um segredo. Se o código secreto tiver sido modificado por outro processo, a operação de eliminação falha.

gcloud

Antes de usar qualquer um dos dados de comandos abaixo, faça as seguintes substituições:

  • SECRET_ID: o ID do segredo ou o identificador totalmente qualificado do segredo.
  • LOCATION: a Google Cloud localização do segredo.
  • ETAG: a etiqueta de entidade do segredo. A ETag tem de incluir as aspas. Por exemplo, se o valor ETag fosse "abc", o valor com carateres de escape da shell seria "\"abc\"".

Execute o seguinte comando:

Linux, macOS ou 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 qualquer um dos dados do pedido, faça as seguintes substituições:

  • LOCATION: a Google Cloud localização do segredo.
  • PROJECT_ID: o Google Cloud ID do projeto.
  • SECRET_ID: o ID do segredo ou o identificador totalmente qualificado do segredo.
  • ETAG: a etiqueta de entidade do segredo. O ETag é especificado como parte da string de consulta do URL e tem de ser codificado por URL. Por exemplo, se o valor ETag for "abc", o valor codificado por URL seria %22abc%22 porque o caráter de aspas é codificado como %22.

Método HTTP e URL:

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

Corpo JSON do pedido:

{}

Para enviar o seu pedido, escolha uma destas opções:

curl

Guarde o corpo do pedido num ficheiro com o nome request.json, e execute o seguinte 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

Guarde o corpo do pedido num ficheiro com o nome request.json, e execute o seguinte 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

Deve receber uma resposta JSON semelhante à seguinte:

{}

Go

Para executar este código, primeiro configure um ambiente de desenvolvimento Go e instale o SDK Go do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o â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 executar este código, primeiro configure um ambiente de desenvolvimento Java e instale o SDK Java do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o â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 executar este código, primeiro configure um ambiente de desenvolvimento Python e instale o SDK Python do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o â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)

Atualize um segredo com ETags

Esta secção descreve a utilização de ETags ao atualizar um segredo. Se o segredo tiver sido modificado por outro processo, a operação de atualização falha.

gcloud

Antes de usar qualquer um dos dados de comandos abaixo, faça as seguintes substituições:

  • SECRET_ID: o ID do segredo ou o identificador totalmente qualificado do segredo.
  • LOCATION: a Google Cloud localização do segredo.
  • KEY: o nome da etiqueta.
  • VALUE: o valor da etiqueta correspondente.
  • ETAG: a etiqueta de entidade do segredo. A ETag tem de incluir as aspas. Por exemplo, se o valor ETag fosse "abc", o valor com carateres de escape da shell seria "\"abc\"".

Execute o seguinte comando:

Linux, macOS ou 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"

A resposta devolve o segredo.

REST

Antes de usar qualquer um dos dados do pedido, faça as seguintes substituições:

  • LOCATION: a Google Cloud localização do segredo.
  • PROJECT_ID: o Google Cloud ID do projeto.
  • SECRET_ID: o ID do segredo ou o identificador totalmente qualificado do segredo.
  • ETAG: a etiqueta de entidade do segredo. O ETag é especificado como um campo no Secret e tem de incluir as aspas. Por exemplo, se o valor ETag fosse "abc", o valor com carateres de escape JSON seria {"etag":"\"abc\""}.
  • KEY: o nome da etiqueta.
  • VALUE: o valor da etiqueta correspondente.

Método HTTP e URL:

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

Corpo JSON do pedido:

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

Para enviar o seu pedido, escolha uma destas opções:

curl

Guarde o corpo do pedido num ficheiro com o nome request.json, e execute o seguinte 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

Guarde o corpo do pedido num ficheiro com o nome request.json, e execute o seguinte 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

Deve receber uma resposta JSON semelhante à seguinte:

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

Go

Para executar este código, primeiro configure um ambiente de desenvolvimento Go e instale o SDK Go do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o â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 executar este código, primeiro configure um ambiente de desenvolvimento Java e instale o SDK Java do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o â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 executar este código, primeiro configure um ambiente de desenvolvimento Python e instale o SDK Python do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o â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

Atualize uma versão secreta com ETags

Esta secção descreve a utilização de ETags quando atualiza uma versão secreta. Se a versão do segredo tiver sido modificada por outro processo, a operação de atualização falha.

O exemplo de código aqui descrito descreve a desativação de uma versão secreta com ETags. Também pode especificar ETags durante outras operações de mutação de segredos, como quando ativa versões desativadas ou destrói versões de segredos. Consulte os exemplos de código para o Secret Manager.

gcloud

Antes de usar qualquer um dos dados de comandos abaixo, faça as seguintes substituições:

  • VERSION_ID: o ID da versão do segredo.
  • SECRET_ID: o ID do segredo ou o identificador totalmente qualificado do segredo.
  • LOCATION: a Google Cloud localização do segredo.
  • ETAG: a etiqueta da entidade. A ETag tem de incluir as aspas. Por exemplo, se o valor ETag fosse "abc", o valor com carateres de escape da shell seria "\"abc\"".

Execute o seguinte comando:

Linux, macOS ou 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"

A resposta devolve o segredo.

REST

Antes de usar qualquer um dos dados do pedido, faça as seguintes substituições:

  • LOCATION: a Google Cloud localização do segredo
  • PROJECT_ID: o Google Cloud ID do projeto
  • SECRET_ID: o ID do segredo ou o identificador totalmente qualificado do segredo
  • VERSION_ID: o ID da versão do segredo
  • ETAG: a etiqueta de entidade da versão do segredo. O ETag é especificado como um campo no SecretVersion e tem de incluir as aspas. Por exemplo, se o valor ETag fosse "abc", o valor com carateres de escape JSON seria {"etag":"\"abc\""}.

Método HTTP e URL:

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

Corpo JSON do pedido:

{"etag":"ETAG"}

Para enviar o seu pedido, escolha uma destas opções:

curl

Guarde o corpo do pedido num ficheiro com o nome request.json, e execute o seguinte 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

Guarde o corpo do pedido num ficheiro com o nome request.json, e execute o seguinte 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

Deve receber uma resposta JSON semelhante à seguinte:

{
  "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 executar este código, primeiro configure um ambiente de desenvolvimento Go e instale o SDK Go do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o â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 executar este código, primeiro configure um ambiente de desenvolvimento Java e instale o SDK Java do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o â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 executar este código, primeiro configure um ambiente de desenvolvimento Python e instale o SDK Python do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o â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

O que se segue?