建立 Cloud DLP 檢查範本

本主題將詳細說明如何建立新的檢查範本。如需使用 Cloud DLP UI 建立新檢查範本的快速逐步操作說明,請參閱建立 Cloud DLP 檢查範本的快速入門導覽課程

關於範本

您可以使用「範本」建立及保留設定資訊,以便與 Cloud Data Loss Prevention (DLP) 搭配使用。範本很適合用於將檢查內容和去識別化方式等設定資訊與要求的實作分離,範本不僅可以讓您重複使用設定,也能保持使用者和資料集之間的一致性。

Cloud DLP 可支援本主題中討論到的檢查範本,也可支援建立 Cloud DLP 去識別化範本一文中討論的去識別化範本。

如要瞭解 Cloud DLP 範本的概念資訊,請參閱範本一文。

建立新的檢查範本

建立新的 Cloud DLP 範本:

主控台

  1. 在 GCP 主控台中,開啟 Cloud DLP。

    前往 Cloud DLP UI Beta 版

  2. 在 [Create] (建立) 選單中,選擇 [Template] (範本)

    已選取 [Create] (建立) 選單 > [Templates] (範本) 的 DLP UI 螢幕擷圖。

    也可以按一下以下按鈕:

    建立新範本

「建立範本」頁面包含下列區段:

  1. 命名
  2. InfoTypes
  3. 可信度門檻

命名

請在 [Naming] (命名) 下方,輸入檢查範本的 ID。在執行工作、建立工作觸發條件等作業時,就是以 ID 來引用範本。您可以使用英文字母、數字和連字號。如果有需要,也可以輸入一段說明,方便記住範本的功能。

InfoTypes

接下來,請選擇用來掃描內容的內建 infoType。

InfoType 偵測工具可尋找特定類型的機密資料。例如,Cloud DLP US_SOCIAL_SECURITY_NUMBER infoType 偵測工具可尋找美國社會安全號碼。

「Create」(建立) 範本中 DLP UI 的 InfoTypes 區段螢幕截圖。

在「InfoType」下,選擇與您要掃描之資料類型對應的 infoType 偵測工具。您也可以將此欄位保留空白,以掃描所有預設 infoType。InfoType 偵測工具參考資料中提供每個偵測工具的詳細資訊。

可信度門檻

Cloud DLP 每次偵測到機密資料的可能相符項目時,都會為該項目指派可能性值,範圍從「非常不可能」到「非常可能」。當您在此處設定可能性值時,就是在指示 Cloud DLP 僅比對與該可能性值或更高值對應的資料。

「Create」(建立) 範本中 DLP UI 的「Confidence threshold」(可信度門檻) 區段螢幕截圖。

預設值「Possible」(或許可能) 足以供大多數情況使用。如果使用此範本時,得到的相符項目範圍常常過廣,請將滑桿上移。如果得到的相符項目太少,請將滑桿下移。

完成之後,按一下 [Create] (建立) 即可建立範本。系統隨即會顯示範本的摘要資訊頁面。

DLP UI 的「Inspection template」(檢查範本) 詳細資訊畫面螢幕截圖。

如要返回 Cloud DLP 主頁面,請在 GCP 主控台中按一下「返回」箭頭。

通訊協定

請注意,檢查範本只是可重複使用的檢查設定,再加上一些中繼資料。就 API 而言,InspectTemplate 物件其實是 InspectConfig 物件,只是包括多一點的中繼資料欄位,如顯示名稱和說明。因此,建立新檢查範本的基本步驟如下:

  1. InspectConfig 物件開始。
  2. 呼叫或透過 POST 使用 projects.inspectTemplatesorganizations.inspectTemplates 資源的 create 方法,在您的要求中加入含有顯示名稱、說明和該 InspectConfig 物件的 InspectTemplate 物件。

傳回的 InspectTemplate 將立即可供使用。您可以透過範本的 name 在其他呼叫或工作中參照範本。您可以呼叫 *.inspectTemplates.list 方法列出現有的範本。如要查看特定範本,請呼叫 *.inspectTemplates.get 方法。請注意,您最多可以建立 1000 個範本。

如果您曾使用 Cloud DLP 檢查文字、圖片或結構化內容中的機密內容,表示您已經建立過 InspectConfig 物件。只要再進行一個步驟即可將這個物件轉換成 InspectTemplate 物件。

