更新数据政策

更新现有数据政策的数据遮盖配置。此示例介绍了如何使用 FieldMask 有选择地更新“data_masking_policy”(例如,将遮盖表达式从 ALWAYS_NULL 更改为 SHA256),而不会影响其他字段或重新创建政策。

代码示例

Node.js

试用此示例之前,请按照 BigQuery 快速入门:使用客户端库中的 Node.js 设置说明进行操作。 如需了解详情,请参阅 BigQuery Node.js API 参考文档

如需向 BigQuery 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

const datapolicy = require('@google-cloud/bigquery-datapolicies');
const {DataPolicyServiceClient} = datapolicy.v2;
const protos = datapolicy.protos.google.cloud.bigquery.datapolicies.v2;
const {status} = require('@grpc/grpc-js');

const client = new DataPolicyServiceClient();

/**
 * Updates the data masking configuration of an existing data policy.
 * This example demonstrates how to use a FieldMask to selectively update the
 * `data_masking_policy` (for example, changing the masking expression from
 * ALWAYS_NULL to SHA256) without affecting other fields or recreating the policy.
 *
 * @param {string} projectId The Google Cloud project ID (For example, 'example-project-id').
 * @param {string} location The location of the data policy (For example, 'us').
 * @param {string} dataPolicyId The ID of the data policy to update (For example, 'example-data-policy-id').
 */
async function updateDataPolicy(projectId, location, dataPolicyId) {
  const resourceName = client.dataPolicyPath(projectId, location, dataPolicyId);

  const getRequest = {
    name: resourceName,
  };

  try {
    // To prevent race conditions, use the policy's etag in the update.
    const [currentDataPolicy] = await client.getDataPolicy(getRequest);
    const currentETag = currentDataPolicy.etag;

    // This example transitions a masking rule from ALWAYS_NULL to SHA256.
    const dataPolicy = {
      name: resourceName,
      etag: currentETag,
      dataMaskingPolicy: {
        predefinedExpression:
          protos.DataMaskingPolicy.PredefinedExpression.SHA256,
      },
    };

    // Use a field mask to selectively update only the data masking policy.
    const updateMask = {
      paths: ['data_masking_policy'],
    };

    const request = {
      dataPolicy,
      updateMask,
    };

    const [response] = await client.updateDataPolicy(request);
    console.log(`Successfully updated data policy: ${response.name}`);
    console.log(
      `New masking expression: ${response.dataMaskingPolicy.predefinedExpression}`
    );
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(
        `Error: Data policy '${resourceName}' not found. ` +
          'Make sure the data policy exists and the project, location, and data policy ID are correct.'
      );
    } else {
      console.error('Error updating data policy:', err.message, err);
    }
  }
}

Python

试用此示例之前,请按照 BigQuery 快速入门:使用客户端库中的 Python 设置说明进行操作。 如需了解详情,请参阅 BigQuery Python API 参考文档

如需向 BigQuery 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

from google.api_core import exceptions
from google.cloud import bigquery_datapolicies_v2
from google.protobuf import field_mask_pb2

client = bigquery_datapolicies_v2.DataPolicyServiceClient()


def update_data_policy(
    project_id: str,
    location: str,
    data_policy_id: str
) -> None:
    """Updates the data masking configuration of an existing data policy.

    This example demonstrates how to use a FieldMask to selectively update the
    `data_masking_policy` (for example, changing the masking expression from
    ALWAYS_NULL to SHA256) without affecting other fields or recreating the policy.

    Args:
        project_id: The Google Cloud project ID.
        location: The geographic location (for example, "us") of the data policy.
        data_policy_id: The ID of the data policy to update.
    """

    data_policy_name = client.data_policy_path(
        project=project_id,
        location=location,
        data_policy=data_policy_id,
    )

    # To prevent race conditions, use the policy's etag in the update.
    existing_policy = client.get_data_policy(name=data_policy_name)

    # This example transitions a masking rule from ALWAYS_NULL to SHA256.
    updated_data_policy = bigquery_datapolicies_v2.DataPolicy(
        name=data_policy_name,
        data_masking_policy=bigquery_datapolicies_v2.DataMaskingPolicy(
            predefined_expression=bigquery_datapolicies_v2.DataMaskingPolicy.PredefinedExpression.SHA256
        ),
        etag=existing_policy.etag,
    )

    # Use a field mask to selectively update only the data masking policy.
    update_mask = field_mask_pb2.FieldMask(
        paths=["data_masking_policy"]
    )
    request = bigquery_datapolicies_v2.UpdateDataPolicyRequest(
        data_policy=updated_data_policy,
        update_mask=update_mask,
    )

    try:
        response = client.update_data_policy(request=request)
        print(f"Successfully updated data policy: {response.name}")
        print(f"New data policy type: {response.data_policy_type.name}")
        if response.data_masking_policy:
            print(
                f"New masking expression: {response.data_masking_policy.predefined_expression.name}"
            )
    except exceptions.NotFound:
        print(f"Error: Data policy '{data_policy_name}' not found.")
        print("Make sure the data policy ID and location are correct.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

后续步骤

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