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

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

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

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

כדי לתזמן משימות סריקה של בדיקות 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 כולל את הקטעים הבאים:

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

שם

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

מיקום

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

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

דגימות

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

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

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

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

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

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

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

הגדרה מתקדמת

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

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

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

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

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

אפשר לבחור מבין קבצים בינאריים, קובצי טקסט, קובצי תמונה, קובצי 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, צריך גם להפעיל את הפעולה שמירה ב-BigQuery. כשמייצאים את הממצאים ל-BigQuery, כל ממצא מכיל את הערכים המתאימים של השדות המזהים. מידע נוסף זמין במאמר identifyingFields.

הגדרת זיהוי

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

תבנית

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

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

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

InfoTypes

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

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

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

ערכות כללים לבדיקה

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

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

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

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

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

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

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

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

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

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

סף ביטחון

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

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

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

הוספת פעולות

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

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

בדיקה

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

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

כדי לחזור לדף הראשי של Sensitive Data Protection, לוחצים על החץ חזרה במסוף 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. אפשר ליצור משימה חדשה באמצעות המשאב DlpJob והשיטה projects.dlpJobs.create.

אפשר לשלוח את ה-JSON לדוגמה הזה בבקשת POST לנקודת הקצה שצוינה של 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 כולל את הקטעים הבאים:

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

שם

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

מיקום

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

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

דגימות

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

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

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

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

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

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

הגדרה מתקדמת

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

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

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

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

קבצים

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

אפשר לבחור בין קבצים בינאריים, קובצי טקסט, קובצי תמונה, קובצי 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, צריך גם להפעיל את הפעולה שמירה ב-BigQuery. כשמייצאים את הממצאים ל-BigQuery, כל ממצא מכיל את הערכים המתאימים של השדות המזהים. מידע נוסף זמין במאמר identifyingFields.

הגדרת זיהוי

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

תבנית

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

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

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

InfoTypes

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

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

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

סוגי מידע בהתאמה אישית

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

ערכות כללים לבדיקה

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

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

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

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

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

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

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

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

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

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

סף ביטחון

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

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

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

הוספת פעולות

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

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

לוח זמנים

בקטע Schedule (תזמון), אפשר לבצע שתי פעולות:

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

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

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

בדיקה

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

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

כדי לחזור לדף הראשי של Sensitive Data Protection, לוחצים על החץ חזרה במסוף 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 מיוצג ב-DLP API על ידי המשאב JobTrigger. אפשר ליצור טריגר חדש של משימה באמצעות method projects.jobTriggers.create של המשאב JobTrigger.

אפשר לשלוח את ה-JSON לדוגמה הזה בבקשת POST לנקודת הקצה שצוינה של 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. לוחצים על הכרטיסייה בדיקה ואז על כרטיסיית המשנה בדיקת משימות.

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

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

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

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.

מחיקת משימה

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

המסוף

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

    מעבר אל Sensitive Data Protection

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

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

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

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. בעמודה פעולות של טריגר העבודה שרוצים למחוק, לוחצים על תפריט הפעולות הנוספות (שמוצג כ-3 נקודות אנכיות) ואז על מחיקה.

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

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 לנקודת הקצה 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 לנקודת הקצה 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'

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

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

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

המסוף

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

    מעבר אל Sensitive Data Protection

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

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

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

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

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

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

משתמשים בשיטה 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 ושל הסבירות הוחלפו בערכים החדשים.

פלט 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 מציין כמה נתונים נבדקו.

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