以下 JSON 是您可以傳送到 projects.inspectTemplates.create 方法的內容範例 (請在 APIs Explorer 中親自操作一下)。這個 JSON 會建立一個含有指定顯示名稱和說明的新範本,然後會比對 infoTypes PHONE_NUMBERUS_TOLLFREE_PHONE_NUMBER 掃描相符項目。其發現項目中最多會包含 100 個相符項目,這些項目的可能性至少為 POSSIBLE,而且會包含每個項目的文字片段內容。

JSON 輸入:

POST https://dlp.googleapis.com/v2/projects/[PROJECT_ID]/inspectTemplates?key={YOUR_API_KEY}

{
  "inspectTemplate":{
    "displayName":"Phone number inspection",
    "description":"Scans for phone numbers",
    "inspectConfig":{
      "infoTypes":[
        {
          "name":"PHONE_NUMBER"
        },
        {
          "name":"US_TOLLFREE_PHONE_NUMBER"
        }
      ],
      "minLikelihood":"POSSIBLE",
      "limits":{
        "maxFindingsPerRequest":100
      },
      "includeQuote":true
    }
  }
}

JSON 輸出:

回應 JSON 會如下所示:

{
  "name":"projects/[PROJECT_ID]/inspectTemplates/[JOB_ID]",
  "displayName":"Phone number inspection",
  "description":"Scans for phone numbers",
  "createTime":"2018-11-30T07:26:28.164136Z",
  "updateTime":"2018-11-30T07:26:28.164136Z",
  "inspectConfig":{
    "infoTypes":[
      {
        "name":"PHONE_NUMBER"
      },
      {
        "name":"US_TOLLFREE_PHONE_NUMBER"
      }
    ],
    "minLikelihood":"POSSIBLE",
    "limits":{
      "maxFindingsPerRequest":100
    },
    "includeQuote":true
  }
}

Java

/**
 * Create a new DLP inspection configuration template.
 *
 * @param displayName (Optional) The human-readable name to give the template
 * @param projectId Google Cloud Project ID to call the API under
 * @param templateId (Optional) The name of the template to be created
 * @param infoTypeList The infoTypes of information to match
 * @param minLikelihood The minimum likelihood required before returning a match
 * @param maxFindings The maximum number of findings to report per request (0 = server maximum)
 */
private static void createInspectTemplate(
    String displayName,
    String templateId,
    String description,
    String projectId,
    List<InfoType> infoTypeList,
    Likelihood minLikelihood,
    int maxFindings) {
  try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

    FindingLimits findingLimits =
        FindingLimits.newBuilder().setMaxFindingsPerRequest(maxFindings).build();

    // Construct the inspection configuration for the template
    InspectConfig inspectConfig =
        InspectConfig.newBuilder()
            .addAllInfoTypes(infoTypeList)
            .setMinLikelihood(minLikelihood)
            .setLimits(findingLimits)
            .build();

    InspectTemplate inspectTemplate =
        InspectTemplate.newBuilder()
            .setInspectConfig(inspectConfig)
            .setDisplayName(displayName)
            .setDescription(description)
            .build();

    CreateInspectTemplateRequest createInspectTemplateRequest =
        CreateInspectTemplateRequest.newBuilder()
            .setParent(ProjectName.of(projectId).toString())
            .setInspectTemplate(inspectTemplate)
            .setTemplateId(templateId)
            .build();

    InspectTemplate response =
        dlpServiceClient.createInspectTemplate(createInspectTemplateRequest);
    System.out.printf("Template created: %s", response.getName());
  } catch (Exception e) {
    System.out.printf("Error creating template: %s", e.getMessage());
  }
}

Node.js

// 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 callingProjectId = process.env.GCLOUD_PROJECT;

// 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;

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

// Whether to include the matching string
// const includeQuote = true;

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

// (Optional) The human-readable name to give the template
// const displayName = 'My template';

// Construct the inspection configuration for the template
const inspectConfig = {
  infoTypes: infoTypes,
  minLikelihood: minLikelihood,
  includeQuote: includeQuote,
  limits: {
    maxFindingsPerRequest: maxFindings,
  },
};

