יצירה ותזמון של משימות בדיקה של Sensitive Data Protection

במאמר הזה נסביר בפירוט איך יוצרים משימת בדיקה ב-Sensitive Data Protection, ואיך מתזמנים משימות בדיקה חוזרות באמצעות יצירת טריגר למשימה. במאמר התחלה מהירה: יצירת טריגר למשימה ב-Sensitive Data Protection מוסבר בקצרה איך יוצרים טריגר חדש למשימה באמצעות ממשק המשתמש של Sensitive Data Protection.

מידע על משימות ביקורת וטריגרים של משימות

כש-Sensitive Data Protection מבצע סריקה כדי לזהות מידע אישי רגיש, כל סריקה פועלת כמשימה. בכל פעם שאתם מורים ל-Sensitive Data Protection לבדוק את מאגרי הנתונים שלכם ב- Google Cloud , כולל קטגוריות של Cloud Storage, טבלאות ב-BigQuery, סוגים של Datastore ונתונים חיצוניים, המערכת יוצרת ומריצה משאב של משימה.

כדי לתזמן משימות סריקה של Sensitive Data Protection, צריך ליצור טריגרים של משימות. טריגר של משימה מאפשר ליצור באופן אוטומטי משימות של Sensitive Data Protection על בסיס תקופתי, ואפשר גם להריץ אותו לפי דרישה.

למידע נוסף על משימות וטריגרים של משימות ב-Sensitive Data Protection, קראו את המאמר משימות וטריגרים של משימות.

יצירת משימת בדיקה חדשה

כדי ליצור משימת בדיקה חדשה ב-Sensitive Data Protection:

המסוף

בקטע Sensitive Data Protection במסוף Google Cloud , נכנסים לדף Create job or job trigger.

כניסה לדף Create job or job trigger

הדף Create job or job trigger כולל את הקטעים הבאים:

בחירת נתוני קלט

שם

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

מיקום

בתפריט Storage type, בוחרים את סוג המאגר שבו מאוחסנים הנתונים שרוצים לסרוק:

  • ‫Cloud Storage: מזינים את כתובת ה-URL של הקטגוריה שרוצים לסרוק, או בוחרים באפשרות Include/exclude בתפריט Location type ולוחצים על Browse כדי לעבור לקטגוריה או לתיקיית המשנה שרוצים לסרוק. מסמנים את התיבה Scan folder recursively כדי לסרוק את הספרייה שצוינה ואת כל הספריות שהיא מכילה. אם לא מסמנים את האפשרות הזו, המערכת סורקת רק את הספרייה שצוינה ולא ספריות משנה.
  • ‫BigQuery: מזינים את המזהים של הפרויקט, מערך הנתונים והטבלה שרוצים לסרוק.
  • Datastore: מזינים את המזהים של הפרויקט, מרחב השמות (אופציונלי) והסוג שרוצים לסרוק.
  • היברידי: אפשר להוסיף תוויות חובה, תוויות אופציונליות ואפשרויות לטיפול בנתונים בטבלה. מידע נוסף זמין במאמר סוגי המטא-נתונים שאפשר לספק.

דגימות

דגימה היא דרך אופציונלית לחסוך במשאבים אם יש לכם כמות גדולה מאוד של נתונים.

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

  • ב-BigQuery, אפשר לדגום קבוצת משנה של כל השורות שנבחרו, בהתאם לאחוז הקבצים שציינתם שייכללו בסריקה.
  • ב-Cloud Storage, אם קובץ כלשהו חורג מהגודל שצוין ב-Max byte size to scan per file, Sensitive Data Protection סורק אותו עד לגודל הקובץ המקסימלי הזה ואז עובר לקובץ הבא.

כדי להפעיל דגימה, בוחרים באחת מהאפשרויות הבאות בתפריט הראשון:

  • Start sampling from top: ‏Sensitive Data Protection מתחיל את הסריקה החלקית בתחילת הנתונים. ב-BigQuery, הסריקה מתחילה בשורה הראשונה. ב-Cloud Storage, הסריקה מתחילה בתחילת כל קובץ ומסתיימת אחרי ש-Sensitive Data Protection סורק עד לגודל הקובץ המקסימלי שצוין.
  • ‫Start sampling from random start: ‏Sensitive Data Protection מתחיל את הסריקה החלקית במיקום אקראי בתוך הנתונים. ב-BigQuery, הסריקה מתחילה בשורה אקראית. ב-Cloud Storage, ההגדרה הזו חלה רק על קבצים שחורגים מהגודל המקסימלי שצוין. ‫Sensitive Data Protection סורק קבצים שקטנים מהגודל המקסימלי במלואם, וקבצים שגדולים מהגודל המקסימלי עד לגודל המקסימלי.

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

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

הגדרה מתקדמת

כשיוצרים משימה לסריקה של קטגוריות של Cloud Storage או טבלאות ב-BigQuery, אפשר לצמצם את החיפוש באמצעות הגדרה מתקדמת. באופן ספציפי, אתם יכולים להגדיר:

  • קבצים (רק ב-Cloud Storage): סוגי הקבצים שרוצים לסרוק, כולל קובצי טקסט, קבצים בינאריים וקובצי תמונות.
  • שדות מזהים (BigQuery בלבד): מזהי שורות ייחודיים בטבלה.
  • ב-Cloud Storage, אם קובץ כלשהו חורג מהגודל שצוין ב-Max byte size to scan per file, Sensitive Data Protection סורק אותו עד לגודל הקובץ המקסימלי הזה ואז עובר לקובץ הבא.

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

  • Start sampling from top: ‏Sensitive Data Protection מתחיל את הסריקה החלקית בתחילת הנתונים. ב-BigQuery, הסריקה מתחילה בשורה הראשונה. ב-Cloud Storage, הסריקה מתחילה בתחילת כל קובץ, ומסתיימת אחרי ש-Sensitive Data Protection סרק עד לגודל הקובץ המקסימלי שצוין (ראו למעלה).
  • Start sampling from random start: הסריקה החלקית של Sensitive Data Protection מתחילה במיקום אקראי בנתונים. ב-BigQuery, הסריקה מתחילה בשורה אקראית. ב-Cloud Storage, ההגדרה הזו חלה רק על קבצים שחורגים מהגודל המקסימלי שצוין. ב-Sensitive Data Protection, קבצים שקטנים מהגודל המקסימלי נסרקים במלואם, וקבצים שגדולים מהגודל המקסימלי נסרקים עד לגודל המקסימלי.
קבצים

בקבצים שמאוחסנים ב-Cloud Storage, אפשר לציין את הסוגים שרוצים לכלול בסריקה בקטע Files.

אתם יכולים לבחור מבין קובצי בינארי, טקסט, תמונה, CSV,‏ TSV,‏ Microsoft Word,‏ Microsoft Excel,‏ Microsoft Powerpoint,‏ PDF ו-Apache Avro. רשימה מקיפה של סיומות הקבצים ש-Sensitive Data Protection יכול לסרוק בקטגוריות של Cloud Storage מופיעה במאמר FileType. אם בוחרים באפשרות Binary, המערכת של Sensitive Data Protection סורקת קבצים מסוגים לא מזוהים.

שדות מזהים

בטבלאות ב-BigQuery, בשדה Identifying fields אתם יכולים להורות ל-Sensitive Data Protection לכלול בתוצאות את הערכים של עמודות המפתח הראשי של הטבלה. כך תוכלו לקשר את הממצאים בחזרה לשורות בטבלה שמכילות אותם.

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

כדי לייצא את הממצאים ל-BigQuery, צריך גם להפעיל את הפעולה Save to BigQuery. כשמייצאים את הממצאים ל-BigQuery, כל ממצא מכיל את הערכים המתאימים של השדות המזהים. מידע נוסף זמין במאמר identifyingFields.

הגדרת הזיהוי

בקטע Configure detection מציינים את סוגי המידע הרגיש שרוצים לסרוק. השלמת הקטע הזה היא אופציונלית. אם תדלגו על החלק הזה, Sensitive Data Protection יסרוק את הנתונים שלכם לפי קבוצת ברירת מחדל של infoTypes.

תבנית

אתם יכולים להשתמש בתבנית של Sensitive Data Protection כדי לעשות שימוש חוזר בפרטי ההגדרות שציינתם בעבר.

אם כבר יצרתם תבנית שאתם רוצים להשתמש בה, לחצו על השדה Template name כדי לראות רשימה של תבניות בדיקה קיימות. בוחרים או מקלידים את שם התבנית שבה רוצים להשתמש.

מידע נוסף על יצירת תבניות זמין במאמר יצירת תבניות לבדיקה של Sensitive Data Protection.

InfoTypes

גלאי InfoType מוצאים מידע אישי רגיש מסוג מסוים. לדוגמה, גלאי ה-infoType המובנהUS_SOCIAL_SECURITY_NUMBER של Sensitive Data Protection מוצא מספרי ביטוח לאומי בארה"ב. בנוסף למזהי infoType המובנים, אתם יכולים ליצור מזהי infoType בהתאמה אישית.

בקטע InfoTypes, בוחרים את גלאי ה-infoType שתואם לסוג הנתונים שרוצים לסרוק. לא מומלץ להשאיר את הקטע הזה ריק. אם תעשו את זה, Sensitive Data Protection יסרוק את הנתונים שלכם באמצעות קבוצת ברירת מחדל של infoTypes, שעשויה לכלול infoTypes שאתם לא צריכים. מידע נוסף על כל גלאי זמין בחומר העזר בנושא גלאי InfoType.

למידע נוסף על ניהול של סוגי מידע מובנים ומותאמים אישית בקטע הזה, קראו את המאמר ניהול של סוגי מידע באמצעות מסוף Google Cloud .

קבוצות כללים לבדיקה

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

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

  1. לוחצים על הוספת קבוצת כללים.
  2. בשדה Choose target infoTypes, בוחרים את סוגי המידע שקבוצת הכללים משנה אם הכללים מתקיימים.
  3. לוחצים על Add a rule כדי לפתוח תפריט עם אפשרויות, כולל כלל הרחבה (Hotword),‏ כלל להחרגה ו-Adjustment rule.

כדי ליצור כלל הרחבה (Hotword), בוחרים באפשרות כלל הרחבה (Hotword). לאחר מכן, מבצעים את הפעולות הבאות:

  1. בשדה Hotword, מזינים ביטוי רגולרי ש-Sensitive Data Protection יחפש.
  2. בתפריט Hotword proximity, בוחרים אם מילת ההפעלה שהזנתם נמצאת לפני או אחרי ה-infoType שנבחר.
  3. בשדה Hotword distance from infoType, מזינים את מספר התווים המשוער בין מילת ההפעלה לבין ה-infoType שנבחר.
  4. בקטע Confidence level adjustment, בוחרים אם להקצות להתאמות רמת סבירות קבועה, או להגדיל או להקטין את רמת הסבירות שמוגדרת כברירת מחדל בסכום מסוים.

כדי ליצור כלל החרגה, בוחרים באפשרות Exclusion rule ובסוג כלל ההחרגה שרוצים ליצור, למשל ביטוי רגולרי. לאחר מכן, מבצעים את הפעולות הבאות:

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

כדי ליצור כלל התאמה, בוחרים באפשרות כלל התאמה ובסוג כלל ההתאמה, לדוגמה, התאמה לפי ממצאים בתמונות. לאחר מכן, מבצעים את הפעולות הבאות:

  1. בשדה Context infoTypes, בוחרים את הגלאים של סוגי המידע שמספקים הקשר לממצא היעד. ‫Sensitive Data Protection משתמש ב-infoTypes של הקשר כדי להעריך אם צריך לשנות את ה-infoType של היעד.
  2. בשדה Minimum likelihood, בוחרים את רמת הסבירות הנמוכה ביותר שיכולה להיות לסוגי המידע בהקשר, ועדיין להפעיל את כלל ההתאמה. אם ערך הסבירות של ממצא הקשר שזוהה נמוך מהערך הזה, Sensitive Data Protection לא משנה את הסבירות של ממצא היעד.
  3. בממצאים של תמונות, בשדה Image containment type בוחרים את הקשר המרחבי הנדרש בין סוגי המידע הרגיש של היעד וההקשר. לדוגמה, אם בוחרים באפשרות Encloses, הממצא של ההקשר חייב להכיל את ממצא היעד כדי שהכלל יחול.
  4. בשדה Likelihood, בוחרים את רמת הסבירות החדשה שרוצים להקצות לממצא היעד.

אתם יכולים להוסיף עוד קבוצות כללים כדי לשפר את תוצאות הסריקה.

סף ביטחון

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

ערך ברירת המחדל Possible מספיק לרוב המטרות. אם אתם מקבלים באופן קבוע התאמות רחבות מדי, הזיזו את פס ההזזה למעלה. אם אתם מקבלים מעט מדי התאמות, הזיזו את פס ההזזה למטה.

בסיום, לוחצים על המשך.

הוספת פעולות

בקטע Add actions, בוחרים פעולה אחת או יותר ש-Sensitive Data Protection יבצע אחרי שהמשימה תסתיים. מידע נוסף זמין במאמר הפעלת פעולות של בדיקה או ניתוח סיכונים.

אחרי שבוחרים פעולות, לוחצים על המשך.

בדיקה

בקטע Review מופיע סיכום בפורמט JSON של הגדרות המשימה שציינתם.

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

כדי לחזור לדף הראשי של Sensitive Data Protection, לוחצים על החץ Back במסוף Google Cloud .

C#

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


using System;
using System.Linq;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;
using static Google.Cloud.Dlp.V2.StorageConfig.Types;

public class JobsCreate
{
    public static DlpJob CreateJob(string projectId, string gcsPath)
    {
        var dlp = DlpServiceClient.Create();

        var storageConfig = new StorageConfig
        {
            CloudStorageOptions = new CloudStorageOptions
            {
                FileSet = new CloudStorageOptions.Types.FileSet()
                {
                    Url = gcsPath
                }
            },
            TimespanConfig = new TimespanConfig
            {
                EnableAutoPopulationOfTimespanConfig = true
            }
        };

        var inspectConfig = new InspectConfig
        {
            InfoTypes = { new[] { "EMAIL_ADDRESS", "CREDIT_CARD_NUMBER" }.Select(it => new InfoType() { Name = it }) },
            IncludeQuote = true,
            MinLikelihood = Likelihood.Unlikely,
            Limits = new InspectConfig.Types.FindingLimits() { MaxFindingsPerItem = 100 }
        };

        var response = dlp.CreateDlpJob(new CreateDlpJobRequest
        {
            Parent = new LocationName(projectId, "global").ToString(),
            InspectJob = new InspectJobConfig
            {
                InspectConfig = inspectConfig,
                StorageConfig = storageConfig,
            }
        });

        Console.WriteLine($"Job: {response.Name} status: {response.State}");

        return response;
    }
}

