יצירה וניהול של תגים לסודות אזוריים

מדריך זה מתאר כיצד ליצור ולנהל תגיות בסודות אזוריים. אתם יכולים להשתמש בתגים כדי לקבץ סודות קשורים ב-Secret Manager ולאחסן מטא נתונים על המשאבים האלה על סמך התגים שלהם.

מידע על התגים

תג הוא זוג מפתח-ערך שניתן לצרף למשאב בתוךCloud de Confiance by S3NS. אתם יכולים להשתמש בתגים כדי להגדיר תנאי לאישור או לדחייה של כללי מדיניות אם תג ספציפי מצורף או לא מצורף למשאב. לדוגמה, אתם יכולים להתנות את מתן התפקידים ב-IAM בהתאם לתגים. למידע נוסף, ראו סקירת תגים.

כדי לצרף תגים למשאבים, יוצרים משאב של קישור תגים שמקשר את הערך ל Cloud de Confiance by S3NS משאב.

ההרשאות הנדרשות

כדי לקבל את ההרשאות שדרושות לניהול תגים, צריך לבקש מהאדמין להקצות לכם את תפקידי ה-IAM הבאים:

  • ‫Tag Viewer (roles/resourcemanager.tagViewer) במשאבים שהתגים מצורפים אליהם
  • כדי להציג ולנהל תגים ברמת הארגון: צפייה בארגון (roles/resourcemanager.organizationViewer) באותו ארגון
  • יצירה, עדכון ומחיקה של הגדרות תגים: Tag Administrator (roles/resourcemanager.tagAdmin) on the resource you're creating, updating, or deleting tags for
  • צירוף והסרה של תגים ממשאבים: Tag User (roles/resourcemanager.tagUser) על ערך התג ועל המשאבים שאתם מצרפים או מסירים מהם את ערך התג

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

יכול להיות שאפשר לקבל את ההרשאות הנדרשות גם באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש.

כדי לצרף תגים לסודות ב-Secret Manager, צריך את התפקיד Secret Manager Admin ‏ (roles/secretmanager.admin).

יצירת מפתחות וערכים של תגים

לפני שמצרפים תג, צריך ליצור תג ולהגדיר את הערך שלו. למידע נוסף, ראו יצירת תגית והוספת ערך תגית.

הוספת תגים במהלך יצירת משאב

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

המסוף

  1. עבור לדף מנהל סודי בקונסולה Cloud de Confiance .
  2. מעבר אל Secret Manager

  3. בדף Secret Manager (ניהול סודות), לוחצים על הכרטיסייה Regional secrets (סודות אזוריים).
  4. בוחרים באפשרות ליצירת סוד אזורי חדש.
  5. לוחצים על ניהול תגים.
  6. אם הארגון שלכם לא מופיע בחלונית Manage tags, לוחצים על Select scope for tags ובוחרים את הארגון או הפרויקט.
  7. לוחצים על הוספת תג.
  8. בוחרים את מפתח התג ואת ערך התג מהרשימה. אפשר לסנן את הרשימה באמצעות מילות מפתח.
  9. לוחצים על Save. הקטע Tags (תגים) מתעדכן במידע על התגים.
  10. יוצרים את הסוד האזורי. הסוד האזורי החדש נוצר עם התגים שצוינו.

gcloud

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

  • ‫SECRET_ID: המזהה הייחודי של הסוד.
  • ‫LOCATION: המיקום של הסוד.
  • ‫TAG_KEY: המזהה הקבוע או השם ממרחב השמות של מפתח התג שמצורף – לדוגמה, tagKeys/567890123456.
  • ‫TAG_VALUE: המזהה הקבוע או השם ממרחב השמות של ערך התג שמצורף – לדוגמה, tagValues/567890123456.

כדי לציין כמה תגים, מפרידים ביניהם באמצעות פסיק, לדוגמה, TAGKEY1=TAGVALUE1,TAGKEY2=TAGVALUE2.

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

‫Linux,‏ macOS או Cloud Shell

gcloud secrets create SECRET_ID --location=LOCATION --tags=TAG_KEY=TAG_VALUE