// Construct template-creation request
const request = {
  parent: dlp.projectPath(callingProjectId),
  inspectTemplate: {
    inspectConfig: inspectConfig,
    displayName: displayName,
  },
  templateId: templateId,
};

try {
  const [response] = await dlp.createInspectTemplate(request);
  const templateName = response.name;
  console.log(`Successfully created template ${templateName}.`);
} catch (err) {
  console.log(`Error in createInspectTemplate: ${err.message || err}`);
}

Python

def create_inspect_template(project, info_types,
                            template_id=None, display_name=None,
                            min_likelihood=None, max_findings=None,
                            include_quote=None):
    """Creates a Data Loss Prevention API inspect template.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        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.
        template_id: The id of the template. If omitted, an id will be randomly
            generated.
        display_name: The optional display name of the template.
        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.
        include_quote: Boolean for whether to display a quote of the detected
            information in the results.
    Returns:
        None; the response from the API is printed to the terminal.
    """

    # Import the client library
    import google.cloud.dlp

    # Instantiate a client.
    dlp = google.cloud.dlp.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,
        'include_quote': include_quote,
        'limits': {'max_findings_per_request': max_findings},
    }

    inspect_template = {
        'inspect_config': inspect_config,
        'display_name': display_name,
    }

    # Convert the project id into a full resource id.
    parent = dlp.project_path(project)

    # Call the API.
    response = dlp.create_inspect_template(
        parent, inspect_template=inspect_template, template_id=template_id)

    print('Successfully created template {}'.format(response.name))

Go

// createInspectTemplate creates a template with the given configuration.
func createInspectTemplate(w io.Writer, client *dlp.Client, project string, minLikelihood dlppb.Likelihood, maxFindings int32, templateID, displayName, description string, infoTypes []string) {
	// Convert the info type strings to a list of InfoTypes.
	var i []*dlppb.InfoType
	for _, it := range infoTypes {
		i = append(i, &dlppb.InfoType{Name: it})
	}

	// Create a configured request.
	req := &dlppb.CreateInspectTemplateRequest{
		Parent:     "projects/" + project,
		TemplateId: templateID,
		InspectTemplate: &dlppb.InspectTemplate{
			DisplayName: displayName,
			Description: description,
			InspectConfig: &dlppb.InspectConfig{
				InfoTypes:     i,
				MinLikelihood: minLikelihood,
				Limits: &dlppb.InspectConfig_FindingLimits{
					MaxFindingsPerRequest: maxFindings,
				},
			},
		},
	}
	// Send the request.
	resp, err := client.CreateInspectTemplate(context.Background(), req)
	if err != nil {
		log.Fatalf("error creating inspect template: %v", err)
	}
	// Print the result.
	fmt.Fprintf(w, "Successfully created inspect template: %v", resp.GetName())
}

PHP

use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectTemplate;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;

/**
 * Create a new DLP inspection configuration template.
 *
 * @param string $callingProjectId The project ID to run the API call under
 * @param string $templateId The name of the template to be created
 * @param string $displayName (Optional) The human-readable name to give the template
 * @param string $description (Optional) A description for the trigger to be created
 * @param int $maxFindings (Optional) The maximum number of findings to report per request (0 = server maximum)
 */
function create_inspect_template(
    $callingProjectId,
    $templateId,
    $displayName = '',
    $description = '',
    $maxFindings = 0
) {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

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

    // Whether to include the matching string in the response
    $includeQuote = true;

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

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

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

    // Construct inspection template
    $inspectTemplate = (new InspectTemplate())
        ->setInspectConfig($inspectConfig)
        ->setDisplayName($displayName)
        ->setDescription($description);

    // Run request
    $parent = $dlp->projectName($callingProjectId);
    $dlp->createInspectTemplate($parent, [
        'inspectTemplate' => $inspectTemplate,
        'templateId' => $templateId
    ]);

    // Print results
    printf(
        'Successfully created template projects/%s/inspectTemplates/%s' . PHP_EOL,
        $callingProjectId,
        $templateId
    );
}

C#