Go

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// createJob creates an inspection job
func createJob(w io.Writer, projectID, gcsPath string, infoTypeNames []string) error {
	// projectID := "my-project-id"
	// gcsPath := "gs://" + "your-bucket-name" + "path/to/file.txt";
	// infoTypeNames := []string{"EMAIL_ADDRESS", "PERSON_NAME", "LOCATION", "PHONE_NUMBER"}

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return err
	}

	// Closing the client safely cleans up background resources.
	defer client.Close()

	// Specify the GCS file to be inspected.
	storageConfig := &dlppb.StorageConfig{
		Type: &dlppb.StorageConfig_CloudStorageOptions{
			CloudStorageOptions: &dlppb.CloudStorageOptions{
				FileSet: &dlppb.CloudStorageOptions_FileSet{
					Url: gcsPath,
				},
			},
		},

		// Set autoPopulateTimespan to true to scan only new content.
		TimespanConfig: &dlppb.StorageConfig_TimespanConfig{
			EnableAutoPopulationOfTimespanConfig: true,
		},
	}

	// Specify the type of info the inspection will look for.
	// See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types.
	var infoTypes []*dlppb.InfoType
	for _, c := range infoTypeNames {
		infoTypes = append(infoTypes, &dlppb.InfoType{Name: c})
	}

	inspectConfig := &dlppb.InspectConfig{
		InfoTypes:    infoTypes,
		IncludeQuote: true,

		// The minimum likelihood required before returning a match:
		// See: https://cloud.google.com/dlp/docs/likelihood
		MinLikelihood: dlppb.Likelihood_UNLIKELY,

		// The maximum number of findings to report (0 = server maximum)
		Limits: &dlppb.InspectConfig_FindingLimits{
			MaxFindingsPerItem: 100,
		},
	}

	// Create and send the request.
	req := dlppb.CreateDlpJobRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
		Job: &dlppb.CreateDlpJobRequest_InspectJob{
			InspectJob: &dlppb.InspectJobConfig{
				InspectConfig: inspectConfig,
				StorageConfig: storageConfig,
			},
		},
	}

	// Send the request.
	response, err := client.CreateDlpJob(ctx, &req)
	if err != nil {
		return err
	}

	// Print the results.
	fmt.Fprintf(w, "Created a Dlp Job %v and Status is: %v", response.Name, response.State)
	return nil
}

Java

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.Action;
import com.google.privacy.dlp.v2.CloudStorageOptions;
import com.google.privacy.dlp.v2.CreateDlpJobRequest;
import com.google.privacy.dlp.v2.DlpJob;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectJobConfig;
import com.google.privacy.dlp.v2.Likelihood;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.StorageConfig;
import com.google.privacy.dlp.v2.StorageConfig.TimespanConfig;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class JobsCreate {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String gcsPath = "gs://" + "your-bucket-name" + "path/to/file.txt";
    createJobs(projectId, gcsPath);
  }

  // Creates a DLP Job
  public static void createJobs(String projectId, String gcsPath) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

      // Set autoPopulateTimespan to true to scan only new content
      boolean autoPopulateTimespan = true;
      TimespanConfig timespanConfig =
          TimespanConfig.newBuilder()
              .setEnableAutoPopulationOfTimespanConfig(autoPopulateTimespan)
              .build();

      // Specify the GCS file to be inspected.
      CloudStorageOptions cloudStorageOptions =
          CloudStorageOptions.newBuilder()
              .setFileSet(CloudStorageOptions.FileSet.newBuilder().setUrl(gcsPath))
              .build();
      StorageConfig storageConfig =
          StorageConfig.newBuilder()
              .setCloudStorageOptions(cloudStorageOptions)
              .setTimespanConfig(timespanConfig)
              .build();

      // Specify the type of info the inspection will look for.
      // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
      List<InfoType> infoTypes =
          Stream.of("EMAIL_ADDRESS", "PERSON_NAME", "LOCATION", "PHONE_NUMBER")
              .map(it -> InfoType.newBuilder().setName(it).build())
              .collect(Collectors.toList());
      // The minimum likelihood required before returning a match:
      // See: https://cloud.google.com/dlp/docs/likelihood
      Likelihood minLikelihood = Likelihood.UNLIKELY;

      // The maximum number of findings to report (0 = server maximum)
      InspectConfig.FindingLimits findingLimits =
          InspectConfig.FindingLimits.newBuilder().setMaxFindingsPerItem(100).build();

      InspectConfig inspectConfig =
          InspectConfig.newBuilder()
              .addAllInfoTypes(infoTypes)
              .setIncludeQuote(true)
              .setMinLikelihood(minLikelihood)
              .setLimits(findingLimits)
              .build();

      // Specify the action that is triggered when the job completes.
      Action.PublishSummaryToCscc publishSummaryToCscc =
          Action.PublishSummaryToCscc.getDefaultInstance();
      Action action = Action.newBuilder().setPublishSummaryToCscc(publishSummaryToCscc).build();

      // Configure the inspection job we want the service to perform.
      InspectJobConfig inspectJobConfig =
          InspectJobConfig.newBuilder()
              .setInspectConfig(inspectConfig)
              .setStorageConfig(storageConfig)
              .addActions(action)
              .build();

      // Construct the job creation request to be sent by the client.
      CreateDlpJobRequest createDlpJobRequest =
          CreateDlpJobRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setInspectJob(inspectJobConfig)
              .build();

      // Send the job creation request and process the response.
      DlpJob createdDlpJob = dlpServiceClient.createDlpJob(createDlpJobRequest);
      System.out.println("Job created successfully: " + createdDlpJob.getName());
    }
  }
}

Node.js

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Initialize google DLP Client
const dlp = new DLP.DlpServiceClient();

async function jobsCreate() {
  // Construct cloud storage configuration
  const cloudStorageConfig = {
    cloudStorageOptions: {
      fileSet: {
        url: cloudFileUrl,
      },
    },
    timespanConfig: {
      enableAutoPopulationOfTimespanConfig: true,
    },
  };

  // Construct inspect job configuration
  const inspectJob = {
    storageConfig: cloudStorageConfig,
  };

  // Construct inspect configuration
  const inspectConfig = {
    infoTypes: [
      {name: 'EMAIL_ADDRESS'},
      {name: 'PERSON_NAME'},
      {name: 'LOCATION'},
      {name: 'PHONE_NUMBER'},
    ],
    includeQuote: true,
    minLikelihood: DLP.protos.google.privacy.dlp.v2.Likelihood.LIKELY,
    excludeInfoTypes: false,
  };

  // Combine configurations into a request for the service.
  const request = {
    parent: `projects/${projectId}/locations/global`,
    inspectJob: inspectJob,
    inspectConfig: inspectConfig,
  };

  // Send the request and receive response from the service
  const [response] = await dlp.createDlpJob(request);
  // Print the results
  console.log(`Job created successfully: ${response.name}`);
}

jobsCreate();

PHP

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Dlp\V2\Action;
use Google\Cloud\Dlp\V2\Action\PublishSummaryToCscc;
use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\CloudStorageOptions;
use Google\Cloud\Dlp\V2\CloudStorageOptions\FileSet;
use Google\Cloud\Dlp\V2\CreateDlpJobRequest;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;
use Google\Cloud\Dlp\V2\InspectJobConfig;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\StorageConfig;
use Google\Cloud\Dlp\V2\StorageConfig\TimespanConfig;

/**
 * Creates an inspection job with the Cloud Data Loss Prevention API.
 *
 * @param string $callingProjectId  The project ID to run the API call under.
 * @param string $gcsPath           GCS file to be inspected. Example : gs://GOOGLE_STORAGE_BUCKET_NAME/dlp_sample.csv
 */
function create_job(
    string $callingProjectId,
    string $gcsPath
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Set autoPopulateTimespan to true to scan only new content.
    $timespanConfig = (new TimespanConfig())
        ->setEnableAutoPopulationOfTimespanConfig(true);

    // Specify the GCS file to be inspected.
    $cloudStorageOptions = (new CloudStorageOptions())
        ->setFileSet((new FileSet())
            ->setUrl($gcsPath));
    $storageConfig = (new StorageConfig())
        ->setCloudStorageOptions(($cloudStorageOptions))
        ->setTimespanConfig($timespanConfig);

    // ----- Construct inspection config -----
    $emailAddressInfoType = (new InfoType())
        ->setName('EMAIL_ADDRESS');
    $personNameInfoType = (new InfoType())
        ->setName('PERSON_NAME');
    $locationInfoType = (new InfoType())
        ->setName('LOCATION');
    $phoneNumberInfoType = (new InfoType())
        ->setName('PHONE_NUMBER');
    $infoTypes = [$emailAddressInfoType, $personNameInfoType, $locationInfoType, $phoneNumberInfoType];

    // Whether to include the matching string in the response.
    $includeQuote = true;
    // The minimum likelihood required before returning a match.
    $minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;

    // The maximum number of findings to report (0 = server maximum).
    $limits = (new FindingLimits())
        ->setMaxFindingsPerRequest(100);

    // Create the Inspect configuration object.
    $inspectConfig = (new InspectConfig())
        ->setMinLikelihood($minLikelihood)
        ->setLimits($limits)
        ->setInfoTypes($infoTypes)
        ->setIncludeQuote($includeQuote);

    // Specify the action that is triggered when the job completes.
    $action = (new Action())
        ->setPublishSummaryToCscc(new PublishSummaryToCscc());

    // Configure the inspection job we want the service to perform.
    $inspectJobConfig = (new InspectJobConfig())
        ->setInspectConfig($inspectConfig)
        ->setStorageConfig($storageConfig)
        ->setActions([$action]);

    // Send the job creation request and process the response.
    $parent = "projects/$callingProjectId/locations/global";
    $createDlpJobRequest = (new CreateDlpJobRequest())
        ->setParent($parent)
        ->setInspectJob($inspectJobConfig);
    $job = $dlp->createDlpJob($createDlpJobRequest);

    // Print results.
    printf($job->getName());
}

Python

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import google.cloud.dlp


def create_dlp_job(
    project: str,
    bucket: str,
    info_types: list[str],
    job_id: str = None,
    max_findings: int = 100,
    auto_populate_timespan: bool = True,
) -> None:
    """Uses the Data Loss Prevention API to create a DLP job.
    Args:
        project: The project id to use as a parent resource.
        bucket: The name of the GCS bucket to scan. This sample scans all
            files in the bucket.
        info_types: A list of strings representing info types to look for.
            A full list of info type categories can be fetched from the API.
        job_id: The id of the job. If omitted, an id will be randomly generated.
        max_findings: The maximum number of findings to report; 0 = no maximum.
        auto_populate_timespan: Automatically populates time span config start
            and end times in order to scan new content only.
    """

    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Convert the project id into a full resource id.
    parent = f"projects/{project}"

    # Prepare info_types by converting the list of strings into a list of
    # dictionaries (protos are also accepted).
    info_types = [{"name": info_type} for info_type in info_types]

    # Construct the configuration dictionary. Keys which are None may
    # optionally be omitted entirely.
    inspect_config = {
        "info_types": info_types,
        "min_likelihood": google.cloud.dlp_v2.Likelihood.UNLIKELY,
        "limits": {"max_findings_per_request": max_findings},
        "include_quote": True,
    }

    # Construct a cloud_storage_options dictionary with the bucket's URL.
    url = f"gs://{bucket}/*"
    storage_config = {
        "cloud_storage_options": {"file_set": {"url": url}},
        # Time-based configuration for each storage object.
        "timespan_config": {
            # Auto-populate start and end times in order to scan new objects
            # only.
            "enable_auto_population_of_timespan_config": auto_populate_timespan
        },
    }

    # Construct the job definition.
    job = {"inspect_config": inspect_config, "storage_config": storage_config}

    # Call the API.
    response = dlp.create_dlp_job(
        request={"parent": parent, "inspect_job": job, "job_id": job_id}
    )

    # Print out the result.
    print(f"Job : {response.name} status: {response.state}")

REST

משימה מיוצגת ב-DLP API באמצעות המשאב DlpJobs. כדי ליצור משימה חדשה, משתמשים ב-method ‏projects.dlpJobs.create של המשאב DlpJob.

אפשר לשלוח את ה-JSON לדוגמה בבקשת POST לנקודת הקצה (endpoint) שצוינה ב-REST של Sensitive Data Protection. דוגמת ה-JSON הבאה ממחישה איך ליצור משימה ב-Sensitive Data Protection. המשימה היא סריקת בדיקה של Datastore.

כדי לנסות את זה במהירות, אתם יכולים להשתמש ב-API Explorer שמוטמע בהמשך. חשוב לזכור שבקשה שהושלמה בהצלחה, גם כזו שנוצרה ב-API Explorer, תיצור משימה. למידע כללי על השימוש ב-JSON כדי לשלוח בקשות ל-DLP API, עיינו במדריך למתחילים בנושא JSON.

קלט JSON:

{
  "inspectJob": {
    "storageConfig": {
      "bigQueryOptions": {
        "tableReference": {
          "projectId": "bigquery-public-data",
          "datasetId": "san_francisco_sfpd_incidents",
          "tableId": "sfpd_incidents"
        }
      },
      "timespanConfig": {
        "startTime": "2020-01-01T00:00:01Z",
        "endTime": "2020-01-31T23:59:59Z",
        "timestampField": {
          "name": "timestamp"
        }
      }
    },
    "inspectConfig": {
      "infoTypes": [
        {
          "name": "PERSON_NAME"
        },
        {
          "name": "STREET_ADDRESS"
        }
      ],
      "excludeInfoTypes": false,
      "includeQuote": true,
      "minLikelihood": "LIKELY"
    },
    "actions": [
      {
        "saveFindings": {
          "outputConfig": {
            "table": {
              "projectId": "[PROJECT-ID]",
              "datasetId": "[DATASET-ID]"
            }
          }
        }
      }
    ]
  }
}

פלט מסוג JSON:

הפלט הבא מציין שהמשימה נוצרה בהצלחה.

{
  "name": "projects/[PROJECT-ID]/dlpJobs/[JOB-ID]",
  "type": "INSPECT_JOB",
  "state": "PENDING",
  "inspectDetails": {
    "requestedOptions": {
      "snapshotInspectTemplate": {},
      "jobConfig": {
        "storageConfig": {
          "bigQueryOptions": {
            "tableReference": {
              "projectId": "bigquery-public-data",
              "datasetId": "san_francisco_sfpd_incidents",
              "tableId": "sfpd_incidents"
            }
          },
          "timespanConfig": {
            "startTime": "2020-01-01T00:00:01Z",
            "endTime": "2020-01-31T23:59:59Z",
            "timestampField": {
              "name": "timestamp"
            }
          }
        },
        "inspectConfig": {
          "infoTypes": [
            {
              "name": "PERSON_NAME"
            },
            {
              "name": "STREET_ADDRESS"
            }
          ],
          "minLikelihood": "LIKELY",
          "limits": {},
          "includeQuote": true
        },
        "actions": [
          {
            "saveFindings": {
              "outputConfig": {
                "table": {
                  "projectId": "[PROJECT-ID]",
                  "datasetId": "[DATASET-ID]",
                  "tableId": "[TABLE-ID]"
                }
              }
            }
          }
        ]
      }
    },
    "result": {}
  },
  "createTime": "2020-07-10T07:26:33.643Z"
}

