更新作业触发器

此示例将更新 infoType 和作业触发器的最低可能性。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C#

如需了解如何安装和使用用于 Sensitive Data Protection 的客户端库,请参阅 Sensitive Data Protection 客户端库

如需向 Sensitive Data Protection 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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

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

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

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

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

Go

如需了解如何安装和使用用于 Sensitive Data Protection 的客户端库,请参阅 Sensitive Data Protection 客户端库

如需向 Sensitive Data Protection 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import (
	"context"
	"fmt"
	"io"

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

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

	ctx := context.Background()

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

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

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

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

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

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

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

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

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

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

}

Java

如需了解如何安装和使用用于 Sensitive Data Protection 的客户端库,请参阅 Sensitive Data Protection 客户端库

如需向 Sensitive Data Protection 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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

public class TriggersPatch {

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

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

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

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

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

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

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

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

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

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

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

Node.js

如需了解如何安装和使用敏感数据保护客户端库,请参阅 敏感数据保护客户端库

如需向 Sensitive Data Protection 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

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

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

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

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

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

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

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

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

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

PHP

如需了解如何安装和使用用于 Sensitive Data Protection 的客户端库,请参阅 Sensitive Data Protection 客户端库

如需向 Sensitive Data Protection 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

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

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

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

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

    // Send the update job trigger request and process the response.
    $name = "projects/$callingProjectId/locations/global/jobTriggers/" . $jobTriggerName;

    $response = $dlp->updateJobTrigger($name, [
        'jobTrigger' => $jobTrigger,
        'updateMask' => $fieldMask
    ]);

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

Python

如需了解如何安装和使用敏感数据保护客户端库,请参阅 敏感数据保护客户端库

如需向 Sensitive Data Protection 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from typing import List

import google.cloud.dlp


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

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

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

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

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

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

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

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器