public static string CreateInspectTemplate(
    string projectId,
    string templateId,
    string displayName,
    string description,
    string likelihood,
    int maxFindings,
    bool includeQuote)
{
    DlpServiceClient client = DlpServiceClient.Create();

    var request = new CreateInspectTemplateRequest
    {
        Parent = $"projects/{projectId}",
        InspectTemplate = new InspectTemplate
        {
            DisplayName = displayName,
            Description = description,
            InspectConfig = new InspectConfig
            {
                MinLikelihood = (Likelihood)Enum.Parse(typeof(Likelihood), likelihood),
                Limits = new InspectConfig.Types.FindingLimits
                {
                    MaxFindingsPerRequest = maxFindings
                },
                IncludeQuote = includeQuote
            },
        },
        TemplateId = templateId
    };

    var response = client.CreateInspectTemplate(request);

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

    return response.Name;
}

列出檢查範本

如何列出在目前的專案或機構中已建立的所有檢查範本:

主控台

  1. 在 GCP 主控台中,開啟 Cloud DLP。

    前往 Cloud DLP UI Beta 版

  2. 按一下 [Templates] (範本) 分頁標籤。

主控台隨即會列出目前專案的所有檢查範本。

通訊協定

請使用以下其中一種 *.*.list 方法:

Java

/**
 * List DLP inspection templates created in a given project
 *
 * @param projectId Google Cloud Project ID
 */
private static void listInspectTemplates(String projectId) {

  try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

    ListInspectTemplatesRequest request =
        ListInspectTemplatesRequest.newBuilder()
            .setParent(ProjectName.of(projectId).toString())
            .setPageSize(1)
            .build();

    ListInspectTemplatesPagedResponse response = dlpServiceClient.listInspectTemplates(request);
    ListInspectTemplatesPage page = response.getPage();
    ListInspectTemplatesResponse templatesResponse = page.getResponse();

    for (InspectTemplate template : templatesResponse.getInspectTemplatesList()) {
      System.out.printf("Template name: %s\n", template.getName());
      if (template.getDisplayName() != null) {
        System.out.printf("\tDisplay name: %s \n", template.getDisplayName());
        System.out.printf("\tCreate time: %s \n", template.getCreateTime());
        System.out.printf("\tUpdate time: %s \n", template.getUpdateTime());

        // print inspection config
        InspectConfig inspectConfig = template.getInspectConfig();
        for (InfoType infoType : inspectConfig.getInfoTypesList()) {
          System.out.printf("\tInfoType: %s\n", infoType.getName());
        }
        System.out.printf("\tMin likelihood: %s\n", inspectConfig.getMinLikelihood());
        System.out.printf("\tLimits: %s\n", inspectConfig.getLimits().getMaxFindingsPerRequest());
      }
    }
  } catch (Exception e) {
    System.out.printf("Error creating template: %s", e.getMessage());
  }
}

Node.js

// 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 callingProjectId = process.env.GCLOUD_PROJECT;

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

// Construct template-listing request
const request = {
  parent: dlp.projectPath(callingProjectId),
};

try {
  // Run template-deletion request
  const [templates] = await dlp.listInspectTemplates(request);

  templates.forEach(template => {
    console.log(`Template ${template.name}`);
    if (template.displayName) {
      console.log(`  Display name: ${template.displayName}`);
    }

    console.log(`  Created: ${formatDate(template.createTime)}`);
    console.log(`  Updated: ${formatDate(template.updateTime)}`);

    const inspectConfig = template.inspectConfig;
    const infoTypes = inspectConfig.infoTypes.map(x => x.name);
    console.log(`  InfoTypes:`, infoTypes.join(' '));
    console.log(`  Minimum likelihood:`, inspectConfig.minLikelihood);
    console.log(`  Include quotes:`, inspectConfig.includeQuote);

    const limits = inspectConfig.limits;
    console.log(`  Max findings per request:`, limits.maxFindingsPerRequest);
  });
} catch (err) {
  console.log(`Error in listInspectTemplates: ${err.message || err}`);
}

Python