יצירת טריגר חדש למשימה

כדי ליצור טריגר חדש למשימה ב-Sensitive Data Protection:

המסוף

בקטע Sensitive Data Protection במסוף Google Cloud , נכנסים לדף Create job or job trigger.

כניסה לדף Create job or job trigger

הדף Create job or job trigger כולל את הקטעים הבאים:

בחירת נתוני קלט

שם

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

מיקום

בתפריט Storage type, בוחרים את סוג המאגר שבו מאוחסנים הנתונים שרוצים לסרוק:

  • ‫Cloud Storage: מזינים את כתובת ה-URL של הקטגוריה שרוצים לסרוק, או בוחרים באפשרות Include/exclude בתפריט Location type ולוחצים על Browse כדי לעבור לקטגוריה או לתיקיית המשנה שרוצים לסרוק. מסמנים את התיבה Scan folder recursively כדי לסרוק את הספרייה שצוינה ואת כל הספריות שהיא מכילה. אם לא מסמנים את האפשרות הזו, המערכת סורקת רק את הספרייה שצוינה ולא ספריות משנה.
  • ‫BigQuery: מזינים את המזהים של הפרויקט, מערך הנתונים והטבלה שרוצים לסרוק.
  • Datastore: מזינים את המזהים של הפרויקט, מרחב השמות (אופציונלי) והסוג שרוצים לסרוק.

דגימות

דגימה היא דרך אופציונלית לחסוך במשאבים אם יש לכם כמות גדולה מאוד של נתונים.

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

  • ב-BigQuery, אפשר לדגום קבוצת משנה של כל השורות שנבחרו, בהתאם לאחוז הקבצים שציינתם שייכללו בסריקה.
  • ב-Cloud Storage, אם קובץ כלשהו חורג מהגודל שצוין ב-Max byte size to scan per file, Sensitive Data Protection סורק אותו עד לגודל הקובץ המקסימלי הזה ואז עובר לקובץ הבא.

כדי להפעיל דגימה, בוחרים באחת מהאפשרויות הבאות בתפריט הראשון:

  • Start sampling from top: ‏Sensitive Data Protection מתחיל את הסריקה החלקית בתחילת הנתונים. ב-BigQuery, הסריקה מתחילה בשורה הראשונה. ב-Cloud Storage, הסריקה מתחילה בתחילת כל קובץ, ומסתיימת אחרי ש-Sensitive Data Protection סרק עד לגודל הקובץ המקסימלי שצוין (ראו למעלה).
  • ‫Start sampling from random start: ‏Sensitive Data Protection מתחיל את הסריקה החלקית במיקום אקראי בתוך הנתונים. ב-BigQuery, הסריקה מתחילה בשורה אקראית. ב-Cloud Storage, ההגדרה הזו חלה רק על קבצים שחורגים מהגודל המקסימלי שצוין. ‫Sensitive Data Protection סורק קבצים שקטנים מהגודל המקסימלי במלואם, וקבצים שגדולים מהגודל המקסימלי עד לגודל המקסימלי.

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

הגדרה מתקדמת

כשיוצרים טריגר של משימה לסריקה של קטגוריות של Cloud Storage או טבלאות ב-BigQuery, אפשר לצמצם את החיפוש על ידי הגדרת תצורה מתקדמת. באופן ספציפי, אתם יכולים להגדיר:

  • ‫Files (רק ב-Cloud Storage): סוגי הקבצים שרוצים לסרוק, כולל קובצי טקסט, קבצים בינאריים וקובצי תמונות.
  • שדות מזהים (BigQuery בלבד): מזהי שורות ייחודיים בטבלה.
  • ב-Cloud Storage, אם קובץ כלשהו חורג מהגודל שצוין ב-Max byte size to scan per file, Sensitive Data Protection סורק אותו עד לגודל הקובץ המקסימלי הזה ואז עובר לקובץ הבא.

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

  • Start sampling from top: ‏Sensitive Data Protection מתחיל את הסריקה החלקית בתחילת הנתונים. ב-BigQuery, הסריקה מתחילה בשורה הראשונה. ב-Cloud Storage, הסריקה מתחילה בתחילת כל קובץ, ומסתיימת אחרי ש-Sensitive Data Protection סרק עד לגודל הקובץ המקסימלי שצוין (ראו למעלה).
  • Start sampling from random start: הסריקה החלקית של Sensitive Data Protection מתחילה במיקום אקראי בנתונים. ב-BigQuery, הסריקה מתחילה בשורה אקראית. ב-Cloud Storage, ההגדרה הזו חלה רק על קבצים שחורגים מהגודל המקסימלי שצוין. ב-Sensitive Data Protection, קבצים שקטנים מהגודל המקסימלי נסרקים במלואם, וקבצים שגדולים מהגודל המקסימלי נסרקים עד לגודל המקסימלי.

קבצים

בקטע Files, אתם יכולים לציין את סוגי הקבצים שמאוחסנים ב-Cloud Storage שאתם רוצים לכלול בסריקה.

אתם יכולים לבחור מבין קובצי Apache Avro,‏ PDF,‏ Microsoft Powerpoint,‏ Microsoft Excel,‏ Microsoft Word,‏ תמונה, טקסט ובינארי. FileType היא רשימה מקיפה של סיומות קבצים ש-Sensitive Data Protection יכול לסרוק בקטגוריות של Cloud Storage. אם בוחרים באפשרות Binary, המערכת של Sensitive Data Protection סורקת קבצים מסוגים לא מזוהים.

שדות מזהים

בטבלאות ב-BigQuery, בשדה Identifying fields אתם יכולים להורות ל-Sensitive Data Protection לכלול בתוצאות את הערכים של עמודות המפתח הראשי של הטבלה. כך תוכלו לקשר את הממצאים בחזרה לשורות בטבלה שמכילות אותם.

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

כדי לייצא את הממצאים ל-BigQuery, צריך גם להפעיל את הפעולה Save to BigQuery. כשמייצאים את הממצאים ל-BigQuery, כל ממצא מכיל את הערכים המתאימים של השדות המזהים. מידע נוסף זמין במאמר identifyingFields.

הגדרת הזיהוי

בקטע Configure detection מציינים את סוגי המידע הרגיש שרוצים לסרוק. לא חובה למלא את הקטע הזה. אם תדלגו על החלק הזה, Sensitive Data Protection יסרוק את הנתונים שלכם לפי קבוצת ברירת מחדל של infoTypes.

תבנית

אתם יכולים להשתמש בתבנית של Sensitive Data Protection כדי לעשות שימוש חוזר בפרטי ההגדרות שציינתם בעבר.

אם כבר יצרתם תבנית שאתם רוצים להשתמש בה, לחצו על השדה Template name כדי לראות רשימה של תבניות בדיקה קיימות. בוחרים או מקלידים את שם התבנית שבה רוצים להשתמש.

מידע נוסף על יצירת תבניות זמין במאמר יצירת תבניות לבדיקה של Sensitive Data Protection.

InfoTypes

גלאי InfoType מוצאים מידע אישי רגיש מסוג מסוים. לדוגמה, גלאי ה-infoType המובנהUS_SOCIAL_SECURITY_NUMBER של Sensitive Data Protection מוצא מספרי ביטוח לאומי בארה"ב. בנוסף למזהי ה-infoType המובנים, אתם יכולים ליצור מזהי infoType בהתאמה אישית.

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

אפשר גם להוסיף כללים מותאמים אישית לבדיקת נתוני infoType בקטע Custom infoTypes, ולהתאים אישית את הכללים המובנים והמותאמים אישית לבדיקת נתוני infoType בקטע Inspection rulesets.

סוגי מידע מותאמים אישית

כדי להוסיף טיפוסי מידע בהתאמה אישית, ראו הוספת טיפוסי מידע בהתאמה אישית.

קבוצות כללים לבדיקה

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

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

  1. לוחצים על הוספת קבוצת כללים.
  2. בשדה Choose target infoTypes, בוחרים את סוגי המידע שקבוצת הכללים משנה אם הכללים מתקיימים.
  3. לוחצים על Add a rule כדי לפתוח תפריט עם אפשרויות, כולל כלל הרחבה (Hotword),‏ כלל להחרגה ו-Adjustment rule.

כדי ליצור כלל הרחבה (Hotword), בוחרים באפשרות כלל הרחבה (Hotword). לאחר מכן, מבצעים את הפעולות הבאות:

  1. בשדה Hotword, מזינים ביטוי רגולרי ש-Sensitive Data Protection יחפש.
  2. בתפריט Hotword proximity, בוחרים אם מילת ההפעלה שהזנתם נמצאת לפני או אחרי ה-infoType שנבחר.
  3. בשדה Hotword distance from infoType, מזינים את מספר התווים המשוער בין מילת ההפעלה לבין ה-infoType שנבחר.
  4. בקטע Confidence level adjustment, בוחרים אם להקצות להתאמות רמת סבירות קבועה, או להגדיל או להקטין את רמת הסבירות שמוגדרת כברירת מחדל בסכום מסוים.

כדי ליצור כלל החרגה, בוחרים באפשרות Exclusion rule ובסוג כלל ההחרגה שרוצים ליצור, למשל ביטוי רגולרי. לאחר מכן, מבצעים את הפעולות הבאות:

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

כדי ליצור כלל התאמה, בוחרים באפשרות כלל התאמה ובסוג כלל ההתאמה, לדוגמה, התאמה לפי ממצאים בתמונות. לאחר מכן, מבצעים את הפעולות הבאות:

  1. בשדה Context infoTypes, בוחרים את הגלאים של סוגי המידע שמספקים הקשר לממצא היעד. ‫Sensitive Data Protection משתמש ב-infoTypes של הקשר כדי להעריך אם צריך לשנות את ה-infoType של היעד.
  2. בשדה Minimum likelihood, בוחרים את רמת הסבירות הנמוכה ביותר שיכולה להיות לסוגי המידע בהקשר, ועדיין להפעיל את כלל ההתאמה. אם ערך הסבירות של ממצא הקשר שזוהה נמוך מהערך הזה, Sensitive Data Protection לא משנה את הסבירות של ממצא היעד.
  3. בממצאים של תמונות, בשדה Image containment type בוחרים את הקשר המרחבי הנדרש בין סוגי המידע הרגיש של היעד וההקשר. לדוגמה, אם בוחרים באפשרות Encloses, הממצא של ההקשר חייב להכיל את ממצא היעד כדי שהכלל יחול.
  4. בשדה Likelihood, בוחרים את רמת הסבירות החדשה שרוצים להקצות לממצא היעד.

אתם יכולים להוסיף עוד קבוצות כללים כדי לשפר את תוצאות הסריקה.

סף ביטחון

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

ערך ברירת המחדל Possible מספיק לרוב המטרות. אם אתם מקבלים באופן קבוע התאמות רחבות מדי, הזיזו את פס ההזזה למעלה. אם אתם מקבלים מעט מדי התאמות, הזיזו את פס ההזזה למטה.

בסיום, לוחצים על המשך.

הוספת פעולות

בקטע Add actions, בוחרים פעולה אחת או יותר ש-Sensitive Data Protection יבצע אחרי שהמשימה תסתיים. מידע נוסף זמין במאמר הפעלת פעולות של בדיקה או ניתוח סיכונים.

אחרי שבוחרים פעולות, לוחצים על המשך.

תזמון

בקטע לוח זמנים, אתם יכולים לבצע שתי פעולות:

  • ציון טווח זמן: האפשרות הזו מגבילה את הקבצים או השורות לסריקה לפי תאריך. לוחצים על Start time כדי לציין את חותמת הזמן המוקדמת ביותר של הקובץ שרוצים לכלול. כדי לציין את כל הקבצים, משאירים את הערך הזה ריק. לוחצים על End time כדי לציין את חותמת הזמן האחרונה של הקובץ שרוצים לכלול. אם לא רוצים להגדיר גבול עליון לחותמת הזמן, משאירים את הערך הזה ריק.
  • ‫Create a trigger to run the job on a periodic schedule: האפשרות הזו הופכת את המשימה לטריגר של משימה שפועל לפי לוח זמנים קבוע. אם לא תציינו לוח זמנים, תיצרו משימה אחת שתתחיל מיד ותפעל פעם אחת. כדי ליצור טריגר של משימה שפועל באופן קבוע, צריך להגדיר את האפשרות הזו.

    ערך ברירת המחדל הוא גם הערך המינימלי: 24 שעות. הערך המקסימלי הוא 60 ימים.

    אם רוצים ש-Sensitive Data Protection יסרוק רק קבצים או שורות חדשים, בוחרים באפשרות Limit scans only to new content. בבדיקה של BigQuery, רק שורות שנוצרו לפני שלוש שעות לפחות נכללות בסריקה. הבעיה המוכרת שקשורה לפעולה הזו.

בדיקה

בקטע Review מופיע סיכום בפורמט JSON של הגדרות המשימה שציינתם.

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

כדי לחזור לדף הראשי של Sensitive Data Protection, לוחצים על החץ Back במסוף Google Cloud .

C#

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;
using System;
using System.Collections.Generic;
using static Google.Cloud.Dlp.V2.CloudStorageOptions.Types;
using static Google.Cloud.Dlp.V2.InspectConfig.Types;
using static Google.Cloud.Dlp.V2.JobTrigger.Types;
using static Google.Cloud.Dlp.V2.StorageConfig.Types;

public class TriggersCreate
{
    public static JobTrigger Create(
        string projectId,
        string bucketName,
        Likelihood minLikelihood,
        int maxFindings,
        bool autoPopulateTimespan,
        int scanPeriod,
        IEnumerable<InfoType> infoTypes,
        string triggerId,
        string displayName,
        string description)
    {
        var dlp = DlpServiceClient.Create();

        var jobConfig = new InspectJobConfig
        {
            InspectConfig = new InspectConfig
            {
                MinLikelihood = minLikelihood,
                Limits = new FindingLimits
                {
                    MaxFindingsPerRequest = maxFindings
                },
                InfoTypes = { infoTypes }
            },
            StorageConfig = new StorageConfig
            {
                CloudStorageOptions = new CloudStorageOptions
                {
                    FileSet = new FileSet
                    {
                        Url = $"gs://{bucketName}/*"
                    }
                },
                TimespanConfig = new TimespanConfig
                {
                    EnableAutoPopulationOfTimespanConfig = autoPopulateTimespan
                }
            }
        };

        var jobTrigger = new JobTrigger
        {
            Triggers =
            {
                new Trigger
                {
                    Schedule = new Schedule
                    {
                        RecurrencePeriodDuration = new Google.Protobuf.WellKnownTypes.Duration
                        {
                            Seconds = scanPeriod * 60 * 60 * 24
                        }
                    }
                }
            },
            InspectJob = jobConfig,
            Status = Status.Healthy,
            DisplayName = displayName,
            Description = description
        };

        var response = dlp.CreateJobTrigger(
            new CreateJobTriggerRequest
            {
                Parent = new LocationName(projectId, "global").ToString(),
                JobTrigger = jobTrigger,
                TriggerId = triggerId
            });

        Console.WriteLine($"Successfully created trigger {response.Name}");
        return response;
    }
}

