שימוש בתגי ישות לבקרת בו-זמניות אופטימית

‫Secret Manager תומך בשימוש בתגי ישות (ETags) לבקרת בו-זמניות אופטימית.

במקרים מסוימים, שני תהליכים שמעדכנים את אותו משאב במקביל עלולים להפריע זה לזה, כך שהתהליך השני יחליף את הפעולה של התהליך הראשון.

תגי ETag מספקים אמצעי לבקרת בו-זמניות אופטימית, בכך שהם מאפשרים לתהליכים לראות אם משאב שונה לפני שהם מבצעים פעולה במשאב הזה.

שימוש ב-ETags עם Secret Manager

בקשות השינוי הבאות של משאבים תומכות ב-ETags:

בבקשת secrets.patch, תג ה-ETag של הבקשה מוטמע בנתוני Secret. כל הבקשות האחרות מקבלות פרמטר אופציונלי etag.

אם מצוין ETag והוא תואם ל-ETag הנוכחי של המשאב, הבקשה תצליח. אחרת, היא תיכשל עם השגיאה FAILED_PRECONDITION וקוד הסטטוס 400 של HTTP. אם לא מצוין ETag, הבקשה תמשיך בלי לבדוק את ערך ה-ETag שמאוחסן כרגע.

תגי ETag של משאבים נוצרים בזמן יצירת המשאב (projects.secrets.create,‏ projects.secrets.addVersion) ומתעדכנים עבור כל אחת מבקשות השינוי שמופיעות ברשימה שלמעלה. בקשת שינוי מעדכנת רק את ה-ETag של המשאב שאליו היא מתייחסת. כלומר, עדכון של גרסת סוד לא משפיע על ה-ETag של הסוד, וכך גם עדכון של ה-ETag לא משפיע על גרסת הסוד.

גם אם עדכון לא משנה את מצב המשאב, הוא עדיין מעדכן את ה-ETag של המשאב.

דוגמה:

  • משתמש 1 מנסה להפעיל גרסה סודית בלי לדעת שהיא כבר הופעלה. המערכת מעבדת את זה, ולא משנה שום דבר חוץ מה-ETag של הגרסה.

  • משתמש 2, שמשתמש ב-ETag הישן, מנסה להשבית את הגרסה.

  • הפעולה נכשלת כי המערכת מזהה את תג ה-ETag החדש יותר, שמציין כוונה עדכנית יותר להשאיר את הגרסה מופעלת.

גם עדכונים שנראים קלים חשובים בגלל שינויים ב-ETag. כך מובטחת עקביות הנתונים, במיוחד אם כמה משתמשים או מערכות מבצעים אינטראקציה עם אותו משאב.

המשאב etag מוחזר בתשובה בכל פעם שמשאב (Secret או SecretVersion) נכלל.

מחיקת סוד באמצעות ETags

בקטע הזה מוסבר איך משתמשים ב-ETags כשמוחקים סוד. אם סוד כלשהו שונה על ידי תהליך אחר, פעולת המחיקה נכשלת.

gcloud

לפני השימוש בנתוני הפקודה הבאים, צריך להחליף את הנתונים הבאים:

  • ‫SECRET_ID: המזהה של הסוד.
  • ‫LOCATION: Cloud de Confiance by S3NS המיקום של הסוד.
  • ‫ETAG: תג הישות של הסוד. תג ה-ETag חייב לכלול את המירכאות שמקיפות אותו. לדוגמה, אם ערך ה-ETag היה "abc", הערך אחרי הסרת התווים המיוחדים יהיה "\"abc\"".

מריצים את הפקודה הבאה:

‫Linux,‏ macOS או 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

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ‫LOCATION: Cloud de Confiance by S3NS המיקום של הסוד.
  • ‫PROJECT_ID: מזהה הפרויקט ב- Cloud de Confiance by S3NS .
  • ‫SECRET_ID: המזהה של הסוד.
  • ‫ETAG: תג הישות של הסוד. ה-ETag מצוין כחלק ממחרוזת השאילתה של כתובת ה-URL, והוא חייב להיות בקידוד URL. לדוגמה, אם ערך ה-ETag הוא "abc", הערך המקודד בכתובת ה-URL יהיה %22abc%22 כי התו של המירכאות מקודד כ-%22.

ה-method של ה-HTTP וכתובת ה-URL:

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

גוף בקשת JSON:

{}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

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

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

$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

אתם אמורים לקבל תגובת JSON שדומה לזו:

{}