‏Windows (PowerShell)

gcloud secrets create SECRET_ID --location=LOCATION --tags=TAG_KEY=TAG_VALUE

Windows‏ (cmd.exe)

gcloud secrets create SECRET_ID --location=LOCATION --tags=TAG_KEY=TAG_VALUE

REST

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

  • ‫LOCATION: המיקום של הסוד
  • ‫PROJECT_ID: מזהה הפרויקט
  • ‫SECRET_ID: המזהה הייחודי של הסוד
  • ‫TAGKEY_NAME: המזהה הקבוע או השם ממרחב השמות של מפתח התג שמצורף – לדוגמה, tagKeys/567890123456.
  • ‫TAGVALUE_NAME: המזהה הקבוע או השם ממרחב השמות של ערך התג שמצורף – לדוגמה, tagValues/567890123456.

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

POST https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets?secretId=SECRET_ID

גוף בקשת JSON:

{
  "tags": {
    "TAGKEY_NAME": "TAGVALUE_NAME"
  }
}

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

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?secretId=SECRET_ID"

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?secretId=SECRET_ID" | Select-Object -Expand Content

אמורים לקבל קוד סטטוס של הצלחה (2xx) ותגובה ריקה.

C#

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת C# ‎ ולהתקין את Secret Manager C# SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף cloud-platform.


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