Go

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
	"github.com/golang/protobuf/ptypes/duration"
)

// createTrigger creates a trigger with the given configuration.
func createTrigger(w io.Writer, projectID string, triggerID, displayName, description, bucketName string, infoTypeNames []string) error {
	// projectID := "my-project-id"
	// triggerID := "my-trigger"
	// displayName := "My Trigger"
	// description := "My trigger description"
	// bucketName := "my-bucket"
	// infoTypeNames := []string{"US_SOCIAL_SECURITY_NUMBER"}

	ctx := context.Background()

	client, err := dlp.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("dlp.NewClient: %w", err)
	}
	defer client.Close()

	// Convert the info type strings to a list of InfoTypes.
	var infoTypes []*dlppb.InfoType
	for _, it := range infoTypeNames {
		infoTypes = append(infoTypes, &dlppb.InfoType{Name: it})
	}

	// Create a configured request.
	req := &dlppb.CreateJobTriggerRequest{
		Parent:    fmt.Sprintf("projects/%s/locations/global", projectID),
		TriggerId: triggerID,
		JobTrigger: &dlppb.JobTrigger{
			DisplayName: displayName,
			Description: description,
			Status:      dlppb.JobTrigger_HEALTHY,
			// Triggers control when the job will start.
			Triggers: []*dlppb.JobTrigger_Trigger{
				{
					Trigger: &dlppb.JobTrigger_Trigger_Schedule{
						Schedule: &dlppb.Schedule{
							Option: &dlppb.Schedule_RecurrencePeriodDuration{
								RecurrencePeriodDuration: &duration.Duration{
									Seconds: 10 * 60 * 60 * 24, // 10 days in seconds.
								},
							},
						},
					},
				},
			},
			// Job configures the job to run when the trigger runs.
			Job: &dlppb.JobTrigger_InspectJob{
				InspectJob: &dlppb.InspectJobConfig{
					InspectConfig: &dlppb.InspectConfig{
						InfoTypes:     infoTypes,
						MinLikelihood: dlppb.Likelihood_POSSIBLE,
						Limits: &dlppb.InspectConfig_FindingLimits{
							MaxFindingsPerRequest: 10,
						},
					},
					StorageConfig: &dlppb.StorageConfig{
						Type: &dlppb.StorageConfig_CloudStorageOptions{
							CloudStorageOptions: &dlppb.CloudStorageOptions{
								FileSet: &dlppb.CloudStorageOptions_FileSet{
									Url: "gs://" + bucketName + "/*",
								},
							},
						},
						// Time-based configuration for each storage object. See more at
						// https://cloud.google.com/dlp/docs/reference/rest/v2/InspectJobConfig#TimespanConfig
						TimespanConfig: &dlppb.StorageConfig_TimespanConfig{
							// Auto-populate start and end times in order to scan new objects only.
							EnableAutoPopulationOfTimespanConfig: true,
						},
					},
				},
			},
		},
	}

	// Send the request.
	resp, err := client.CreateJobTrigger(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateJobTrigger: %w", err)
	}
	fmt.Fprintf(w, "Successfully created trigger: %v", resp.GetName())
	return nil
}

Java

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.CloudStorageOptions;
import com.google.privacy.dlp.v2.CreateJobTriggerRequest;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectJobConfig;
import com.google.privacy.dlp.v2.JobTrigger;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.Schedule;
import com.google.privacy.dlp.v2.StorageConfig;
import com.google.privacy.dlp.v2.StorageConfig.TimespanConfig;
import com.google.protobuf.Duration;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TriggersCreate {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String gcsPath = "gs://" + "your-bucket-name" + "path/to/file.txt";
    createTrigger(projectId, gcsPath);
  }

  public static void createTrigger(String projectId, String gcsPath) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

      // Set autoPopulateTimespan to true to scan only new content
      boolean autoPopulateTimespan = true;
      TimespanConfig timespanConfig =
          TimespanConfig.newBuilder()
              .setEnableAutoPopulationOfTimespanConfig(autoPopulateTimespan)
              .build();

      // Specify the GCS file to be inspected.
      CloudStorageOptions cloudStorageOptions =
          CloudStorageOptions.newBuilder()
              .setFileSet(CloudStorageOptions.FileSet.newBuilder().setUrl(gcsPath))
              .build();
      StorageConfig storageConfig =
          StorageConfig.newBuilder()
              .setCloudStorageOptions(cloudStorageOptions)
              .setTimespanConfig(timespanConfig)
              .build();

      // Specify the type of info the inspection will look for.
      // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
      List<InfoType> infoTypes =
          Stream.of("PHONE_NUMBER", "EMAIL_ADDRESS", "CREDIT_CARD_NUMBER")
              .map(it -> InfoType.newBuilder().setName(it).build())
              .collect(Collectors.toList());

      InspectConfig inspectConfig = InspectConfig.newBuilder().addAllInfoTypes(infoTypes).build();

      // Configure the inspection job we want the service to perform.
      InspectJobConfig inspectJobConfig =
          InspectJobConfig.newBuilder()
              .setInspectConfig(inspectConfig)
              .setStorageConfig(storageConfig)
              .build();

      // Set scanPeriod to the number of days between scans (minimum: 1 day)
      int scanPeriod = 1;

      // Optionally set a display name of max 100 chars and a description of max 250 chars
      String displayName = "Daily Scan";
      String description = "A daily inspection for personally identifiable information.";

      // Schedule scan of GCS bucket every scanPeriod number of days (minimum = 1 day)
      Duration duration = Duration.newBuilder().setSeconds(scanPeriod * 24 * 3600).build();
      Schedule schedule = Schedule.newBuilder().setRecurrencePeriodDuration(duration).build();
      JobTrigger.Trigger trigger = JobTrigger.Trigger.newBuilder().setSchedule(schedule).build();
      JobTrigger jobTrigger =
          JobTrigger.newBuilder()
              .setInspectJob(inspectJobConfig)
              .setDisplayName(displayName)
              .setDescription(description)
              .setStatus(JobTrigger.Status.HEALTHY)
              .addTriggers(trigger)
              .build();

      // Create scan request to be sent by client
      CreateJobTriggerRequest createJobTriggerRequest =
          CreateJobTriggerRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setJobTrigger(jobTrigger)
              .build();

      // Send the scan request and process the response
      JobTrigger createdJobTrigger = dlpServiceClient.createJobTrigger(createJobTriggerRequest);

      System.out.println("Created Trigger: " + createdJobTrigger.getName());
      System.out.println("Display Name: " + createdJobTrigger.getDisplayName());
      System.out.println("Description: " + createdJobTrigger.getDescription());
    }
  }
}

Node.js

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'my-project';

// (Optional) The name of the trigger to be created.
// const triggerId = 'my-trigger';

// (Optional) A display name for the trigger to be created
// const displayName = 'My Trigger';

// (Optional) A description for the trigger to be created
// const description = "This is a sample trigger.";

// The name of the bucket to scan.
// const bucketName = 'YOUR-BUCKET';

// Limit scan to new content only.
// const autoPopulateTimespan = true;

// How often to wait between scans, in days (minimum = 1 day)
// const scanPeriod = 1;

// The infoTypes of information to match
// const infoTypes = [{ name: 'PHONE_NUMBER' }, { name: 'EMAIL_ADDRESS' }, { name: 'CREDIT_CARD_NUMBER' }];

// The minimum likelihood required before returning a match
// const minLikelihood = 'LIKELIHOOD_UNSPECIFIED';

// The maximum number of findings to report per request (0 = server maximum)
// const maxFindings = 0;

async function createTrigger() {
  // Get reference to the bucket to be inspected
  const storageItem = {
    cloudStorageOptions: {
      fileSet: {url: `gs://${bucketName}/*`},
    },
    timeSpanConfig: {
      enableAutoPopulationOfTimespanConfig: autoPopulateTimespan,
    },
  };

  // Construct job to be triggered
  const job = {
    inspectConfig: {
      infoTypes: infoTypes,
      minLikelihood: minLikelihood,
      limits: {
        maxFindingsPerRequest: maxFindings,
      },
    },
    storageConfig: storageItem,
  };

  // Construct trigger creation request
  const request = {
    parent: `projects/${projectId}/locations/global`,
    jobTrigger: {
      inspectJob: job,
      displayName: displayName,
      description: description,
      triggers: [
        {
          schedule: {
            recurrencePeriodDuration: {
              seconds: scanPeriod * 60 * 60 * 24, // Trigger the scan daily
            },
          },
        },
      ],
      status: 'HEALTHY',
    },
    triggerId: triggerId,
  };

  // Run trigger creation request
  const [trigger] = await dlp.createJobTrigger(request);
  console.log(`Successfully created trigger ${trigger.name}.`);
}

createTrigger();

PHP

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\CloudStorageOptions;
use Google\Cloud\Dlp\V2\CloudStorageOptions\FileSet;
use Google\Cloud\Dlp\V2\CreateJobTriggerRequest;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;
use Google\Cloud\Dlp\V2\InspectJobConfig;
use Google\Cloud\Dlp\V2\JobTrigger;
use Google\Cloud\Dlp\V2\JobTrigger\Status;
use Google\Cloud\Dlp\V2\JobTrigger\Trigger;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\Schedule;
use Google\Cloud\Dlp\V2\StorageConfig;
use Google\Cloud\Dlp\V2\StorageConfig\TimespanConfig;
use Google\Protobuf\Duration;

/**
 * Create a Data Loss Prevention API job trigger.
 *
 * @param string $callingProjectId     The project ID to run the API call under
 * @param string $bucketName           The name of the bucket to scan
 * @param string $triggerId            (Optional) The name of the trigger to be created
 * @param string $displayName          (Optional) The human-readable name to give the trigger
 * @param string $description          (Optional) A description for the trigger to be created
 * @param int    $scanPeriod           (Optional) How often to wait between scans, in days (minimum = 1 day)
 * @param bool   $autoPopulateTimespan (Optional) Automatically limit scan to new content only
 * @param int    $maxFindings          (Optional) The maximum number of findings to report per request (0 = server maximum)
 */
function create_trigger(
    string $callingProjectId,
    string $bucketName,
    string $triggerId,
    string $displayName,
    string $description,
    int $scanPeriod,
    bool $autoPopulateTimespan,
    int $maxFindings
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // ----- Construct job config -----
    // The infoTypes of information to match
    $personNameInfoType = (new InfoType())
        ->setName('PERSON_NAME');
    $phoneNumberInfoType = (new InfoType())
        ->setName('PHONE_NUMBER');
    $infoTypes = [$personNameInfoType, $phoneNumberInfoType];

    // The minimum likelihood required before returning a match
    $minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;

    // Specify finding limits
    $limits = (new FindingLimits())
        ->setMaxFindingsPerRequest($maxFindings);

    // Create the inspectConfig object
    $inspectConfig = (new InspectConfig())
        ->setMinLikelihood($minLikelihood)
        ->setLimits($limits)
        ->setInfoTypes($infoTypes);

    // Create triggers
    $duration = (new Duration())
        ->setSeconds($scanPeriod * 60 * 60 * 24);

    $schedule = (new Schedule())
        ->setRecurrencePeriodDuration($duration);

    $triggerObject = (new Trigger())
        ->setSchedule($schedule);

    // Create the storageConfig object
    $fileSet = (new FileSet())
        ->setUrl('gs://' . $bucketName . '/*');

    $storageOptions = (new CloudStorageOptions())
        ->setFileSet($fileSet);

    // Auto-populate start and end times in order to scan new objects only.
    $timespanConfig = (new TimespanConfig())
        ->setEnableAutoPopulationOfTimespanConfig($autoPopulateTimespan);

    $storageConfig = (new StorageConfig())
        ->setCloudStorageOptions($storageOptions)
        ->setTimespanConfig($timespanConfig);

    // Construct the jobConfig object
    $jobConfig = (new InspectJobConfig())
        ->setInspectConfig($inspectConfig)
        ->setStorageConfig($storageConfig);

    // ----- Construct trigger object -----
    $jobTriggerObject = (new JobTrigger())
        ->setTriggers([$triggerObject])
        ->setInspectJob($jobConfig)
        ->setStatus(Status::HEALTHY)
        ->setDisplayName($displayName)
        ->setDescription($description);

    // Run trigger creation request
    $parent = $dlp->locationName($callingProjectId, 'global');
    $createJobTriggerRequest = (new CreateJobTriggerRequest())
        ->setParent($parent)
        ->setJobTrigger($jobTriggerObject)
        ->setTriggerId($triggerId);
    $trigger = $dlp->createJobTrigger($createJobTriggerRequest);

    // Print results
    printf('Successfully created trigger %s' . PHP_EOL, $trigger->getName());
}

Python

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

from typing import Optional

import google.cloud.dlp


def create_trigger(
    project: str,
    bucket: str,
    scan_period_days: int,
    info_types: List[str],
    trigger_id: Optional[str] = None,
    display_name: Optional[str] = None,
    description: Optional[str] = None,
    min_likelihood: Optional[int] = None,
    max_findings: Optional[int] = None,
    auto_populate_timespan: Optional[bool] = False,
) -> None:
    """Creates a scheduled Data Loss Prevention API inspect_content trigger.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        bucket: The name of the GCS bucket to scan. This sample scans all
            files in the bucket using a wildcard.
        scan_period_days: How often to repeat the scan, in days.
            The minimum is 1 day.
        info_types: A list of strings representing info types to look for.
            A full list of info type categories can be fetched from the API.
        trigger_id: The id of the trigger. If omitted, an id will be randomly
            generated.
        display_name: The optional display name of the trigger.
        description: The optional description of the trigger.
        min_likelihood: A string representing the minimum likelihood threshold
            that constitutes a match. One of: 'LIKELIHOOD_UNSPECIFIED',
            'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE', 'LIKELY', 'VERY_LIKELY'.
        max_findings: The maximum number of findings to report; 0 = no maximum.
        auto_populate_timespan: Automatically populates time span config start
            and end times in order to scan new content only.
    Returns:
        None; the response from the API is printed to the terminal.
    """

    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Prepare info_types by converting the list of strings into a list of
    # dictionaries (protos are also accepted).
    info_types = [{"name": info_type} for info_type in info_types]

    # Construct the configuration dictionary. Keys which are None may
    # optionally be omitted entirely.
    inspect_config = {
        "info_types": info_types,
        "min_likelihood": min_likelihood,
        "limits": {"max_findings_per_request": max_findings},
    }

    # Construct a cloud_storage_options dictionary with the bucket's URL.
    url = f"gs://{bucket}/*"
    storage_config = {
        "cloud_storage_options": {"file_set": {"url": url}},
        # Time-based configuration for each storage object.
        "timespan_config": {
            # Auto-populate start and end times in order to scan new objects
            # only.
            "enable_auto_population_of_timespan_config": auto_populate_timespan
        },
    }

    # Construct the job definition.
    job = {"inspect_config": inspect_config, "storage_config": storage_config}

    # Construct the schedule definition:
    schedule = {
        "recurrence_period_duration": {"seconds": scan_period_days * 60 * 60 * 24}
    }

    # Construct the trigger definition.
    job_trigger = {
        "inspect_job": job,
        "display_name": display_name,
        "description": description,
        "triggers": [{"schedule": schedule}],
        "status": google.cloud.dlp_v2.JobTrigger.Status.HEALTHY,
    }

    # Convert the project id into a full resource id.
    parent = f"projects/{project}"

    # Call the API.
    response = dlp.create_job_trigger(
        request={"parent": parent, "job_trigger": job_trigger, "trigger_id": trigger_id}
    )

    print(f"Successfully created trigger {response.name}")