Go

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Secret Manager Go SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף 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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Secret Manager Java SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף 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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת Python ולהתקין את Secret Manager Python SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף 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)

עדכון סוד באמצעות תגי ETags

בקטע הזה מוסבר איך משתמשים ב-ETags כשמעדכנים סוד. אם תהליך אחר שינה את הסוד, פעולת העדכון תיכשל.

gcloud

לפני השימוש בנתוני הפקודה הבאים, צריך להחליף את הנתונים הבאים:

  • ‫SECRET_ID: המזהה של הסוד.
  • ‫LOCATION: Cloud de Confiance by S3NS המיקום של הסוד.
  • ‫KEY: שם התווית.
  • ‫VALUE: ערך התווית התואם.
  • ‫ETAG: תג הישות של הסוד. תג ה-ETag חייב לכלול את המירכאות שמקיפות אותו. לדוגמה, אם ערך ה-ETag היה "abc", הערך אחרי הסרת התווים המיוחדים יהיה "\"abc\"".

מריצים את הפקודה הבאה:

‫Linux,‏ macOS או 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"

התשובה מחזירה את הסוד.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ‫LOCATION: Cloud de Confiance by S3NS המיקום של הסוד.
  • ‫PROJECT_ID: מזהה הפרויקט ב- Cloud de Confiance by S3NS .
  • ‫SECRET_ID: המזהה של הסוד.
  • ‫ETAG: תג הישות של הסוד. התג ETag מצוין כשדה ב-Secret וחייב לכלול את המרכאות שמסביב. לדוגמה, אם ערך ה-ETag היה "abc", הערך אחרי הוספת התו '\' יהיה {"etag":"\"abc\""}.
  • ‫KEY: שם התווית.
  • ‫VALUE: ערך התווית התואם.

ה-method של ה-HTTP וכתובת ה-URL:

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

גוף בקשת JSON:

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

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

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

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

$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

אתם אמורים לקבל תגובת JSON שדומה לזו:

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

Go

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Secret Manager Go SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף 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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Secret Manager Java SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף 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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת Python ולהתקין את Secret Manager Python SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף 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

עדכון גרסה של סוד באמצעות תגי ETags

בקטע הזה מתואר השימוש ב-ETags כשמעדכנים גרסה של סוד. אם גרסת הסוד עודכנה על ידי תהליך אחר, פעולת העדכון תיכשל.

בדוגמה הבאה מוצג קוד להשבתת גרסה של סוד באמצעות תגי ETags. אפשר גם לציין ETags במהלך פעולות אחרות של שינוי סודות, למשל כשמפעילים גרסאות מושבתות או כשמשמידים גרסאות של סודות. אפשר לעיין בדוגמאות הקוד של Secret Manager.

gcloud

לפני השימוש בנתוני הפקודה הבאים, צריך להחליף את הנתונים הבאים:

  • ‫VERSION_ID: המזהה של גרסת הסוד.
  • ‫SECRET_ID: המזהה של הסוד.
  • ‫LOCATION: Cloud de Confiance by S3NS המיקום של הסוד.
  • ‫ETAG: תג הישות. תג ה-ETag חייב לכלול את המירכאות שמקיפות אותו. לדוגמה, אם ערך ה-ETag היה "abc", הערך אחרי הסרת התווים המיוחדים יהיה "\"abc\"".

מריצים את הפקודה הבאה:

‫Linux,‏ macOS או 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"

התשובה מחזירה את הסוד.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ‫LOCATION: Cloud de Confiance by S3NS המיקום של הסוד.
  • ‫PROJECT_ID: מזהה הפרויקט ב- Cloud de Confiance by S3NS .
  • ‫SECRET_ID: המזהה של הסוד.
  • ‫VERSION_ID: המזהה של גרסת הסוד.
  • ‫ETAG: תג הישות של גרסת הסוד. התג ETag מוגדר כשדה ב-SecretVersion וחייב לכלול את המרכאות שמסביב. לדוגמה, אם ערך ה-ETag היה "abc", הערך אחרי הוספת התו '\' יהיה {"etag":"\"abc\""}.

ה-method של ה-HTTP וכתובת ה-URL:

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

גוף בקשת JSON:

{"etag":"ETAG"}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

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

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

$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

אתם אמורים לקבל תגובת JSON שדומה לזו:

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

Go

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Secret Manager Go SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף 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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Secret Manager Java SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף 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

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת Python ולהתקין את Secret Manager Python SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף 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

המאמרים הבאים