Creating Sensitive Data Protection inspection templates

This topic describes in detail how to create a new inspection template. For aquick walkthrough of how to create a new inspection template using theGoogle Cloud console, seeQuickstart: Creating a Sensitive Data Protectioninspection template.

About templates

You can usetemplates to create and persist configuration information to usewith Sensitive Data Protection. Templates are useful for decoupling configurationinformation—such as what you inspect for and how you de-identifyit—from the implementation of your requests. Templates provide a way tore-use configuration and enable consistency across users and datasets. Inaddition, whenever you update a template, it's updated for any job triggerthat uses it.

Sensitive Data Protection supports inspection templates, which are discussed inthis topic, and de-identification templates, which are discussed inCreating Sensitive Data Protection de-identificationtemplates.

For conceptual information about templates in Sensitive Data Protection, seeTemplates.

Create a new inspection template

Important: The code on this page requires that you first set up a Sensitive Data Protection client. For more information about installing and creating a Sensitive Data Protection client, seeSensitive Data Protection client libraries. (Sending JSON to Sensitive Data Protection REST endpoints does not require a client library.)

Console

In the Google Cloud console, go to theCreate template page.

Go to Create template

TheCreate template page contains the following sections:

Define template

UnderDefine template, enter an identifier for the inspection template. Thisis how you'll refer to the template when you run a job, create a job trigger,and so on. You can use letters, numbers, and hyphens. If you want, you can alsoenter a more human-friendly display name, as well as a description to betterremember what the template does.

In theResource location field, select the region where the data to beinspected is stored. The inspection template you create is also stored inthis region. If you want to be able to use the new inspection template in anyregion, selectGlobal (any region).

Configure detection

Next, you configure what Sensitive Data Protection detects in your content bychoosing an infoType and other options.

InfoType detectors find sensitive data of a certain type. For example, theSensitive Data ProtectionUS_SOCIAL_SECURITY_NUMBER infoType detector findsUS Social Security numbers. In addition to the built-in infoType detectors, youcan create your own custom infoType detectors.

In theInfoTypes section, choose the infoType detector that corresponds to a datatype you want to scan for. We don't recommend leaving this section blank. Doingso causes Sensitive Data Protection to scan your data with a default set ofinfoTypes, which might include infoTypes that you don't need.More information about each detector is provided inInfoType detector reference.

For more information about how to manage built-in and custom infoTypes inthis section, seeManage infoTypes through the Google Cloud console.

Inspection rulesets

Inspection rulesets allow you to customize both built-in and custom infoType detectors using context rules. The two types of inspection rules are:

To add a new ruleset, first specify one or more built-in or custom infoType detectors in theInfoTypes section. These are the infoType detectors that your rulesets will be modifying. Then, do the following:

  1. Click in theChoose infoTypes field. The infoType or infoTypes you specified previously appear below the field in a menu.
  2. Choose an infoType from the menu, and then clickAdd rule. A menu appears with the two optionsHotword rule andExclusion rule.

For hotword rules, chooseHotword rules. Then, do the following:

  1. In theHotword field, enter a regular expression that Sensitive Data Protection should look for.
  2. From theHotword proximity menu, choose whether the hotword you entered is found before or after the chosen infoType.
  3. InHotword distance from infoType, enter the approximate number of characters between the hotword and the chosen infoType.
  4. InConfidence level adjustment, choose whether to assign matches a fixedlikelihood level, or to increase or decrease the default likelihood level by a certain amount.

For exclusion rules, chooseExclusion rules. Then, do the following:

  1. In theExclude field, enter a regular expression (regex) that Sensitive Data Protection should look for.
  2. From theMatching type menu, choose one of the following:
    • Full match: The finding must completely match the regex.
    • Partial match: A substring of the finding can match the regex.
    • Inverse match: The finding doesn't match the regex.

You can add additional hotword or exclusion rules and rulesets to further refine your scan results.

Confidence threshold

Every time Sensitive Data Protection detects a potential match for sensitive data,it assigns it alikelihood value on a scale from "Very unlikely"to "Very likely." When you set a likelihood value here, you are instructingSensitive Data Protection to only match on data that corresponds to that likelihoodvalue or higher.

The default value of "Possible" is sufficient for most purposes. If youroutinely get matches that are too broad, move the slider up. If you gettoo few matches, move the slider down.

When you're done, clickCreate to create the template. The template'ssummary information page appears.