public class CreateRegionalSecretWithTagsSample
{
    public Secret CreateRegionalSecretWithTags(
      string projectId = "my-project",
      string locationId = "my-location",
      string secretId = "my-secret",
      string tagKeyName = "tagKey/value",
      string tagValueName = "tagValue/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
        {
            Tags =
            {
                { tagKeyName, tagValueName }
            },
        };

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

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

// createSecretWithTags creates a new regional secret with the given name and tags.
func createRegionalSecretWithTags(w io.Writer, projectId, locationId, secretId, tagKey, tagValue string) error {
	parent := fmt.Sprintf("projects/%s/locations/%s", projectId, locationId)

	// 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()

	// Build the request.
	req := &secretmanagerpb.CreateSecretRequest{
		Parent:   parent,
		SecretId: secretId,
		Secret: &secretmanagerpb.Secret{
			Tags: map[string]string{
				tagKey: tagValue,
			},
		},
	}

	// Call the API.
	result, err := client.CreateSecret(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create secret: %w", err)
	}
	fmt.Fprintf(w, "Created secret with tags: %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.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 CreateRegionalSecretWithTags {

  public static void createRegionalSecretWithTags() 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 tag to be added
    String tagKey = "your-tag-key";
    // This is the value of the tag to be added
    String tagValue = "your-tag-value";
    createRegionalSecretWithTags(projectId, locationId, secretId, tagKey, tagValue);
  }

  // Create a secret with tags.
  public static Secret createRegionalSecretWithTags(
       String projectId,
       String locationId,
       String secretId,
       String tagKey,
       String tagValue)
      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 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 tags.
      Secret secret =
          Secret.newBuilder()
            .putTags(tagKey, tagValue)
            .build();

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

Node.js

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Secret Manager Node.js SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף cloud-platform.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const locationId = 'my-location';
// const secretId = 'my-secret';
// const tagKey = 'tagKeys/281475012216835';
// const tagValue = 'tagValues/281476592621530';
const parent = `projects/${projectId}/locations/${locationId}`;

// Imports the 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 createRegionalSecretWithTags() {
  const [secret] = await client.createSecret({
    parent: parent,
    secretId: secretId,
    secret: {
      tags: {
        [tagKey]: tagValue,
      },
    },
  });

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

createRegionalSecretWithTags();

PHP

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

כדי להריץ את הקוד הזה, קודם צריך לקרוא על שימוש ב-PHP ב-Google Cloud ולהתקין את Secret Manager PHP SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף cloud-platform.

// 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 $tagKey     Your tag key (e.g. 'tagKeys/281475012216835')
 * @param string $tagValue   Your tag value (e.g. 'tagValues/281476592621530')
 */
function create_regional_secret_with_tags(string $projectId, string $locationId, string $secretId, string $tagKey, string $tagValue): 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 tags.
    $tags = [$tagKey => $tagValue];
    $secret ->setTags($tags);

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

Python

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת Python ולהתקין את Secret Manager Python SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף cloud-platform.

import argparse

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


def create_regional_secret_with_tags(
    project_id: str,
    location_id: str,
    secret_id: str,
    tag_key: str,
    tag_value: str,
) -> secretmanager_v1.Secret:
    """
    Create a new regional secret with the given name and associated tags. 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 API.
    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 secret.
    parent = f"projects/{project_id}/locations/{location_id}"

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

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

    return response

Ruby

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Ruby ולהתקין את Secret Manager Ruby SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף cloud-platform.

require "google/cloud/secret_manager"

##
# Create a regional secret with tags
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location_id [String] Your Google Cloud location (e.g. "us-west1")
# @param secret_id [String] Your secret name (e.g. "my-secret")
# @param tag_key [String] Your tag key (e.g. "my-tag-key")
# @param tag_value [String] Your tag value (e.g "my-tag-value")
#
def create_regional_secret_with_tags project_id:, location_id:, secret_id:, tag_key:, tag_value:
  # 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: {
      tags: {
        tag_key.name => tag_value.name
      }
    }
  )

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

הוספת תגים למשאבים קיימים

כדי להוסיף תג לסודות אזוריים קיימים:

המסוף

  1. עוברים לדף Secret Manager במסוף Cloud de Confiance .
  2. מעבר אל Secret Manager

  3. בוחרים את הסוד האזורי שרוצים לצרף אליו תג.
  4. לוחצים על תגים.
  5. אם הארגון שלך לא מופיע בחלונית תגיות, לחץ על בחר היקף. בוחרים את הארגון ולוחצים על פתיחה.
  6. לחץ על הוסף תגית.
  7. בוחרים את מפתח התג ואת ערך התג מהרשימה. אפשר לסנן את הרשימה באמצעות מילות מפתח.
  8. לוחצים על Save.
  9. בתיבת הדו-שיח אישור, לחץ על אישור כדי לצרף את התג.
  10. התראה מאשרת שהתגים עודכנו.

gcloud

כדי לצרף תג לסוד אזורי, צריך ליצור משאב של קישור תגים באמצעות הפקודה gcloud resource-manager tags bindings create:

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

  • TAGVALUE_NAME: המזהה הקבוע או השם במרווח השמות של ערך התג המצורף - לדוגמה, tagValues/567890123456.
  • ‫RESOURCE_ID הוא המזהה המלא של המשאב, כולל שם הדומיין של ה-API, כדי לזהות את סוג המשאב (//secretmanager.googleapis.com/). לדוגמה, כדי לצרף תג ל-projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID, המזהה המלא הוא //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID.
  • ‫LOCATION: המיקום של המשאב. אם אתם מצרף תגית למשאב גלובלי, כגון תיקייה או פרויקט, השמטו את הדגל הזה. אם מצרפים תג למשאב אזורי או למשאב של תחום מוגדר, צריך לציין את המיקום – לדוגמה, us-central1 (אזור) או us-central1-a (תחום).

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

‫Linux,‏ macOS או Cloud Shell

gcloud resource-manager tags bindings create \
    --tag-value=TAGVALUE_NAME \
    --parent=RESOURCE_ID \
    --location=LOCATION

‏Windows (PowerShell)

gcloud resource-manager tags bindings create `
    --tag-value=TAGVALUE_NAME `
    --parent=RESOURCE_ID `
    --location=LOCATION

Windows‏ (cmd.exe)

gcloud resource-manager tags bindings create ^
    --tag-value=TAGVALUE_NAME ^
    --parent=RESOURCE_ID ^
    --location=LOCATION

Node.js

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Secret Manager Node.js SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף cloud-platform.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const locationId = 'my-location';
// const secretId = 'my-secret';
// const tagValue = 'tagValues/281476592621530';
const parent = `projects/${projectId}/locations/${locationId}`;

// Imports the library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');
const {TagBindingsClient} = require('@google-cloud/resource-manager').v3;

// Adding the endpoint to call the regional
const options = {};
const bindingOptions = {};
options.apiEndpoint = `secretmanager.${locationId}.rep.googleapis.com`;
bindingOptions.apiEndpoint = `${locationId}-cloudresourcemanager.googleapis.com`;

// Instantiates a client
const client = new SecretManagerServiceClient(options);
const resourcemanagerClient = new TagBindingsClient(bindingOptions);

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

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

  const [operation] = await resourcemanagerClient.createTagBinding({
    tagBinding: {
      parent: `//secretmanager.googleapis.com/${secret.name}`,
      tagValue: tagValue,
    },
  });
  const [response] = await operation.promise();
  console.log('Created Tag Binding', response.name);
}

bindTagsToRegionalSecret();

PHP

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

כדי להריץ את הקוד הזה, קודם צריך לקרוא על שימוש ב-PHP ב-Google Cloud ולהתקין את Secret Manager PHP SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף cloud-platform.

// 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;
use Google\Cloud\ResourceManager\V3\Client\TagBindingsClient;
use Google\Cloud\ResourceManager\V3\CreateTagBindingRequest;
use Google\Cloud\ResourceManager\V3\TagBinding;

/**
 * @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 $tagValue   Your tag value (e.g. 'tagValues/281476592621530')
 */
function bind_tags_to_regional_secret(string $projectId, string $locationId, string $secretId, string $tagValue): 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();

    // 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' . PHP_EOL, $newSecret->getName());

    // Specify regional endpoint.
    $tagBindOptions = ['apiEndpoint' => "$locationId-cloudresourcemanager.googleapis.com"];
    $tagBindingsClient = new TagBindingsClient($tagBindOptions);
    $tagBinding = (new TagBinding())
        ->setParent('//secretmanager.googleapis.com/' . $newSecret->getName())
        ->setTagValue($tagValue);

    // Build the request.
    $request = (new CreateTagBindingRequest())
        ->setTagBinding($tagBinding);

    // Create the tag binding.
    $operationResponse = $tagBindingsClient->createTagBinding($request);
    $operationResponse->pollUntilComplete();

    // Check if the operation succeeded.
    if ($operationResponse->operationSucceeded()) {
        printf('Tag binding created for secret %s with tag value %s' . PHP_EOL, $newSecret->getName(), $tagValue);
    } else {
        $error = $operationResponse->getError();
        printf('Error in creating tag binding: %s' . PHP_EOL, $error->getMessage());
    }
}

Python

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת Python ולהתקין את Secret Manager Python SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף cloud-platform.

import argparse

# Import the Secret Manager and Resource Manager client library.
from google.cloud import resourcemanager_v3
from google.cloud import secretmanager


def bind_tags_to_regional_secret(
    project_id: str,
    location_id: str,
    secret_id: str,
    tag_value: str,
) -> resourcemanager_v3.TagBinding:
    """
    Create a new regional secret with the given name, and then bind an existing
    tag to it. 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.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.
    secret_response = client.create_secret(
        request={
            "parent": parent,
            "secret_id": secret_id,
        }
    )

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

    # Endpoint to call the regional secret manager sever
    resource_manager_api_endpoint = f"{location_id}-cloudresourcemanager.googleapis.com"

    # Create the resource manager client
    resource_manager_client = resourcemanager_v3.TagBindingsClient(
        client_options={"api_endpoint": resource_manager_api_endpoint},
    )

    # Create the tag binding
    request = resourcemanager_v3.CreateTagBindingRequest(
        tag_binding=resourcemanager_v3.TagBinding(
            parent=f"//secretmanager.googleapis.com/{secret_response.name}",
            tag_value=f"{tag_value}",
        ),
    )

    # Create the tag binding
    operation = resource_manager_client.create_tag_binding(request=request)

    # Wait for the operation to complete
    response = operation.result()

    # Print the tag binding
    print(f"Created tag binding: {response.name}")

    return response

הצגת רשימת תגים שמצורפים למשאבים

אפשר לראות רשימה של תגי קישור שמצורפים ישירות לסוד האזורי או עוברים אליו בירושה.

המסוף

  1. עבור לדף מנהל סודי בקונסולה Cloud de Confiance .
  2. מעבר אל Secret Manager

  3. התגים מוצגים בעמודה Tags (תגים) של הסוד.

gcloud

כדי לקבל רשימה של התאמות תגים שצורפו למשאב, משתמשים בפקודה gcloud resource-manager tags bindings list:

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

  • ‫RESOURCE_ID הוא המזהה המלא של המשאב, כולל שם הדומיין של ה-API, כדי לזהות את סוג המשאב (//secretmanager.googleapis.com/). לדוגמה, כדי לצרף תג ל-projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID, המזהה המלא הוא //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID.
  • LOCATION: מיקום המשאב שלך. אם אתם צופים בתג שמצורף למשאב גלובלי, כמו תיקייה או פרויקט, אל תכללו את הדגל הזה. אם צופים בתג שמצורף למשאב אזורי או למשאב של תחום מוגדר, צריך לציין את המיקום – לדוגמה, us-central1 (אזור) או us-central1-a (תחום).

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

‫Linux,‏ macOS או Cloud Shell

gcloud resource-manager tags bindings list \
    --parent=RESOURCE_ID \
    --location=LOCATION

‏Windows (PowerShell)

gcloud resource-manager tags bindings list `
    --parent=RESOURCE_ID `
    --location=LOCATION

Windows‏ (cmd.exe)

gcloud resource-manager tags bindings list ^
    --parent=RESOURCE_ID ^
    --location=LOCATION

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

  name: tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F7890123456/tagValues/567890123456
    tagValue: tagValues/567890123456
    resource: //secretmanager.googleapis.com/projects/project-abc/secrets/secret-xyz

ניתוק תגים ממשאבים

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

המסוף

  1. עבור לדף מנהל סודי בקונסולה Cloud de Confiance .
  2. מעבר אל Secret Manager

  3. בוחרים את הסוד האזורי שרוצים להסיר ממנו תג.
  4. לוחצים על תגים.
  5. בחלונית תגים, לצד התג שרוצים לנתק, לוחצים על מחיקת הפריט.
  6. לוחצים על Save.
  7. בתיבת הדו-שיח אישור, לוחצים על אישור כדי לבטל את הקישור של התג.

התראה מאשרת שהתגים עודכנו.

gcloud

כדי למחוק קישור תגים, משתמשים בפקודה gcloud resource-manager tags bindings delete:

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

  • TAGVALUE_NAME: המזהה הקבוע או השם במרווח השמות של ערך התג המצורף - לדוגמה, tagValues/567890123456.
  • ‫RESOURCE_ID הוא המזהה המלא של המשאב, כולל שם הדומיין של ה-API, כדי לזהות את סוג המשאב (//secretmanager.googleapis.com/). לדוגמה, כדי לצרף תג ל-projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID, המזהה המלא הוא //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID.
  • ‫LOCATION: המיקום של המשאב. אם אתם מצרף תגית למשאב גלובלי, כגון תיקייה או פרויקט, השמטו את הדגל הזה. אם מצרפים תג למשאב אזורי או למשאב של תחום מוגדר, צריך לציין את המיקום – לדוגמה, us-central1 (אזור) או us-central1-a (תחום).

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

‫Linux,‏ macOS או Cloud Shell

gcloud resource-manager tags bindings delete \
    --tag-value=TAGVALUE_NAME \
    --parent=RESOURCE_ID \
    --location=LOCATION

‏Windows (PowerShell)

gcloud resource-manager tags bindings delete `
    --tag-value=TAGVALUE_NAME `
    --parent=RESOURCE_ID `
    --location=LOCATION

Windows‏ (cmd.exe)

gcloud resource-manager tags bindings delete ^
    --tag-value=TAGVALUE_NAME ^
    --parent=RESOURCE_ID ^
    --location=LOCATION

מחיקת מפתחות וערכים של תגים

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

תנאים ותגים בניהול הזהויות והרשאות הגישה (IAM)

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

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