def list_inspect_templates(project):
    """Lists all Data Loss Prevention API inspect templates.
    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.
    """

    # Import the client library
    import google.cloud.dlp

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

    # Convert the project id into a full resource id.
    parent = dlp.project_path(project)

    # Call the API.
    response = dlp.list_inspect_templates(parent)

    # Define a helper function to convert the API's "seconds since the epoch"
    # time format into a human-readable string.
    def human_readable_time(timestamp):
        return str(time.localtime(timestamp.seconds))

    for template in response:
        print('Template {}:'.format(template.name))
        if template.display_name:
            print('  Display Name: {}'.format(template.display_name))
        print('  Created: {}'.format(
            human_readable_time(template.create_time)))
        print('  Updated: {}'.format(
            human_readable_time(template.update_time)))

        config = template.inspect_config
        print('  InfoTypes: {}'.format(', '.join(
            [it.name for it in config.info_types]
        )))
        print('  Minimum likelihood: {}'.format(config.min_likelihood))
        print('  Include quotes: {}'.format(config.include_quote))
        print('  Max findings per request: {}'.format(
            config.limits.max_findings_per_request))

Go

// listInspectTemplates lists the inspect templates in the project.
func listInspectTemplates(w io.Writer, client *dlp.Client, project string) {
	// Create a configured request.
	req := &dlppb.ListInspectTemplatesRequest{
		Parent: "projects/" + project,
	}
	// Send the request and iterate over the results.
	it := client.ListInspectTemplates(context.Background(), req)
	for {
		t, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Fatalf("error getting inspect templates: %v", err)
		}
		c := t.GetCreateTime()
		u := t.GetUpdateTime()
		fmt.Fprintf(w, "Inspect template %v\n", t.GetName())
		fmt.Fprintf(w, "  Created: %v\n", time.Unix(c.GetSeconds(), int64(c.GetNanos())).Format(time.RFC1123))
		fmt.Fprintf(w, "  Updated: %v\n", time.Unix(u.GetSeconds(), int64(u.GetNanos())).Format(time.RFC1123))
		fmt.Fprintf(w, "  Display Name: %q\n", t.GetDisplayName())
		fmt.Fprintf(w, "  Description: %q\n", t.GetDescription())
	}
}

PHP

use Google\Cloud\Dlp\V2\DlpServiceClient;

/**
 * List DLP inspection configuration templates.
 * @param string $callingProjectId The GCP Project ID to run the API call under
 */
function list_inspect_templates($callingProjectId)
{
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    $parent = $dlp->projectName($callingProjectId);

    // Run request
    $response = $dlp->listInspectTemplates($parent);

    // Print results
    $templates = $response->iterateAllElements();

    foreach ($templates as $template) {
        printf('Template %s' . PHP_EOL, $template->getName());
        printf('  Created: %s' . PHP_EOL, $template->getCreateTime()->getSeconds());
        printf('  Updated: %s' . PHP_EOL, $template->getUpdateTime()->getSeconds());
        printf('  Display Name: %s' . PHP_EOL, $template->getDisplayName());
        printf('  Description: %s' . PHP_EOL, $template->getDescription());

        $inspectConfig = $template->getInspectConfig();
        if ($inspectConfig === null) {
            print('  No inspect config.' . PHP_EOL);
        } else {
            printf('  Minimum likelihood: %s' . PHP_EOL, $inspectConfig->getMinLikelihood());
            printf('  Include quotes: %s' . PHP_EOL, $inspectConfig->getIncludeQuote());
            $limits = $inspectConfig->getLimits();
            printf('  Max findings per request: %s' . PHP_EOL, $limits->getMaxFindingsPerRequest());
        }
    }
}

C#

public static object ListInspectTemplate(string projectId)
{
    DlpServiceClient client = DlpServiceClient.Create();

    var response = client.ListInspectTemplates(
        new ListInspectTemplatesRequest
        {
            Parent = $"projects/{projectId}",
        }
    );
    foreach (var template in response)
    {
        Console.WriteLine($"Template {template.Name}:");
        Console.WriteLine($"\tDisplay Name: {template.DisplayName}");
        Console.WriteLine($"\tDescription: {template.Description}");
        Console.WriteLine($"\tCreated: {template.CreateTime}");
        Console.WriteLine($"\tUpdated: {template.UpdateTime}");
        Console.WriteLine("Configuration:");
        Console.WriteLine($"\tMin Likelihood: {template.InspectConfig?.MinLikelihood}");
        Console.WriteLine($"\tInclude quotes: {template.InspectConfig?.IncludeQuote}");
        Console.WriteLine($"\tMax findings per request: {template.InspectConfig?.Limits.MaxFindingsPerRequest}");
    }