REST

טריגר של משימה מיוצג ב-DLP API על ידי המשאב JobTrigger. כדי ליצור טריגר חדש למשימה, משתמשים ב-method‏ projects.jobTriggers.create של המשאב JobTrigger.

אפשר לשלוח את ה-JSON לדוגמה בבקשת POST לנקודת הקצה (endpoint) שצוינה ב-REST של Sensitive Data Protection. דוגמת ה-JSON הבאה ממחישה איך ליצור טריגר של משימה ב-Sensitive Data Protection. המשימה שהטריגר הזה יפעיל היא סריקת בדיקה של Datastore. הטריגר של המשימה שנוצר פועל כל 86,400 שניות (או 24 שעות).

כדי לנסות את זה במהירות, אתם יכולים להשתמש ב-API Explorer שמוטמע בהמשך. חשוב לזכור שבקשה מוצלחת, גם כזו שנוצרה ב-API Explorer, תיצור טריגר חדש של משימה מתוזמנת. למידע כללי על השימוש ב-JSON כדי לשלוח בקשות ל-DLP API, קראו את המדריך למתחילים בנושא JSON.

קלט JSON:

{
  "jobTrigger":{
    "displayName":"JobTrigger1",
    "description":"Starts an inspection of a Datastore kind",
    "triggers":[
      {
        "schedule":{
          "recurrencePeriodDuration":"86400s"
        }
      }
    ],
    "status":"HEALTHY",
    "inspectJob":{
      "storageConfig":{
        "datastoreOptions":{
          "kind":{
            "name":"Example-Kind"
          },
          "partitionId":{
            "projectId":"[PROJECT_ID]",
            "namespaceId":"[NAMESPACE_ID]"
          }
        }
      },
      "inspectConfig":{
        "infoTypes":[
          {
            "name":"PHONE_NUMBER"
          }
        ],
        "excludeInfoTypes":false,
        "includeQuote":true,
        "minLikelihood":"LIKELY"
      },
      "actions":[
        {
          "saveFindings":{
            "outputConfig":{
              "table":{
                "projectId":"[PROJECT_ID]",
                "datasetId":"[BIGQUERY_DATASET_NAME]",
                "tableId":"[BIGQUERY_TABLE_NAME]"
              }
            }
          }
        }
      ]
    }
  }
}

פלט מסוג JSON:

הפלט הבא מציין שהטריגר של המשימה נוצר בהצלחה.

{
  "name":"projects/[PROJECT_ID]/jobTriggers/[JOB_TRIGGER_NAME]",
  "displayName":"JobTrigger1",
  "description":"Starts an inspection of a Datastore kind",
  "inspectJob":{
    "storageConfig":{
      "datastoreOptions":{
        "partitionId":{
          "projectId":"[PROJECT_ID]",
          "namespaceId":"[NAMESPACE_ID]"
        },
        "kind":{
          "name":"Example-Kind"
        }
      }
    },
    "inspectConfig":{
      "infoTypes":[
        {
          "name":"PHONE_NUMBER"
        }
      ],
      "minLikelihood":"LIKELY",
      "limits":{

      },
      "includeQuote":true
    },
    "actions":[
      {
        "saveFindings":{
          "outputConfig":{
            "table":{
              "projectId":"[PROJECT_ID]",
              "datasetId":"[BIGQUERY_DATASET_NAME]",
              "tableId":"[BIGQUERY_TABLE_NAME]"
            }
          }
        }
      }
    ]
  },
  "triggers":[
    {
      "schedule":{
        "recurrencePeriodDuration":"86400s"
      }
    }
  ],
  "createTime":"2018-11-30T01:52:41.171857Z",
  "updateTime":"2018-11-30T01:52:41.171857Z",
  "status":"HEALTHY"
}

הצגת רשימה של כל המשימות

כדי להציג את כל המשימות בפרויקט הנוכחי:

המסוף

  1. נכנסים לדף Sensitive Data Protection במסוף Google Cloud .

    כניסה ל-Sensitive Data Protection

  2. לוחצים על הכרטיסייה Inspection ואז על כרטיסיית המשנה Inspect jobs.

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

C#

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;

public class JobsList
{
    public static PagedEnumerable<ListDlpJobsResponse, DlpJob> ListDlpJobs(string projectId, string filter, DlpJobType jobType)
    {
        var dlp = DlpServiceClient.Create();

        var response = dlp.ListDlpJobs(new ListDlpJobsRequest
        {
            Parent = new LocationName(projectId, "global").ToString(),
            Filter = filter,
            Type = jobType
        });

        // Uncomment to print jobs
        // foreach (var job in response)
        // {
        //     Console.WriteLine($"Job: {job.Name} status: {job.State}");
        // }

        return response;
    }
}

Go

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
	"google.golang.org/api/iterator"
)

// listJobs lists jobs matching the given optional filter and optional jobType.
func listJobs(w io.Writer, projectID, filter, jobType string) error {
	// projectID := "my-project-id"
	// filter := "`state` = FINISHED"
	// jobType := "RISK_ANALYSIS_JOB"
	ctx := context.Background()
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("dlp.NewClient: %w", err)
	}
	defer client.Close()

	// Create a configured request.
	req := &dlppb.ListDlpJobsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
		Filter: filter,
		Type:   dlppb.DlpJobType(dlppb.DlpJobType_value[jobType]),
	}
	// Send the request and iterate over the results.
	it := client.ListDlpJobs(ctx, req)
	for {
		j, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Next: %w", err)
		}
		fmt.Fprintf(w, "Job %v status: %v\n", j.GetName(), j.GetState())
	}
	return nil
}

Java

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.DlpJob;
import com.google.privacy.dlp.v2.DlpJobType;
import com.google.privacy.dlp.v2.ListDlpJobsRequest;
import com.google.privacy.dlp.v2.LocationName;
import java.io.IOException;

public class JobsList {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    listJobs(projectId);
  }

  // Lists DLP jobs
  public static void listJobs(String projectId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

      // Construct the request to be sent by the client.
      // For more info on filters and job types,
      // see https://cloud.google.com/dlp/docs/reference/rest/v2/projects.dlpJobs/list
      ListDlpJobsRequest listDlpJobsRequest =
          ListDlpJobsRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setFilter("state=DONE")
              .setType(DlpJobType.valueOf("INSPECT_JOB"))
              .build();

      // Send the request to list jobs and process the response
      DlpServiceClient.ListDlpJobsPagedResponse response =
          dlpServiceClient.listDlpJobs(listDlpJobsRequest);

      System.out.println("DLP jobs found:");
      for (DlpJob dlpJob : response.getPage().getValues()) {
        System.out.println(dlpJob.getName() + " -- " + dlpJob.getState());
      }
    }
  }
}

Node.js

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'my-project';

// The filter expression to use
// For more information and filter syntax, see https://cloud.google.com/dlp/docs/reference/rest/v2/projects.dlpJobs/list
// const filter = `state=DONE`;

// The type of job to list (either 'INSPECT_JOB' or 'RISK_ANALYSIS_JOB')
// const jobType = 'INSPECT_JOB';
async function listJobs() {
  // Construct request for listing DLP scan jobs
  const request = {
    parent: `projects/${projectId}/locations/global`,
    filter: filter,
    type: jobType,
  };

  // Run job-listing request
  const [jobs] = await dlp.listDlpJobs(request);
  jobs.forEach(job => {
    console.log(`Job ${job.name} status: ${job.state}`);
  });
}

listJobs();

PHP

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\DlpJob\JobState;
use Google\Cloud\Dlp\V2\DlpJobType;
use Google\Cloud\Dlp\V2\ListDlpJobsRequest;

/**
 * List Data Loss Prevention API jobs corresponding to a given filter.
 *
 * @param string $callingProjectId  The project ID to run the API call under
 * @param string $filter            The filter expression to use
 */
function list_jobs(string $callingProjectId, string $filter): void
{
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // The type of job to list (either 'INSPECT_JOB' or 'REDACT_JOB')
    $jobType = DlpJobType::INSPECT_JOB;

    // Run job-listing request
    // For more information and filter syntax,
    // @see https://cloud.google.com/dlp/docs/reference/rest/v2/projects.dlpJobs/list
    $parent = "projects/$callingProjectId/locations/global";
    $listDlpJobsRequest = (new ListDlpJobsRequest())
        ->setParent($parent)
        ->setFilter($filter)
        ->setType($jobType);
    $response = $dlp->listDlpJobs($listDlpJobsRequest);

    // Print job list
    $jobs = $response->iterateAllElements();
    foreach ($jobs as $job) {
        printf('Job %s status: %s' . PHP_EOL, $job->getName(), $job->getState());
        $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();

        if ($job->getState() == JobState::DONE) {
            if (count($infoTypeStats) > 0) {
                foreach ($infoTypeStats as $infoTypeStat) {
                    printf(
                        '  Found %s instance(s) of type %s' . PHP_EOL,
                        $infoTypeStat->getCount(),
                        $infoTypeStat->getInfoType()->getName()
                    );
                }
            } else {
                print('  No findings.' . PHP_EOL);
            }
        }
    }
}

Python

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


from typing import Optional

import google.cloud.dlp


def list_dlp_jobs(
    project: str, filter_string: Optional[str] = None, job_type: Optional[str] = None
) -> None:
    """Uses the Data Loss Prevention API to lists DLP jobs that match the
        specified filter in the request.
    Args:
        project: The project id to use as a parent resource.
        filter: (Optional) Allows filtering.
            Supported syntax:
            * Filter expressions are made up of one or more restrictions.
            * Restrictions can be combined by 'AND' or 'OR' logical operators.
            A sequence of restrictions implicitly uses 'AND'.
            * A restriction has the form of '<field> <operator> <value>'.
            * Supported fields/values for inspect jobs:
                - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED
                - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY
                - `trigger_name` - The resource name of the trigger that
                                   created job.
            * Supported fields for risk analysis jobs:
                - `state` - RUNNING|CANCELED|FINISHED|FAILED
            * The operator must be '=' or '!='.
            Examples:
            * inspected_storage = cloud_storage AND state = done
            * inspected_storage = cloud_storage OR inspected_storage = bigquery
            * inspected_storage = cloud_storage AND
                                  (state = done OR state = canceled)
        type: (Optional) The type of job. Defaults to 'INSPECT'.
            Choices:
            DLP_JOB_TYPE_UNSPECIFIED
            INSPECT_JOB: The job inspected content for sensitive data.
            RISK_ANALYSIS_JOB: The job executed a Risk Analysis computation.

    Returns:
        None; the response from the API is printed to the terminal.
    """

    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Convert the project id into a full resource id.
    parent = f"projects/{project}"

    # Job type dictionary
    job_type_to_int = {
        "DLP_JOB_TYPE_UNSPECIFIED": google.cloud.dlp.DlpJobType.DLP_JOB_TYPE_UNSPECIFIED,
        "INSPECT_JOB": google.cloud.dlp.DlpJobType.INSPECT_JOB,
        "RISK_ANALYSIS_JOB": google.cloud.dlp.DlpJobType.RISK_ANALYSIS_JOB,
    }
    # If job type is specified, convert job type to number through enums.
    if job_type:
        job_type = job_type_to_int[job_type]

    # Call the API to get a list of jobs.
    response = dlp.list_dlp_jobs(
        request={"parent": parent, "filter": filter_string, "type_": job_type}
    )

    # Iterate over results.
    for job in response:
        print(f"Job: {job.name}; status: {job.state.name}")

REST

למשאב DlpJob יש את ה-method‏ projects.dlpJobs.list, שבאמצעותה אפשר להציג את כל המשימות.

כדי להציג את כל המשימות שמוגדרות כרגע בפרויקט, שולחים בקשת GET לנקודת הקצה dlpJobs, כמו בדוגמה הבאה:

כתובת ה-URL:

GET https://dlp.googleapis.com/v2/projects/[PROJECT-ID]/dlpJobs?key={YOUR_API_KEY}

פלט ה-JSON הבא מציג את אחת מהמשימות שהוחזרו. שימו לב שהמבנה של המשימה משקף את המבנה של המשאב DlpJob.

פלט מסוג JSON:

{
  "jobs":[
    {
      "name":"projects/[PROJECT-ID]/dlpJobs/i-5270277269264714623",
      "type":"INSPECT_JOB",
      "state":"DONE",
      "inspectDetails":{
        "requestedOptions":{
          "snapshotInspectTemplate":{
          },
          "jobConfig":{
            "storageConfig":{
              "cloudStorageOptions":{
                "fileSet":{
                  "url":"[CLOUD-STORAGE-URL]"
                },
                "fileTypes":[
                  "FILE_TYPE_UNSPECIFIED"
                ],
                "filesLimitPercent":100
              },
              "timespanConfig":{
                "startTime":"2019-09-08T22:43:16.623Z",
                "enableAutoPopulationOfTimespanConfig":true
              }
            },
            "inspectConfig":{
              "infoTypes":[
                {
                  "name":"US_SOCIAL_SECURITY_NUMBER"
                },
                {
                  "name":"CANADA_SOCIAL_INSURANCE_NUMBER"
                }
              ],
              "minLikelihood":"LIKELY",
              "limits":{
              },
              "includeQuote":true
            },
            "actions":[
              {
                "saveFindings":{
                  "outputConfig":{
                    "table":{
                      "projectId":"[PROJECT-ID]",
                      "datasetId":"[DATASET-ID]",
                      "tableId":"[TABLE-ID]"
                    }
                  }
                }
              }
            ]
          }
        },
        "result":{
          ...
        }
      },
      "createTime":"2019-09-09T22:43:16.918Z",
      "startTime":"2019-09-09T22:43:16.918Z",
      "endTime":"2019-09-09T22:43:53.091Z",
      "jobTriggerName":"projects/[PROJECT-ID]/jobTriggers/sample-trigger2"
    },
    ...

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

רשימה של כל הטריגרים של המשימות

כדי להציג רשימה של כל הטריגרים של המשימות בפרויקט הנוכחי:

המסוף

נכנסים לדף Sensitive Data Protection במסוף Google Cloud .

כניסה ל-Sensitive Data Protection

בכרטיסיית המשנה Job triggers שבכרטיסייה Inspection, מוצגת רשימה של כל הטריגרים למשימות בפרויקט הנוכחי.

C#

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;
using System;

public class TriggersList
{
    public static PagedEnumerable<ListJobTriggersResponse, JobTrigger> List(string projectId)
    {
        var dlp = DlpServiceClient.Create();

        var response = dlp.ListJobTriggers(
            new ListJobTriggersRequest
            {
                Parent = new LocationName(projectId, "global").ToString(),
            });

        foreach (var trigger in response)
        {
            Console.WriteLine($"Name: {trigger.Name}");
            Console.WriteLine($"  Created: {trigger.CreateTime}");
            Console.WriteLine($"  Updated: {trigger.UpdateTime}");
            Console.WriteLine($"  Display Name: {trigger.DisplayName}");
            Console.WriteLine($"  Description: {trigger.Description}");
            Console.WriteLine($"  Status: {trigger.Status}");
            Console.WriteLine($"  Error count: {trigger.Errors.Count}");
        }

        return response;
    }
}

Go

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"
	"time"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
	"github.com/golang/protobuf/ptypes"
	"google.golang.org/api/iterator"
)

// listTriggers lists the triggers for the given project.
func listTriggers(w io.Writer, projectID string) error {
	// projectID := "my-project-id"

	ctx := context.Background()

	client, err := dlp.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("dlp.NewClient: %w", err)
	}
	defer client.Close()

	// Create a configured request.
	req := &dlppb.ListJobTriggersRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
	}
	// Send the request and iterate over the results.
	it := client.ListJobTriggers(ctx, req)
	for {
		t, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Next: %w", err)
		}
		fmt.Fprintf(w, "Trigger %v\n", t.GetName())
		c, err := ptypes.Timestamp(t.GetCreateTime())
		if err != nil {
			return fmt.Errorf("CreateTime Timestamp: %w", err)
		}
		fmt.Fprintf(w, "  Created: %v\n", c.Format(time.RFC1123))
		u, err := ptypes.Timestamp(t.GetUpdateTime())
		if err != nil {
			return fmt.Errorf("UpdateTime Timestamp: %w", err)
		}
		fmt.Fprintf(w, "  Updated: %v\n", u.Format(time.RFC1123))
		fmt.Fprintf(w, "  Display Name: %q\n", t.GetDisplayName())
		fmt.Fprintf(w, "  Description: %q\n", t.GetDescription())
		fmt.Fprintf(w, "  Status: %v\n", t.GetStatus())
		fmt.Fprintf(w, "  Error Count: %v\n", len(t.GetErrors()))
	}

	return nil
}

Java

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.JobTrigger;
import com.google.privacy.dlp.v2.ListJobTriggersRequest;
import com.google.privacy.dlp.v2.LocationName;
import java.io.IOException;

class TriggersList {
  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    listTriggers(projectId);
  }

  public static void listTriggers(String projectId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {
      // Build the request to be sent by the client
      ListJobTriggersRequest listJobTriggersRequest =
          ListJobTriggersRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .build();

      // Use the client to send the API request.
      DlpServiceClient.ListJobTriggersPagedResponse response =
          dlpServiceClient.listJobTriggers(listJobTriggersRequest);

      // Parse the response and process the results
      System.out.println("DLP triggers found:");
      for (JobTrigger trigger : response.getPage().getValues()) {
        System.out.println("Trigger: " + trigger.getName());
        System.out.println("\tCreated: " + trigger.getCreateTime());
        System.out.println("\tUpdated: " + trigger.getUpdateTime());
        if (trigger.getDisplayName() != null) {
          System.out.println("\tDisplay name: " + trigger.getDisplayName());
        }
        if (trigger.getDescription() != null) {
          System.out.println("\tDescription: " + trigger.getDescription());
        }
        System.out.println("\tStatus: " + trigger.getStatus());
        System.out.println("\tError count: " + trigger.getErrorsCount());
      }
      ;
    }
  }
}

Node.js

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'my-project'

async function listTriggers() {
  // Construct trigger listing request
  const request = {
    parent: `projects/${projectId}/locations/global`,
  };

  // Helper function to pretty-print dates
  const formatDate = date => {
    const msSinceEpoch = parseInt(date.seconds, 10) * 1000;
    return new Date(msSinceEpoch).toLocaleString('en-US');
  };

  // Run trigger listing request
  const [triggers] = await dlp.listJobTriggers(request);
  triggers.forEach(trigger => {
    // Log trigger details
    console.log(`Trigger ${trigger.name}:`);
    console.log(`  Created: ${formatDate(trigger.createTime)}`);
    console.log(`  Updated: ${formatDate(trigger.updateTime)}`);
    if (trigger.displayName) {
      console.log(`  Display Name: ${trigger.displayName}`);
    }
    if (trigger.description) {
      console.log(`  Description: ${trigger.description}`);
    }
    console.log(`  Status: ${trigger.status}`);
    console.log(`  Error count: ${trigger.errors.length}`);
  });
}

listTriggers();

PHP

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\ListJobTriggersRequest;

/**
 * List Data Loss Prevention API job triggers.
 *
 * @param string $callingProjectId  The project ID to run the API call under
 */
function list_triggers(string $callingProjectId): void
{
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    $parent = "projects/$callingProjectId/locations/global";

    // Run request
    $listJobTriggersRequest = (new ListJobTriggersRequest())
        ->setParent($parent);
    $response = $dlp->listJobTriggers($listJobTriggersRequest);

    // Print results
    $triggers = $response->iterateAllElements();
    foreach ($triggers as $trigger) {
        printf('Trigger %s' . PHP_EOL, $trigger->getName());
        printf('  Created: %s' . PHP_EOL, $trigger->getCreateTime()->getSeconds());
        printf('  Updated: %s' . PHP_EOL, $trigger->getUpdateTime()->getSeconds());
        printf('  Display Name: %s' . PHP_EOL, $trigger->getDisplayName());
        printf('  Description: %s' . PHP_EOL, $trigger->getDescription());
        printf('  Status: %s' . PHP_EOL, $trigger->getStatus());
        printf('  Error count: %s' . PHP_EOL, count($trigger->getErrors()));
        $timespanConfig = $trigger->getInspectJob()->getStorageConfig()->getTimespanConfig();
        printf('  Auto-populates timespan config: %s' . PHP_EOL,
            ($timespanConfig && $timespanConfig->getEnableAutoPopulationOfTimespanConfig() ? 'yes' : 'no'));
    }
}

Python

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import google.cloud.dlp


def list_triggers(project: str) -> None:
    """Lists all Data Loss Prevention API triggers.
    Args:
        project: The Google Cloud project id to use as a parent resource.
    Returns:
        None; the response from the API is printed to the terminal.
    """

    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Convert the project id into a full resource id.
    parent = f"projects/{project}"

    # Call the API.
    response = dlp.list_job_triggers(request={"parent": parent})

    for trigger in response:
        print(f"Trigger {trigger.name}:")
        print(f"  Created: {trigger.create_time}")
        print(f"  Updated: {trigger.update_time}")
        if trigger.display_name:
            print(f"  Display Name: {trigger.display_name}")
        if trigger.description:
            print(f"  Description: {trigger.description}")
        print(f"  Status: {trigger.status}")
        print(f"  Error count: {len(trigger.errors)}")

REST

למשאב JobTrigger יש את ה-method‏ projects.jobTriggers.list, שבאמצעותה אפשר להציג את כל הטריגרים של המשימות.

כדי להציג את כל הטריגרים של המשימות שמוגדרים כרגע בפרויקט, שולחים בקשת GET לנקודת הקצה jobTriggers, כמו שמוצג כאן:

כתובת ה-URL:

GET https://dlp.googleapis.com/v2/projects/[PROJECT-ID]/jobTriggers?key={YOUR_API_KEY}

פלט ה-JSON הבא מציג את הטריגר של המשימה שיצרנו בקטע הקודם. שימו לב שהמבנה של הטריגר של המשימה משקף את המבנה של המשאב JobTrigger.

פלט מסוג JSON:

{
  "jobTriggers":[
    {
      "name":"projects/[PROJECT_ID]/jobTriggers/[JOB_TRIGGER_NAME]",
      "displayName":"JobTrigger1",
      "description":"Starts an inspection of a Datastore kind",
      "inspectJob":{
        "storageConfig":{
          "datastoreOptions":{
            "partitionId":{
              "projectId":"[PROJECT_ID]",
              "namespaceId":"[NAMESPACE_ID]"
            },
            "kind":{
              "name":"Example-Kind"
            }
          }
        },
        "inspectConfig":{
          "infoTypes":[
            {
              "name":"PHONE_NUMBER"
            }
          ],
          "minLikelihood":"LIKELY",
          "limits":{

          },
          "includeQuote":true
        },
        "actions":[
          {
            "saveFindings":{
              "outputConfig":{
                "table":{
                  "projectId":"[PROJECT_ID]",
                  "datasetId":"[BIGQUERY_DATASET_NAME]",
                  "tableId":"[BIGQUERY_TABLE_NAME]"
                }
              }
            }
          }
        ]
      },
      "triggers":[
        {
          "schedule":{
            "recurrencePeriodDuration":"86400s"
          }
        }
      ],
      "createTime":"2018-11-30T01:52:41.171857Z",
      "updateTime":"2018-11-30T01:52:41.171857Z",
      "status":"HEALTHY"
    },

    ...

],
  "nextPageToken":"KkwKCQjivJ2UpPreAgo_Kj1wcm9qZWN0cy92ZWx2ZXR5LXN0dWR5LTE5NjEwMS9qb2JUcmlnZ2Vycy8xNTA5NzEyOTczMDI0MDc1NzY0"
}

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

מחיקת משרה

כדי למחוק משימה מהפרויקט, כולל התוצאות שלה: הפעולה הזו לא משפיעה על תוצאות שנשמרו מחוץ ל-Google Ads (למשל ב-BigQuery).

המסוף

  1. נכנסים לדף Sensitive Data Protection במסוף Google Cloud .

    כניסה ל-Sensitive Data Protection

  2. לוחצים על הכרטיסייה Inspection ואז על כרטיסיית המשנה Inspect jobs. במסוף Google Cloud תוצג רשימה של כל המשימות בפרויקט הנוכחי.

  3. בעמודה Actions של הטריגר שרוצים למחוק, לוחצים על תפריט האפשרויות הנוספות (שלוש נקודות אנכיות) ואז על Delete.

אפשר גם ללחוץ על המזהה של המשימה שרוצים למחוק ברשימת המשימות. בדף הפרטים של המשימה, לוחצים על מחיקה.

C#

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


using System;
using Google.Cloud.Dlp.V2;

public class JobsDelete
{
    public static void DeleteJob(string jobName)
    {
        var dlp = DlpServiceClient.Create();

        dlp.DeleteDlpJob(new DeleteDlpJobRequest
        {
            Name = jobName
        });

        Console.WriteLine($"Successfully deleted job {jobName}.");
    }
}

Go

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// deleteJob deletes the job with the given name.
func deleteJob(w io.Writer, jobName string) error {
	// jobName := "job-example"
	ctx := context.Background()
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("dlp.NewClient: %w", err)
	}
	defer client.Close()
	req := &dlppb.DeleteDlpJobRequest{
		Name: jobName,
	}
	if err = client.DeleteDlpJob(ctx, req); err != nil {
		return fmt.Errorf("DeleteDlpJob: %w", err)
	}
	fmt.Fprintf(w, "Successfully deleted job")
	return nil
}

Java

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.DeleteDlpJobRequest;
import com.google.privacy.dlp.v2.DlpJobName;
import java.io.IOException;

public class JobsDelete {
  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String jobId = "your-job-id";
    deleteJobs(projectId, jobId);
  }

  // Deletes a DLP Job with the given jobId
  public static void deleteJobs(String projectId, String jobId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

      // Construct the complete job name from the projectId and jobId
      DlpJobName jobName = DlpJobName.of(projectId, jobId);

      // Construct the job deletion request to be sent by the client.
      DeleteDlpJobRequest deleteDlpJobRequest =
          DeleteDlpJobRequest.newBuilder().setName(jobName.toString()).build();

      // Send the job deletion request
      dlpServiceClient.deleteDlpJob(deleteDlpJobRequest);
      System.out.println("Job deleted successfully.");
    }
  }
}

Node.js

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'my-project';

// The name of the job whose results should be deleted
// Parent project ID is automatically extracted from this parameter
// const jobName = 'projects/my-project/dlpJobs/X-#####'

function deleteJob() {
  // Construct job deletion request
  const request = {
    name: jobName,
  };

  // Run job deletion request
  dlp
    .deleteDlpJob(request)
    .then(() => {
      console.log(`Successfully deleted job ${jobName}.`);
    })
    .catch(err => {
      console.log(`Error in deleteJob: ${err.message || err}`);
    });
}

deleteJob();

PHP

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\DeleteDlpJobRequest;

/**
 * Delete results of a Data Loss Prevention API job
 *
 * @param string $jobId The name of the job whose results should be deleted
 */
function delete_job(string $jobId): void
{
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Run job-deletion request
    // The Parent project ID is automatically extracted from this parameter
    $deleteDlpJobRequest = (new DeleteDlpJobRequest())
        ->setName($jobId);
    $dlp->deleteDlpJob($deleteDlpJobRequest);

    // Print status
    printf('Successfully deleted job %s' . PHP_EOL, $jobId);
}

Python

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import google.cloud.dlp


def delete_dlp_job(project: str, job_name: str) -> None:
    """Uses the Data Loss Prevention API to delete a long-running DLP job.
    Args:
        project: The project id to use as a parent resource.
        job_name: The name of the DlpJob resource to be deleted.

    Returns:
        None; the response from the API is printed to the terminal.
    """

    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Convert the project id and job name into a full resource id.
    name = f"projects/{project}/dlpJobs/{job_name}"

    # Call the API to delete job.
    dlp.delete_dlp_job(request={"name": name})

    print(f"Successfully deleted {job_name}")

REST

כדי למחוק משימה מהפרויקט הנוכחי, שולחים בקשת DELETE לנקודת הקצה dlpJobs, כמו שמוצג כאן. מחליפים את השדה [JOB-IDENTIFIER] במזהה של המשימה, שמתחיל ב-i-.

כתובת ה-URL:

DELETE https://dlp.googleapis.com/v2/projects/[PROJECT-ID]/dlpJobs/[JOB-IDENTIFIER]?key={YOUR_API_KEY}

אם הבקשה תצליח, ה-DLP API יחזיר תגובת הצלחה. כדי לוודא שהמשימה נמחקה, מציגים את רשימת כל המשימות.

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

מחיקת טריגר של משימה

המסוף

  1. נכנסים לדף Sensitive Data Protection במסוף Google Cloud .

    כניסה ל-Sensitive Data Protection

    בכרטיסייה Inspection, בכרטיסיית המשנה Job triggers, מוצגת רשימה של כל הטריגרים של המשימות בפרויקט הנוכחי.

  2. בעמודה Actions של הטריגר שרוצים למחוק, לוחצים על תפריט האפשרויות הנוספות (שלוש נקודות אנכיות) ואז על Delete.

לחלופין, ברשימת הטריגרים של המשימות, לוחצים על השם של הטריגר שרוצים למחוק. בדף הפרטים של הטריגר למשימה, לוחצים על Delete.

C#

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


using Google.Cloud.Dlp.V2;
using System;

public class TriggersDelete
{

    public static void Delete(string triggerName)
    {
        var dlp = DlpServiceClient.Create();

        dlp.DeleteJobTrigger(
            new DeleteJobTriggerRequest
            {
                Name = triggerName
            });

        Console.WriteLine($"Successfully deleted trigger {triggerName}.");
    }
}

Go

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// deleteTrigger deletes the given trigger.
func deleteTrigger(w io.Writer, triggerID string) error {
	// triggerID := "my-trigger"

	ctx := context.Background()

	client, err := dlp.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("dlp.NewClient: %w", err)
	}
	defer client.Close()

	req := &dlppb.DeleteJobTriggerRequest{
		Name: triggerID,
	}

	if err := client.DeleteJobTrigger(ctx, req); err != nil {
		return fmt.Errorf("DeleteJobTrigger: %w", err)
	}
	fmt.Fprintf(w, "Successfully deleted trigger %v", triggerID)
	return nil
}

Java

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.DeleteJobTriggerRequest;
import com.google.privacy.dlp.v2.ProjectJobTriggerName;
import java.io.IOException;

class TriggersDelete {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String triggerId = "your-trigger-id";
    deleteTrigger(projectId, triggerId);
  }

  public static void deleteTrigger(String projectId, String triggerId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

      // Get the full trigger name from the given triggerId and ProjectId
      ProjectJobTriggerName triggerName = ProjectJobTriggerName.of(projectId, triggerId);

      // Construct the trigger deletion request to be sent by the client
      DeleteJobTriggerRequest deleteJobTriggerRequest =
          DeleteJobTriggerRequest.newBuilder().setName(triggerName.toString()).build();

      // Send the trigger deletion request
      dlpServiceClient.deleteJobTrigger(deleteJobTriggerRequest);
      System.out.println("Trigger deleted: " + triggerName.toString());
    }
  }
}

Node.js

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'my-project'

// The name of the trigger to be deleted
// Parent project ID is automatically extracted from this parameter
// const triggerId = 'projects/my-project/triggers/my-trigger';

async function deleteTrigger() {
  // Construct trigger deletion request
  const request = {
    name: triggerId,
  };

  // Run trigger deletion request
  await dlp.deleteJobTrigger(request);
  console.log(`Successfully deleted trigger ${triggerId}.`);
}

deleteTrigger();

PHP

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\DeleteJobTriggerRequest;

/**
 * Delete a Data Loss Prevention API job trigger.
 *
 * @param string $callingProjectId  The project ID to run the API call under
 * @param string $triggerId         The name of the trigger to be deleted.
 */
function delete_trigger(string $callingProjectId, string $triggerId): void
{
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Run request
    // The Parent project ID is automatically extracted from this parameter
    $triggerName = "projects/$callingProjectId/locations/global/jobTriggers/$triggerId";
    $deleteJobTriggerRequest = (new DeleteJobTriggerRequest())
        ->setName($triggerName);
    $dlp->deleteJobTrigger($deleteJobTriggerRequest);

    // Print the results
    printf('Successfully deleted trigger %s' . PHP_EOL, $triggerName);
}

Python

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import google.cloud.dlp


def delete_trigger(project: str, trigger_id: str) -> None:
    """Deletes a Data Loss Prevention API trigger.
    Args:
        project: The id of the Google Cloud project which owns the trigger.
        trigger_id: The id of the trigger to delete.
    Returns:
        None; the response from the API is printed to the terminal.
    """

    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Convert the project id into a full resource id.
    parent = f"projects/{project}"

    # Combine the trigger id with the parent id.
    trigger_resource = f"{parent}/jobTriggers/{trigger_id}"

    # Call the API.
    dlp.delete_job_trigger(request={"name": trigger_resource})

    print(f"Trigger {trigger_resource} successfully deleted.")

REST

כדי למחוק טריגר של משימה מהפרויקט הנוכחי, שולחים בקשת DELETE לנקודת הקצה (endpoint) jobTriggers, כמו שמוצג כאן. מחליפים את השדה [JOB-TRIGGER-NAME] בשם של הטריגר להפעלה של משימה.

כתובת ה-URL:

DELETE https://dlp.googleapis.com/v2/projects/[PROJECT-ID]/jobTriggers/[JOB-TRIGGER-NAME]?key={YOUR_API_KEY}

אם הבקשה תצליח, ה-DLP API יחזיר תגובת הצלחה. כדי לוודא שהטריגר של המשימה נמחק, מציגים את כל הטריגרים של המשימות.

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

למצוא עבודה

כדי לקבל משימה מהפרויקט, כולל התוצאות שלה, מבצעים את הפעולות הבאות. הפעולה הזו לא משפיעה על תוצאות שנשמרו באופן חיצוני (למשל ב-BigQuery).

C#

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


using Google.Cloud.Dlp.V2;
using System;

public class JobsGet
{
    public static DlpJob GetDlpJob(string jobName)
    {
        var dlp = DlpServiceClient.Create();

        var response = dlp.GetDlpJob(jobName);

        Console.WriteLine($"Job: {response.Name} status: {response.State}");

        return response;
    }
}

Go

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// jobsGet gets an inspection job using jobName
func jobsGet(w io.Writer, projectID string, jobName string) error {
	// projectId := "my-project-id"
	// jobName := "your-job-id"

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return err
	}

	// Closing the client safely cleans up background resources.
	defer client.Close()

	// Construct the request to be sent by the client.
	req := &dlppb.GetDlpJobRequest{
		Name: jobName,
	}

	// Send the request.
	resp, err := client.GetDlpJob(ctx, req)
	if err != nil {
		return err
	}

	// Print the results.
	fmt.Fprintf(w, "Job Name: %v Job Status: %v", resp.Name, resp.State)
	return nil
}

Java

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.DlpJobName;
import com.google.privacy.dlp.v2.GetDlpJobRequest;
import java.io.IOException;

public class JobsGet {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String jobId = "your-job-id";
    getJobs(projectId, jobId);
  }

  // Gets a DLP Job with the given jobId
  public static void getJobs(String projectId, String jobId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

      // Construct the complete job name from the projectId and jobId
      DlpJobName jobName = DlpJobName.of(projectId, jobId);

      // Construct the get job request to be sent by the client.
      GetDlpJobRequest getDlpJobRequest =
          GetDlpJobRequest.newBuilder().setName(jobName.toString()).build();

      // Send the get job request
      dlpServiceClient.getDlpJob(getDlpJobRequest);
      System.out.println("Job got successfully.");
    }
  }
}

Node.js

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// Job name to look for
// const jobName = 'your-job-name';

async function getJob() {
  // Construct request for finding job using job name.
  const request = {
    name: jobName,
  };

  // Send the request and receive response from the service
  const [job] = await dlp.getDlpJob(request);

  // Print results.
  console.log(`Job ${job.name} status: ${job.state}`);
}

getJob();

PHP

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\GetDlpJobRequest;

/**
 * Get DLP inspection job.
 * @param string $jobName           Dlp job name
 */
function get_job(
    string $jobName
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();
    try {
        // Send the get job request
        $getDlpJobRequest = (new GetDlpJobRequest())
            ->setName($jobName);
        $response = $dlp->getDlpJob($getDlpJobRequest);
        printf('Job %s status: %s' . PHP_EOL, $response->getName(), $response->getState());
    } finally {
        $dlp->close();
    }
}

Python

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import google.cloud.dlp


def get_dlp_job(project: str, job_name: str) -> None:
    """Uses the Data Loss Prevention API to retrieve a DLP job.
    Args:
        project: The project id to use as a parent resource.
        job_name: The name of the DlpJob resource to be retrieved.
    """

    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Convert the project id and job name into a full resource id.
    job_name = f"projects/{project}/locations/global/dlpJobs/{job_name}"

    # Call the API
    response = dlp.get_dlp_job(request={"name": job_name})

    print(f"Job: {response.name} Status: {response.state}")

REST

כדי לקבל משימה מהפרויקט הנוכחי, שולחים בקשת GET לנקודת הקצה (endpoint) dlpJobs, כמו שמוצג כאן. מחליפים את השדה [JOB-IDENTIFIER] במזהה של המשימה, שמתחיל ב-i-.

כתובת ה-URL:

GET https://dlp.googleapis.com/v2/projects/[PROJECT-ID]/dlpJobs/[JOB-IDENTIFIER]?key={YOUR_API_KEY}

אם הבקשה תצליח, ה-DLP API יחזיר תגובת הצלחה.

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

הפעלה מיידית של טריגר למשימה

אחרי שיוצרים טריגר למשימה, אפשר להפעיל אותו כדי לאלץ הפעלה מיידית של הטריגר לצורך בדיקה. כדי לעשות את זה, מריצים את הפקודה הבאה:

curl --request POST \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "X-Goog-User-Project: PROJECT_ID" \
    'https://dlp.googleapis.com/v2/JOB_TRIGGER_NAME:activate'

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

  • ‫PROJECT_ID: המזהה של הפרויקט ב- Google Cloud שבו יחויבו עלויות הגישה שקשורות לבקשה.
  • ‫JOB_TRIGGER_NAME: שם המשאב המלא של הטריגר של המשימה, לדוגמה projects/my-project/locations/global/jobTriggers/123456789.

עדכון טריגר קיים של משימה

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

המסוף

  1. נכנסים לדף Sensitive Data Protection במסוף Google Cloud .

    כניסה ל-Sensitive Data Protection

  2. לוחצים על הכרטיסייה Inspection ואז על כרטיסיית המשנה Job triggers.

    במסוף תוצג רשימה של כל הטריגרים של המשימות בפרויקט הנוכחי.

  3. בעמודה Actions של הטריגר שרוצים למחוק, לוחצים על More ואז על View details.

  4. בדף הפרטים של הטריגר, לוחצים על Edit.

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

C#

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


using Google.Cloud.Dlp.V2;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;

public class TriggersUpdate
{
    public static JobTrigger UpdateJob(
        string projectId,
        string triggerId,
        IEnumerable<InfoType> infoTypes = null,
        Likelihood minLikelihood = Likelihood.Likely)
    {
        // Instantiate the client.
        var dlp = DlpServiceClient.Create();

        // Construct the update job trigger request object by providing the trigger name,
        // job trigger object which will specify the type of info to be inspected and
        // update mask object which specifies the field to be updated.
        // Refer to https://cloud.google.com/dlp/docs/reference/rest/v2/Container for specifying the paths in container object.
        var request = new UpdateJobTriggerRequest
        {
            JobTriggerName = new JobTriggerName(projectId, triggerId),
            JobTrigger = new JobTrigger
            {
                InspectJob = new InspectJobConfig
                {
                    InspectConfig = new InspectConfig
                    {
                        InfoTypes =
                        {
                            infoTypes ?? new InfoType[]
                            {
                                new InfoType { Name = "US_INDIVIDUAL_TAXPAYER_IDENTIFICATION_NUMBER" }
                            }
                        },
                        MinLikelihood = minLikelihood
                    }
                }
            },
            // Specify fields of the jobTrigger resource to be updated when the job trigger is modified.
            // Refer https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask for constructing the field mask paths.
            UpdateMask = new FieldMask
            {
                Paths =
                {
                    "inspect_job.inspect_config.info_types",
                    "inspect_job.inspect_config.min_likelihood"
                }
            }
        };

        // Call the API.
        JobTrigger response = dlp.UpdateJobTrigger(request);

        // Inspect the result.
        Console.WriteLine($"Job Trigger Name: {response.Name}");
        Console.WriteLine($"InfoType updated: {response.InspectJob.InspectConfig.InfoTypes[0]}");
        Console.WriteLine($"Likelihood updated: {response.InspectJob.InspectConfig.MinLikelihood}");
        return response;
    }
}

Go

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

// updateTrigger updates an existing job trigger in Google Cloud Data Loss Prevention (DLP).
// It modifies the configuration of the specified job trigger with the provided updated settings.
func updateTrigger(w io.Writer, jobTriggerName string) error {
	// jobTriggerName := "your-job-trigger-name" (projects/<projectID>/locations/global/jobTriggers/my-trigger)

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return err
	}

	// Closing the client safely cleans up background resources.
	defer client.Close()

	// Specify the type of info the inspection will look for.
	// See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
	infoType := &dlppb.InfoType{
		Name: "PERSON_NAME",
	}

	// Specify the inspectConfig that represents the configuration settings for inspecting sensitive data in
	// DLP API. It includes detection types, custom info types, inspection methods, and actions
	// to be taken on detection.
	inspectConfig := &dlppb.InspectConfig{
		InfoTypes: []*dlppb.InfoType{
			infoType,
		},
		MinLikelihood: dlppb.Likelihood_LIKELY,
	}

	// Configure the inspection job we want the service to perform.
	inspectJobConfig := &dlppb.InspectJobConfig{
		InspectConfig: inspectConfig,
	}

	// Specify the jobTrigger that represents a DLP job trigger configuration.
	// It defines the conditions, actions, and schedule for executing inspections
	// on sensitive data in the specified data storage.
	jobTrigger := &dlppb.JobTrigger{
		Job: &dlppb.JobTrigger_InspectJob{
			InspectJob: inspectJobConfig,
		},
	}

	// fieldMask represents a set of fields to be included in an update operation.
	// It is used to specify which fields of a resource should be updated.
	updateMask := &fieldmaskpb.FieldMask{
		Paths: []string{"inspect_job.inspect_config.info_types", "inspect_job.inspect_config.min_likelihood"},
	}

	// Combine configurations into a request for the service.
	req := &dlppb.UpdateJobTriggerRequest{
		Name:       jobTriggerName,
		JobTrigger: jobTrigger,
		UpdateMask: updateMask,
	}

	// Send the scan request and process the response
	resp, err := client.UpdateJobTrigger(ctx, req)
	if err != nil {
		return err
	}

	// Print the result.
	fmt.Fprintf(w, "Successfully Updated trigger: %v", resp)
	return nil

}