To return to the main Sensitive Data Protection page, click theBack arrow inthe Google Cloud console.

C#

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

usingGoogle.Api.Gax.ResourceNames;usingGoogle.Cloud.Dlp.V2;usingSystem;publicclassInspectTemplateCreate{publicstaticInspectTemplateCreate(stringprojectId,stringtemplateId,stringdisplayName,stringdescription,Likelihoodlikelihood,intmaxFindings,boolincludeQuote){varclient=DlpServiceClient.Create();varrequest=newCreateInspectTemplateRequest{Parent=newLocationName(projectId,"global").ToString(),InspectTemplate=newInspectTemplate{DisplayName=displayName,Description=description,InspectConfig=newInspectConfig{MinLikelihood=likelihood,Limits=newInspectConfig.Types.FindingLimits{MaxFindingsPerRequest=maxFindings},IncludeQuote=includeQuote},},TemplateId=templateId};varresponse=client.CreateInspectTemplate(request);Console.WriteLine($"Successfully created template {response.Name}.");returnresponse;}}

Go

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

import("context""fmt""io"dlp"cloud.google.com/go/dlp/apiv2""cloud.google.com/go/dlp/apiv2/dlppb")// createInspectTemplate creates a template with the given configuration.funccreateInspectTemplate(wio.Writer,projectIDstring,templateID,displayName,descriptionstring,infoTypeNames[]string)error{// projectID := "my-project-id"// templateID := "my-template"// displayName := "My Template"// description := "My template description"// infoTypeNames := []string{"US_SOCIAL_SECURITY_NUMBER"}ctx:=context.Background()client,err:=dlp.NewClient(ctx)iferr!=nil{returnfmt.Errorf("dlp.NewClient: %w",err)}deferclient.Close()// Convert the info type strings to a list of InfoTypes.varinfoTypes[]*dlppb.InfoTypefor_,it:=rangeinfoTypeNames{infoTypes=append(infoTypes,&dlppb.InfoType{Name:it})}// Create a configured request.req:=&dlppb.CreateInspectTemplateRequest{Parent:fmt.Sprintf("projects/%s/locations/global",projectID),TemplateId:templateID,InspectTemplate:&dlppb.InspectTemplate{DisplayName:displayName,Description:description,InspectConfig:&dlppb.InspectConfig{InfoTypes:infoTypes,MinLikelihood:dlppb.Likelihood_POSSIBLE,Limits:&dlppb.InspectConfig_FindingLimits{MaxFindingsPerRequest:10,},},},}// Send the request.resp,err:=client.CreateInspectTemplate(ctx,req)iferr!=nil{returnfmt.Errorf("CreateInspectTemplate: %w",err)}// Print the result.fmt.Fprintf(w,"Successfully created inspect template: %v",resp.GetName())returnnil}

Java

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