    return null;
}

刪除檢查範本

如何刪除檢查範本:

主控台

  1. 在 GCP 主控台中,開啟 Cloud DLP。

    前往 Cloud DLP UI Beta 版

  2. 按一下 [Templates] (範本) 分頁標籤。主控台隨即會列出目前專案的所有範本。

  3. 找出您要刪除的範本,並在對應的「Actions」(動作) 欄中,按一下三個垂直圓點,然後點選 [Delete] (刪除)

    開啟「Actions」(動作) 選單的 DLP UI 範本螢幕擷圖。

您也可以在範本清單中,按一下要刪除的範本名稱。請在範本的詳細資料頁面,按一下 [Delete] (刪除)

通訊協定

請使用以下其中一種 *.*.delete 方法:

在每個 *.*.delete 方法中,請加入待刪除範本的資源名稱。

Java

/**
 * Delete the DLP inspection configuration template with the specified name.
 *
 * @param projectId Google Cloud Project ID
 * @param templateId Template ID to be deleted
 */
private static void deleteInspectTemplate(String projectId, String templateId) {

  // construct the template name to be deleted
  String templateName = String.format("projects/%s/inspectTemplates/%s", projectId, templateId);
  // instantiate the client
  try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {
    // create delete template request
    DeleteInspectTemplateRequest request =
        DeleteInspectTemplateRequest.newBuilder().setName(templateName).build();

    dlpServiceClient.deleteInspectTemplate(request);
    System.out.printf("Deleted template: %s\n", templateName);
  } catch (Exception e) {
    System.err.printf("Error deleting template: %s\n", templateName);
  }
}

Node.js

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

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

// The name of the template to delete
// Parent project ID is automatically extracted from this parameter
// const templateName = 'projects/YOUR_PROJECT_ID/inspectTemplates/#####'

// Construct template-deletion request
const request = {
  name: templateName,
};

try {
  // Run template-deletion request
  await dlp.deleteInspectTemplate(request);
  console.log(`Successfully deleted template ${templateName}.`);
} catch (err) {
  console.log(`Error in deleteInspectTemplate: ${err.message || err}`);
}

Python

def delete_inspect_template(project, template_id):
    """Deletes a Data Loss Prevention API template.
    Args:
        project: The id of the Google Cloud project which owns the template.
        template_id: The id of the template to delete.
    Returns:
        None; the response from the API is printed to the terminal.
    """

    # Import the client library
    import google.cloud.dlp

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

    # Convert the project id into a full resource id.
    parent = dlp.project_path(project)

    # Combine the template id with the parent id.
    template_resource = '{}/inspectTemplates/{}'.format(parent, template_id)

    # Call the API.
    dlp.delete_inspect_template(template_resource)

    print('Template {} successfully deleted.'.format(template_resource))

Go

// deleteInspectTemplate deletes the given template.
func deleteInspectTemplate(w io.Writer, client *dlp.Client, templateID string) {
	req := &dlppb.DeleteInspectTemplateRequest{
		Name: templateID,
	}
	err := client.DeleteInspectTemplate(context.Background(), req)
	if err != nil {
		log.Fatalf("error deleting inspect template: %v", err)
	}
	fmt.Fprintf(w, "Successfully deleted inspect template %v", templateID)
}

PHP

use Google\Cloud\Dlp\V2\DlpServiceClient;

/**
 * Delete a DLP inspection configuration template.
 *
 * @param string $templateId The name of the template to delete.
 *        Parent project ID is automatically extracted from this parameter
 */
function delete_inspect_templates($templateId)
{
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Run template deletion request
    $dlp->deleteInspectTemplate($templateId);

    // Print results
    printf('Successfully deleted template %s' . PHP_EOL, $templateId);
}

C#

public static object DeleteInspectTemplate(string projectId, string templateName)
{
    DlpServiceClient client = DlpServiceClient.Create();

    var request = new DeleteInspectTemplateRequest
    {
        Name = templateName
    };

    client.DeleteInspectTemplate(request);
    Console.WriteLine($"Successfully deleted template {templateName}.");

    return templateName;
}

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Cloud Data Loss Prevention