Java

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectJobConfig;
import com.google.privacy.dlp.v2.JobTrigger;
import com.google.privacy.dlp.v2.JobTriggerName;
import com.google.privacy.dlp.v2.Likelihood;
import com.google.privacy.dlp.v2.UpdateJobTriggerRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;

public class TriggersPatch {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.

    // The Google Cloud project id to use as a parent resource.
    String projectId = "your-project-id";
    // The name of the job trigger to be updated.
    String jobTriggerName = "your-job-trigger-name";
    patchTrigger(projectId, jobTriggerName);
  }

  // Uses the Data Loss Prevention API to update an existing job trigger.
  public static void patchTrigger(String projectId, String jobTriggerName) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

      // Specify the type of info the inspection will look for.
      // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
      InfoType infoType = InfoType.newBuilder().setName("PERSON_NAME").build();

      InspectConfig inspectConfig = InspectConfig.newBuilder()
              .addInfoTypes(infoType)
              .setMinLikelihood(Likelihood.LIKELY)
              .build();

      InspectJobConfig inspectJobConfig = InspectJobConfig.newBuilder()
              .setInspectConfig(inspectConfig)
              .build();

      JobTrigger jobTrigger = JobTrigger.newBuilder()
              .setInspectJob(inspectJobConfig)
              .build();

      // Specify fields of the jobTrigger resource to be updated when the job trigger is modified.
      // Refer https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask for constructing the field mask paths.
      FieldMask fieldMask = FieldMask.newBuilder()
              .addPaths("inspect_job.inspect_config.info_types")
              .addPaths("inspect_job.inspect_config.min_likelihood")
              .build();

      // Update the job trigger with the new configuration.
      UpdateJobTriggerRequest updateJobTriggerRequest = UpdateJobTriggerRequest.newBuilder()
              .setName(JobTriggerName.of(projectId, jobTriggerName).toString())
              .setJobTrigger(jobTrigger)
              .setUpdateMask(fieldMask)
              .build();

      // Call the API to update the job trigger.
      JobTrigger updatedJobTrigger = dlpServiceClient.updateJobTrigger(updateJobTriggerRequest);

      System.out.println("Job Trigger Name: " + updatedJobTrigger.getName());
      System.out.println(
          "InfoType updated: "
              + updatedJobTrigger.getInspectJob().getInspectConfig().getInfoTypes(0).getName());
      System.out.println(
          "Likelihood updated: "
              + updatedJobTrigger.getInspectJob().getInspectConfig().getMinLikelihood());
    }
  }
}

Node.js

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlpClient = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'my-project';

// The job trigger ID to run the API call under
// const jobTriggerName = 'your-job-trigger-name';

async function updateTrigger() {
  // Construct inspect configuration to match PERSON_NAME infotype
  const inspectConfig = {
    infoTypes: [{name: 'PERSON_NAME'}],
    minLikelihood: 'LIKELY',
  };

  // Configure the job trigger we want to update.
  const jobTrigger = {inspectJob: {inspectConfig}};

  const updateMask = {
    paths: [
      'inspect_job.inspect_config.info_types',
      'inspect_job.inspect_config.min_likelihood',
    ],
  };

  // Combine configurations into a request for the service.
  const request = {
    name: `projects/${projectId}/jobTriggers/${jobTriggerName}`,
    jobTrigger,
    updateMask,
  };

  // Send the request and receive response from the service
  const [updatedJobTrigger] = await dlpClient.updateJobTrigger(request);

  // Print the results
  console.log(`Updated Trigger: ${JSON.stringify(updatedJobTrigger)}`);
}
updateTrigger(projectId, jobTriggerName);

PHP

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectJobConfig;
use Google\Cloud\Dlp\V2\JobTrigger;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\UpdateJobTriggerRequest;
use Google\Protobuf\FieldMask;

/**
 * Update an existing job trigger.
 *
 * @param string $callingProjectId  The Google Cloud Project ID to run the API call under.
 * @param string $jobTriggerName    The job trigger name to update.
 *
 */
function update_trigger(
    string $callingProjectId,
    string $jobTriggerName
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Configure the inspectConfig.
    $inspectConfig = (new InspectConfig())
        ->setInfoTypes([
            (new InfoType())
                ->setName('US_INDIVIDUAL_TAXPAYER_IDENTIFICATION_NUMBER')
        ])
        ->setMinLikelihood(Likelihood::LIKELY);

    // Configure the Job Trigger we want the service to perform.
    $jobTrigger = (new JobTrigger())
        ->setInspectJob((new InspectJobConfig())
            ->setInspectConfig($inspectConfig));

    // Specify fields of the jobTrigger resource to be updated when the job trigger is modified.
    // Refer https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask for constructing the field mask paths.
    $fieldMask = (new FieldMask())
        ->setPaths([
            'inspect_job.inspect_config.info_types',
            'inspect_job.inspect_config.min_likelihood'
        ]);

    // Send the update job trigger request and process the response.
    $name = "projects/$callingProjectId/locations/global/jobTriggers/" . $jobTriggerName;
    $updateJobTriggerRequest = (new UpdateJobTriggerRequest())
        ->setName($name)
        ->setJobTrigger($jobTrigger)
        ->setUpdateMask($fieldMask);

    $response = $dlp->updateJobTrigger($updateJobTriggerRequest);

    // Print results.
    printf('Successfully update trigger %s' . PHP_EOL, $response->getName());
}

Python

במאמר ספריות הלקוח של Sensitive Data Protection מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

from typing import List

import google.cloud.dlp


def update_trigger(
    project: str,
    info_types: List[str],
    trigger_id: str,
) -> None:
    """Uses the Data Loss Prevention API to update an existing job trigger.
    Args:
        project: The Google Cloud project id to use as a parent resource
        info_types: A list of strings representing infoTypes to update trigger with.
            A full list of infoType categories can be fetched from the API.
        trigger_id: The id of job trigger which needs to be updated.
    """

    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Prepare info_types by converting the list of strings into a list of
    # dictionaries.
    info_types = [{"name": info_type} for info_type in info_types]

    # Specify fields of the jobTrigger resource to be updated when the
    # job trigger is modified.
    job_trigger = {
        "inspect_job": {
            "inspect_config": {
                "info_types": info_types,
                "min_likelihood": google.cloud.dlp_v2.Likelihood.LIKELY,
            }
        }
    }

    # Convert the project id into a full resource id.
    trigger_name = f"projects/{project}/jobTriggers/{trigger_id}"

    # Call the API.
    # Refer https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask
    # for constructing the field mask paths.
    response = dlp.update_job_trigger(
        request={
            "name": trigger_name,
            "job_trigger": job_trigger,
            "update_mask": {
                "paths": [
                    "inspect_job.inspect_config.info_types",
                    "inspect_job.inspect_config.min_likelihood",
                ]
            },
        }
    )

    # Print out the result.
    print(f"Successfully updated trigger: {response.name}")
    print(
        f"Updated InfoType: {response.inspect_job.inspect_config.info_types[0].name}"
        f" \nUpdates Likelihood: {response.inspect_job.inspect_config.min_likelihood}\n",
    )

REST

משתמשים ב-method‏ projects.jobTriggers.patch כדי לשלוח ערכי JobTrigger חדשים ל-DLP API, כדי לעדכן את הערכים האלה בטריגר ספציפי של משימה.

לדוגמה, נניח שיש לכם את הטריגר הפשוט הבא למשימה. קובץ ה-JSON הזה מייצג את הטריגר של המשימה, והוא הוחזר אחרי שליחת בקשת GET לנקודת הקצה של הטריגר של המשימה בפרויקט הנוכחי.

פלט מסוג JSON:

{
  "name":"projects/[PROJECT_ID]/jobTriggers/[JOB_TRIGGER_NAME]",
  "inspectJob":{
    "storageConfig":{
      "cloudStorageOptions":{
        "fileSet":{
          "url":"gs://dlptesting/*"
        },
        "fileTypes":[
          "FILE_TYPE_UNSPECIFIED"
        ],
        "filesLimitPercent":100
      },
      "timespanConfig":{
        "enableAutoPopulationOfTimespanConfig":true
      }
    },
    "inspectConfig":{
      "infoTypes":[
        {
          "name":"US_SOCIAL_SECURITY_NUMBER"
        }
      ],
      "minLikelihood":"POSSIBLE",
      "limits":{

      }
    },
    "actions":[
      {
        "jobNotificationEmails":{

        }
      }
    ]
  },
  "triggers":[
    {
      "schedule":{
        "recurrencePeriodDuration":"86400s"
      }
    }
  ],
  "createTime":"2019-03-06T21:19:45.774841Z",
  "updateTime":"2019-03-06T21:19:45.774841Z",
  "status":"HEALTHY"
}

קוד ה-JSON הבא, כששולחים אותו עם בקשת PATCH לנקודת הקצה שצוינה, מעדכן את הטריגר של המשימה הנתונה עם infoType חדש לסריקה, וגם עם סבירות מינימלית חדשה. שימו לב שצריך לציין גם את המאפיין updateMask, והערך שלו צריך להיות בפורמט FieldMask.

קלט JSON:

PATCH https://dlp.googleapis.com/v2/projects/[PROJECT_ID]/jobTriggers/[JOB_TRIGGER_NAME]?key={YOUR_API_KEY}

{
  "jobTrigger":{
    "inspectJob":{
      "inspectConfig":{
        "infoTypes":[
          {
            "name":"US_INDIVIDUAL_TAXPAYER_IDENTIFICATION_NUMBER"
          }
        ],
        "minLikelihood":"LIKELY"
      }
    }
  },
  "updateMask":"inspectJob(inspectConfig(infoTypes,minLikelihood))"
}

אחרי ששולחים את ה-JSON הזה לכתובת ה-URL שצוינה, הוא מחזיר את התוצאה הבאה, שמייצגת את הטריגר המעודכן של המשימה. שימו לב שהערכים המקוריים של infoType ו-likelihood הוחלפו בערכים החדשים.

פלט מסוג JSON:

{
  "name":"projects/[PROJECT_ID]/jobTriggers/[JOB_TRIGGER_NAME]",
  "inspectJob":{
    "storageConfig":{
      "cloudStorageOptions":{
        "fileSet":{
          "url":"gs://dlptesting/*"
        },
        "fileTypes":[
          "FILE_TYPE_UNSPECIFIED"
        ],
        "filesLimitPercent":100
      },
      "timespanConfig":{
        "enableAutoPopulationOfTimespanConfig":true
      }
    },
    "inspectConfig":{
      "infoTypes":[
        {
          "name":"US_INDIVIDUAL_TAXPAYER_IDENTIFICATION_NUMBER"
        }
      ],
      "minLikelihood":"LIKELY",
      "limits":{

      }
    },
    "actions":[
      {
        "jobNotificationEmails":{

        }
      }
    ]
  },
  "triggers":[
    {
      "schedule":{
        "recurrencePeriodDuration":"86400s"
      }
    }
  ],
  "createTime":"2019-03-06T21:19:45.774841Z",
  "updateTime":"2019-03-06T21:27:01.650183Z",
  "lastRunTime":"1970-01-01T00:00:00Z",
  "status":"HEALTHY"
}

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

זמן האחזור של המשימה

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

כדי לצמצם את זמן האחזור של המשימה, אתם יכולים לנסות את הפעולות הבאות:

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

    • PERSON_NAME
    • FEMALE_NAME
    • MALE_NAME
    • FIRST_NAME
    • LAST_NAME
    • DATE_OF_BIRTH
    • LOCATION
    • STREET_ADDRESS
    • ORGANIZATION_NAME
  • תמיד צריך לציין במפורש את סוגי המידע. אל תשתמשו ברשימה ריקה של infoTypes.

  • אם אפשר, השתמשו באזור עיבוד אחר.

אם אתם עדיין נתקלים בבעיות של זמן אחזור במשימות אחרי שניסיתם את השיטות האלה, כדאי להשתמש בבקשות content.inspect או content.deidentify במקום במשימות. השיטות האלה נכללות בהסכם רמת השירות. מידע נוסף זמין במאמר הסכם רמת השירות (SLA) של Sensitive Data Protection.

הגבלת הסריקות לתוכן חדש בלבד

אתם יכולים להגדיר את הטריגר של המשימה כך שיגדיר באופן אוטומטי את טווח הזמן של קבצים שמאוחסנים ב-Cloud Storage או ב-BigQuery. כשמגדירים את האובייקט TimespanConfig למילוי אוטומטי, Sensitive Data Protection סורק רק נתונים שנוספו או שונו מאז שהטריגר הופעל בפעם האחרונה:

...
  timespan_config {
        enable_auto_population_of_timespan_config: true
      }
...

בבדיקה של BigQuery, רק שורות שנוצרו לפני שלוש שעות לפחות נכללות בסריקה. בעיה ידועה שקשורה לפעולה הזו.

הפעלת משימות בזמן העלאת קבצים

בנוסף לתמיכה בטריגרים של משימות, שמובנית ב-Sensitive Data Protection, ב-Google Cloud יש גם מגוון רכיבים אחרים שאפשר להשתמש בהם כדי לשלב או להפעיל משימות של Sensitive Data Protection. לדוגמה, אתם יכולים להשתמש בפונקציות Cloud Run כדי להפעיל סריקה של Sensitive Data Protection בכל פעם שקובץ מועלה ל-Cloud Storage.

במאמר סיווג אוטומטי של נתונים שהועלו ל-Cloud Storage מוסבר איך להגדיר את הפעולה הזו.

משימות שהסתיימו בהצלחה בלי לבדוק נתונים

משימה יכולה להסתיים בהצלחה גם אם לא נסרקו נתונים. הנה כמה דוגמאות לתרחישים שבהם זה יכול לקרות:

  • המשימה מוגדרת לבדוק נכס נתונים ספציפי, כמו קובץ, שקיים אבל ריק.
  • המשימה מוגדרת לבדוק נכס נתונים שלא קיים או שכבר לא קיים.
  • המשימה מוגדרת לבדוק קטגוריה ריקה של Cloud Storage.
  • המשימה מוגדרת לבדיקת קטגוריה, והסריקה הרקורסיבית מושבתת. ברמה העליונה, הקטגוריה מכילה רק תיקיות, והן מכילות את הקבצים.
  • המשימה מוגדרת לבדוק רק סוג קובץ ספציפי בקטגוריה, אבל אין בקטגוריה קבצים מהסוג הזה.
  • המשימה מוגדרת לבדיקה של תוכן חדש בלבד, אבל לא היו עדכונים אחרי הפעם האחרונה שהמשימה הופעלה.

במסוף Google Cloud , בשדה Bytes scanned בדף Job details, מצוינת כמות הנתונים שנבדקו על ידי המשימה. ב-DLP API, השדה processedBytes מציין את כמות הנתונים שנבדקו.

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