importcom.google.cloud.dlp.v2.DlpServiceClient;importcom.google.privacy.dlp.v2.CreateInspectTemplateRequest;importcom.google.privacy.dlp.v2.InfoType;importcom.google.privacy.dlp.v2.InspectConfig;importcom.google.privacy.dlp.v2.InspectTemplate;importcom.google.privacy.dlp.v2.LocationName;importjava.io.IOException;importjava.util.List;importjava.util.stream.Collectors;importjava.util.stream.Stream;classTemplatesCreate{publicstaticvoidmain(String[]args)throwsException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";createInspectTemplate(projectId);}// Creates a template to persist configuration informationpublicstaticvoidcreateInspectTemplate(StringprojectId)throwsIOException{// 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(DlpServiceClientdlpServiceClient=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 typesList<InfoType>infoTypes=Stream.of("PHONE_NUMBER","EMAIL_ADDRESS","CREDIT_CARD_NUMBER").map(it->InfoType.newBuilder().setName(it).build()).collect(Collectors.toList());// Construct the inspection configuration for the templateInspectConfiginspectConfig=InspectConfig.newBuilder().addAllInfoTypes(infoTypes).build();// Optionally set a display name and a description for the templateStringdisplayName="Inspection Config Template";Stringdescription="Save configuration for future inspection jobs";// Build the templateInspectTemplateinspectTemplate=InspectTemplate.newBuilder().setInspectConfig(inspectConfig).setDisplayName(displayName).setDescription(description).build();// Create the request to be sent by the clientCreateInspectTemplateRequestcreateInspectTemplateRequest=CreateInspectTemplateRequest.newBuilder().setParent(LocationName.of(projectId,"global").toString()).setInspectTemplate(inspectTemplate).build();// Send the request to the API and process the responseInspectTemplateresponse=dlpServiceClient.createInspectTemplate(createInspectTemplateRequest);System.out.printf("Template created: %s",response.getName());}}}

Node.js

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

// Imports the Google Cloud Data Loss Prevention libraryconstDLP=require('@google-cloud/dlp');// Instantiates a clientconstdlp=newDLP.DlpServiceClient();// The project ID to run the API call under// const projectId = 'my-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';asyncfunctioncreateInspectTemplate(){// Construct the inspection configuration for the templateconstinspectConfig={infoTypes:infoTypes,minLikelihood:minLikelihood,includeQuote:includeQuote,limits:{maxFindingsPerRequest:maxFindings,},};// Construct template-creation requestconstrequest={parent:`projects/${projectId}/locations/global`,inspectTemplate:{inspectConfig:inspectConfig,displayName:displayName,},templateId:templateId,};const[response]=awaitdlp.createInspectTemplate(request);consttemplateName=response.name;console.log(`Successfully created template${templateName}.`);}createInspectTemplate();

PHP

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;use Google\Cloud\Dlp\V2\CreateInspectTemplateRequest;use Google\Cloud\Dlp\V2\InfoType;use Google\Cloud\Dlp\V2\InspectConfig;use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;use Google\Cloud\Dlp\V2\InspectTemplate;use Google\Cloud\Dlp\V2\Likelihood;/** * Create a new DLP inspection configuration template. * * @param string $callingProjectId project ID to run the API call under * @param string $templateId       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(    string $callingProjectId,    string $templateId,    string $displayName = '',    string $description = '',    int $maxFindings = 0): void {    // 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 = "projects/$callingProjectId/locations/global";    $createInspectTemplateRequest = (new CreateInspectTemplateRequest())        ->setParent($parent)        ->setInspectTemplate($inspectTemplate)        ->setTemplateId($templateId);    $template = $dlp->createInspectTemplate($createInspectTemplateRequest);    // Print results    printf('Successfully created template %s' . PHP_EOL, $template->getName());}

Python

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

fromtypingimportListfromtypingimportOptionalimportgoogle.cloud.dlpdefcreate_inspect_template(project:str,info_types:List[str],template_id:Optional[str]=None,display_name:Optional[str]=None,min_likelihood:Optional[int]=None,max_findings:Optional[int]=None,include_quote:Optional[bool]=None,)->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.    """# 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}forinfo_typeininfo_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=f"projects/{project}"# Call the API.response=dlp.create_inspect_template(request={"parent":parent,"inspect_template":inspect_template,"template_id":template_id,})print(f"Successfully created template{response.name}")

REST

An inspection template is a reusable inspection configuration plus somemetadata. In API terms, theInspectTemplateobject is effectively anInspectConfigobject that includes a few more fields of metadata, such as a display name anda description. Therefore, to create a new inspection template, the basic stepsare:

  1. Start with anInspectConfig object.
  2. Call or POST thecreate method of either theprojects.inspectTemplates ororganizations.inspectTemplates resource, including in your request anInspectTemplate object that contains a display name, a description, and thatInspectConfig object.

The returnedInspectTemplate will be ready for use immediately. You canreference it in other calls or jobs by itsname. You can list the existingtemplates by calling the*.inspectTemplates.list method. To view a specifictemplate, call the*.inspectTemplates.get method. Note that the limit for thenumber of templates you can create is 1000.

If you've already had some experience inspecting text, images, or structuredcontent for sensitive content using Sensitive Data Protection, you've alreadycreated anInspectConfigobject. One additional step turns it into anInspectTemplateobject.

The following JSON is an example of what you can send to theprojects.inspectTemplates.createmethod. This JSON creates a new template with the given display name anddescription, and scans for matches on the infoTypesPHONE_NUMBER andUS_TOLLFREE_PHONE_NUMBER. It will include in its findings up to 100 matcheswhose likelihoods are at leastPOSSIBLE, and will include a snippet ofcontext for each.

JSON input:

POSThttps://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 output:

The response JSON looks like the following:

{"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}}
Note: This template was created at the project level, but you could also createit at the organization level using theorganizations.inspectTemplates.createmethod.

To quickly try this out, you can use the APIs Explorer that's embedded below.For general information about using JSON to send requests to theDLP API, see theJSON quickstart.

Use inspection templates

After you create a new inspection template, you can use it when creating a newinspection job or job trigger. Whenever you update that template, it'supdated in any job trigger that uses it. For more information, including codesamples, see:

Console

To get started quickly using your new template, follow the instructionsprovided inQuickstart creating a Sensitive Data Protection inspectiontemplate with the following change:

  • In theConfigure detection >Templates section, click in theTemplate name field and select the template you just created.

For a more in-depth walkthrough of how to scan your content, seeCreating andscheduling Sensitive Data Protection inspection jobs,paying particular attention to the "Configuredetection" section.

REST

You can use the template identifier you specified when creating the templateanywhereinspectTemplateName is accepted, such as:

  • projects.content.inspect:Finds potentially sensitive data in content using the template as itsconfiguration.
  • projects.content.deidentify:Finds and de-identifies potentially sensitive data in content using thetemplate as its configuration. Be aware that this method uses both aninspection template and a de-identification template.
  • projects.dlpJobs.create,in theInspectJobConfigobject: Creates an inspection job that includes the template as itsconfiguration.

List inspection templates

To list all inspection templates that have been created in the current projector organization:

Console

Note: There is currently no way to view organization-level templates in theconsole.
  1. In the Google Cloud console, go to theConfiguration page of Sensitive Data Protection.

    Go to Configuration

  2. Select the project that contains the inspection templates.

  3. Click theTemplates tab.

The console displays a list of all inspection templates for the current project.

C#

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

usingGoogle.Api.Gax.ResourceNames;usingGoogle.Cloud.Dlp.V2;usingSystem;usingGoogle.Api.Gax;publicclassInspectTemplateList{publicstaticPagedEnumerable<ListInspectTemplatesResponse,InspectTemplate>List(stringprojectId){varclient=DlpServiceClient.Create();varresponse=client.ListInspectTemplates(newListInspectTemplatesRequest{Parent=newLocationName(projectId,"global").ToString(),});// Uncomment to list templates//PrintTemplates(response);returnresponse;}publicstaticvoidPrintTemplates(PagedEnumerable<ListInspectTemplatesResponse,InspectTemplate>response){foreach(vartemplateinresponse){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}");}}}

Go

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

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")// listInspectTemplates lists the inspect templates in the project.funclistInspectTemplates(wio.Writer,projectIDstring)error{// projectID := "my-project-id"ctx:=context.Background()client,err:=dlp.NewClient(ctx)iferr!=nil{returnfmt.Errorf("dlp.NewClient: %w",err)}deferclient.Close()// Create a configured request.req:=&dlppb.ListInspectTemplatesRequest{Parent:fmt.Sprintf("projects/%s/locations/global",projectID),}// Send the request and iterate over the results.it:=client.ListInspectTemplates(ctx,req)for{t,err:=it.Next()iferr==iterator.Done{break}iferr!=nil{returnfmt.Errorf("Next: %w",err)}fmt.Fprintf(w,"Inspect template %v\n",t.GetName())c,err:=ptypes.Timestamp(t.GetCreateTime())iferr!=nil{returnfmt.Errorf("CreateTime Timestamp: %w",err)}fmt.Fprintf(w,"  Created: %v\n",c.Format(time.RFC1123))u,err:=ptypes.Timestamp(t.GetUpdateTime())iferr!=nil{returnfmt.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())}returnnil}

Java

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

importcom.google.cloud.dlp.v2.DlpServiceClient;importcom.google.cloud.dlp.v2.DlpServiceClient.ListInspectTemplatesPagedResponse;importcom.google.privacy.dlp.v2.InfoType;importcom.google.privacy.dlp.v2.InspectConfig;importcom.google.privacy.dlp.v2.InspectTemplate;importcom.google.privacy.dlp.v2.ListInspectTemplatesRequest;importcom.google.privacy.dlp.v2.LocationName;importjava.io.IOException;classTemplatesList{publicstaticvoidmain(String[]args)throwsException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";listInspectTemplates(projectId);}// Lists all templates associated with a given projectpublicstaticvoidlistInspectTemplates(StringprojectId)throwsIOException{// 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(DlpServiceClientdlpServiceClient=DlpServiceClient.create()){// Create the request to be sent by the clientListInspectTemplatesRequestrequest=ListInspectTemplatesRequest.newBuilder().setParent(LocationName.of(projectId,"global").toString()).setPageSize(1).build();// Send the requestListInspectTemplatesPagedResponseresponse=dlpServiceClient.listInspectTemplates(request);// Parse through and process the responseSystem.out.println("Templates found:");for(InspectTemplatetemplate:response.getPage().getResponse().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 configInspectConfiginspectConfig=template.getInspectConfig();for(InfoTypeinfoType: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());}}}}}

Node.js

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

// Imports the Google Cloud Data Loss Prevention libraryconstDLP=require('@google-cloud/dlp');// Instantiates a clientconstdlp=newDLP.DlpServiceClient();// The project ID to run the API call under// const projectId = 'my-project';// Helper function to pretty-print datesconstformatDate=date=>{constmsSinceEpoch=parseInt(date.seconds,10)*1000;returnnewDate(msSinceEpoch).toLocaleString('en-US');};asyncfunctionlistInspectTemplates(){// Construct template-listing requestconstrequest={parent:`projects/${projectId}/locations/global`,};// Run template-deletion requestconst[templates]=awaitdlp.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)}`);constinspectConfig=template.inspectConfig;constinfoTypes=inspectConfig.infoTypes.map(x=>x.name);console.log('  InfoTypes:',infoTypes.join(' '));console.log('  Minimum likelihood:',inspectConfig.minLikelihood);console.log('  Include quotes:',inspectConfig.includeQuote);constlimits=inspectConfig.limits;console.log('  Max findings per request:',limits.maxFindingsPerRequest);});}listInspectTemplates();

PHP

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;use Google\Cloud\Dlp\V2\ListInspectTemplatesRequest;/** * List DLP inspection configuration templates. * * @param string $callingProjectId  The project ID to run the API call under */function list_inspect_templates(string $callingProjectId): void{    // Instantiate a client.    $dlp = new DlpServiceClient();    $parent = "projects/$callingProjectId/locations/global";    // Run request    $listInspectTemplatesRequest = (new ListInspectTemplatesRequest())        ->setParent($parent);    $response = $dlp->listInspectTemplates($listInspectTemplatesRequest);    // 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());        }    }}

Python

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

importgoogle.cloud.dlpdeflist_inspect_templates(project:str)->None:"""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.    """# 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_inspect_templates(request={"parent":parent})fortemplateinresponse:print(f"Template{template.name}:")iftemplate.display_name:print(f"  Display Name:{template.display_name}")print(f"  Created:{template.create_time}")print(f"  Updated:{template.update_time}")config=template.inspect_configprint("  InfoTypes:{}".format(", ".join([it.nameforitinconfig.info_types])))print(f"  Minimum likelihood:{config.min_likelihood}")print(f"  Include quotes:{config.include_quote}")print("  Max findings per request:{}".format(config.limits.max_findings_per_request))

REST

Use one of the*.*.list methods:

Copy an inspection template to theglobal region

  1. In the Google Cloud console, go to the Sensitive Data ProtectionConfiguration page.

    Go to Configuration

  2. On the toolbar, click the project selector and select the project thatcontains the inspection template that you want to use.

  3. Click theTemplates tab, and then click theInspect subtab.

  4. Click the ID of the template that you want to use.

  5. On theInspection template details page, clickCopy.

  6. On theCreate template page, in theResource location list, selectGlobal (any region).

  7. ClickCreate.

The template is copied to theglobal region.

Copy an inspection template to another project

  1. In the Google Cloud console, go to the Sensitive Data ProtectionConfiguration page.

    Go to Configuration

  2. On the toolbar, click the project selector and select the project thatcontains the inspection template that you want to use.

  3. Click theTemplates tab, and then click theInspect subtab.

  4. Click the ID of the template that you want to use.

  5. On theInspection template details page, clickCopy.

  6. Select the project that youwant to copy the inspection template to.

    TheCreate template page reloads in the project that you selected.

  7. ClickCreate.

The template is created in the project that you selected.

Delete inspection templates

To delete an inspection template:

Console

  1. In the Google Cloud console, go to theConfiguration page of Sensitive Data Protection.

    Go to Configuration

  2. Select the project that contains the inspection template that you want to delete.

  3. Click theTemplates tab. The console displays a list of all templates for the current project.

  4. In theActions column for the template you want to delete, click themore actions menu (displayed as three dots arranged vertically), and then clickDelete.

Alternatively, from the list of templates, click the name of the template youwant to delete. On the template's detail page, clickDelete.

C#

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

usingGoogle.Cloud.Dlp.V2;usingSystem;publicclassInspectTemplateDelete{publicstaticobjectDelete(stringprojectId,stringtemplateName){varclient=DlpServiceClient.Create();varrequest=newDeleteInspectTemplateRequest{Name=templateName};client.DeleteInspectTemplate(request);Console.WriteLine($"Successfully deleted template {templateName}.");returntemplateName;}}

Go

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

import("context""fmt""io"dlp"cloud.google.com/go/dlp/apiv2""cloud.google.com/go/dlp/apiv2/dlppb")// deleteInspectTemplate deletes the given template.funcdeleteInspectTemplate(wio.Writer,templateIDstring)error{// projectID := "my-project-id"// templateID := "my-template"ctx:=context.Background()client,err:=dlp.NewClient(ctx)iferr!=nil{returnfmt.Errorf("dlp.NewClient: %w",err)}deferclient.Close()req:=&dlppb.DeleteInspectTemplateRequest{Name:templateID,}iferr:=client.DeleteInspectTemplate(ctx,req);err!=nil{returnfmt.Errorf("DeleteInspectTemplate: %w",err)}fmt.Fprintf(w,"Successfully deleted inspect template %v",templateID)returnnil}

Java

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

importcom.google.cloud.dlp.v2.DlpServiceClient;importcom.google.privacy.dlp.v2.DeleteInspectTemplateRequest;importjava.io.IOException;classTemplatesDelete{publicstaticvoidmain(String[]args)throwsException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringtemplateId="your-template-id";deleteInspectTemplate(projectId,templateId);}// Delete an existing templatepublicstaticvoiddeleteInspectTemplate(StringprojectId,StringtemplateId)throwsIOException{// Construct the template name to be deletedStringtemplateName=String.format("projects/%s/inspectTemplates/%s",projectId,templateId);// 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(DlpServiceClientdlpServiceClient=DlpServiceClient.create()){// Create delete template request to be sent by the clientDeleteInspectTemplateRequestrequest=DeleteInspectTemplateRequest.newBuilder().setName(templateName).build();// Send the request with the clientdlpServiceClient.deleteInspectTemplate(request);System.out.printf("Deleted template: %s\n",templateName);}}}

Node.js

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

// Imports the Google Cloud Data Loss Prevention libraryconstDLP=require('@google-cloud/dlp');// Instantiates a clientconstdlp=newDLP.DlpServiceClient();// The project ID to run the API call under// const projectId = 'my-project';// The name of the template to delete// Parent project ID is automatically extracted from this parameter// const templateName = 'projects/YOUR_PROJECT_ID/inspectTemplates/#####'asyncfunctiondeleteInspectTemplate(){// Construct template-deletion requestconstrequest={name:templateName,};// Run template-deletion requestawaitdlp.deleteInspectTemplate(request);console.log(`Successfully deleted template${templateName}.`);}deleteInspectTemplate();

PHP

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;use Google\Cloud\Dlp\V2\DeleteInspectTemplateRequest;/** * Delete a 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 delete */function delete_inspect_template(    string $callingProjectId,    string $templateId): void {    // Instantiate a client.    $dlp = new DlpServiceClient();    // Run template deletion request    $templateName = "projects/$callingProjectId/locations/global/inspectTemplates/$templateId";    $deleteInspectTemplateRequest = (new DeleteInspectTemplateRequest())        ->setName($templateName);    $dlp->deleteInspectTemplate($deleteInspectTemplateRequest);    // Print results    printf('Successfully deleted template %s' . PHP_EOL, $templateName);}

Python

To learn how to install and use the client library for Sensitive Data Protection, seeSensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

importgoogle.cloud.dlpdefdelete_inspect_template(project:str,template_id:str)->None:"""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.    """# Instantiate a client.dlp=google.cloud.dlp_v2.DlpServiceClient()# Convert the project id into a full resource id.parent=f"projects/{project}"# Combine the template id with the parent id.template_resource=f"{parent}/inspectTemplates/{template_id}"# Call the API.dlp.delete_inspect_template(request={"name":template_resource})print(f"Template{template_resource} successfully deleted.")

REST

Use one of the*.*.delete methods:

With each*.*.delete method, you include the resource name of the template tobe deleted.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.