Creating Cloud DLP inspection templates

This topic describes in detail how to create a new inspection template. For a quick walkthrough of how to create a new inspection template using the Cloud DLP UI, see Quickstart creating a Cloud DLP inspection template.

About templates

You can use templates to create and persist configuration information to use with Cloud Data Loss Prevention (DLP). Templates are useful for decoupling configuration information—such as what you inspect for and how you de-identify it—from the implementation of your requests. Templates provide a way to re-use configuration and enable consistency across users and datasets.

Cloud DLP supports inspection templates, which are discussed in this topic, and de-identification templates, which are discussed in Creating Cloud DLP de-identification templates.

For conceptual information about templates in Cloud DLP, see Templates.

Create a new inspection template

To create a new Cloud DLP template:

Console

  1. In the GCP Console, open Cloud DLP.

    Go to Cloud DLP UI Beta

  2. From the Create menu, choose Template.

    Screenshot of DLP UI with Create menu > Templates
        selected.

    Alternatively, click the following button:

    Create new template

The Create template page contains the following sections:

  1. Naming
  2. InfoTypes
  3. Confidence threshold

Naming

Under Naming, enter an identifier for the inspection template. This is 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 also enter a description to better remember what the template does.

InfoTypes

Next, choose a built-in infoType to use to scan your content.

InfoType detectors find sensitive data of a certain type. For example, the Cloud DLP US_SOCIAL_SECURITY_NUMBER infoType detector finds US Social Security numbers.

Screenshot of the DLP UI's InfoTypes section in Create template.

Under InfoTypes, choose the infoType detector that corresponds to a data type you want to scan for. You can also leave this field blank to scan for all default infoTypes. More information about each detector is provided in InfoType detector reference.

Confidence threshold

Every time Cloud DLP detects a potential match for sensitive data, it assigns it a likelihood value on a scale from "Very unlikely" to "Very likely." When you set a likelihood value here, you are instructing Cloud DLP to only match on data that corresponds to that likelihood value or higher.

Screenshot of the DLP UI's Confidence threshold section in Create
          template.

The default value of "Possible" is sufficient for most purposes. If you routinely get matches that are too broad when you use this template, move the slider up. If you get too few matches, move the slider down.

When you're done, click Create to create the template. The template's summary information page appears.

Screenshot of the DLP UI's Inspection template details screen.

To return to the main Cloud DLP page, click the Back arrow in the GCP Console.

Protocol

It's useful to note that an inspection template is simply a reusable inspection configuration plus some metadata. In API terms, the InspectTemplate object is effectively an InspectConfig object that includes a few more fields of metadata, such as a display name and a description. Therefore, to create a new inspection template, the basic steps are:

  1. Start with an InspectConfig object.
  2. Call or POST the create method of either the projects.inspectTemplates or organizations.inspectTemplates resource, including in your request an InspectTemplate object that contains a display name, a description, and that InspectConfig object.

The returned InspectTemplate will be ready for use immediately. You can reference it in other calls or jobs by its name. You can list the existing templates by calling the *.inspectTemplates.list method. To view a specific template, call the *.inspectTemplates.get method. Note that the limit for the number of templates you can create is 1000.

If you've already had some experience inspecting text, images, or structured content for sensitive content using Cloud DLP, you've already created an InspectConfig object. One additional step turns it into an InspectTemplate object.

The following JSON is an example of what you can send to the projects.inspectTemplates.create method. (Try it for yourself in APIs Explorer.) This JSON creates a new template with the given display name and description, and scans for matches on the infoTypes PHONE_NUMBER and US_TOLLFREE_PHONE_NUMBER. It will include in its findings up to 100 matches whose likelihoods are at least POSSIBLE, and will include a snippet of context for each.

JSON Input:

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 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
  }
}

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

/**
 * Create a new DLP inspection configuration template.
 */
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;

/** Uncomment and populate these variables in your code */
// $callingProjectId = 'The project ID to run the API call under';
// $templateId = 'The name of the template to be created';
// $displayName = ''; // (Optional) The human-readable name to give the template
// $description = ''; // (Optional) A description for the trigger to be created
// $maxFindings = 0;  // (Optional) The maximum number of findings to report per request (0 = server maximum)

// 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);
$template = $dlp->createInspectTemplate($parent, [
    'inspectTemplate' => $inspectTemplate,
    'templateId' => $templateId
]);

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

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

Listing inspection templates

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

Console

  1. In the GCP Console, open Cloud DLP.

    Go to Cloud DLP UI Beta

  2. Click the Templates tab.

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

Protocol

Use one of the *.*.list methods:

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

/**
 * List DLP inspection configuration templates.
 */
use Google\Cloud\Dlp\V2\DlpServiceClient;

/** Uncomment and populate these variables in your code */
// $callingProjectId = 'The project ID to run the API call under';

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

Deleting inspection templates

To delete an inspection template:

Console

  1. In the GCP Console, open Cloud DLP.

    Go to Cloud DLP UI Beta

  2. Click the Templates tab. The console displays a list of all templates for the current project.

  3. In the Actions column for the template you want to delete, click the three vertical dots, and then click Delete.

    Screenshot of DLP UI templates with Actions menu open.

Alternatively, from the list of templates, click the name of the template you want to delete. On the template's detail page, click Delete.

Protocol

Use one of the *.*.delete methods:

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

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

/**
 * Delete a DLP inspection configuration template.
 */
use Google\Cloud\Dlp\V2\DlpServiceClient;

/** Uncomment and populate these variables in your code */
// $callingProjectId = 'The project ID to run the API call under';
// $templateId = 'The name of the template to delete';

// Instantiate a client.
$dlp = new DlpServiceClient();

// Run template deletion request
$templateName = $dlp->projectInspectTemplateName($callingProjectId, $templateId);
$dlp->deleteInspectTemplate($templateName);

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

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

¿Te sirvió esta página? Envíanos tu opinión:

Enviar comentarios sobre…

Cloud Data Loss Prevention