使用 Rego 编写自定义规则

本文档介绍了如何使用 Rego 政策语言编写自定义规则。您可以在 Workload Manager 中使用这些规则,根据为组织定义的最佳实践评估工作负载。

如需了解详情,请参阅 Workload Manager 中的自定义规则简介

准备工作

使用 Rego 编写自定义规则

Google 提供了一个示例 GitHub 代码库,其中包含一组预定义的规则,可用于评估工作负载。这些示例涵盖了多种使用情形。 从代码库中选择规则,或创建描述评估要求的规则 (.rego) 文件。

自定义规则包含以下部分:

  • 元数据。以下字段定义了规则元数据:

    • DETAILS:规则的简短说明。
    • SEVERITY:用户定义的值,用于定义违规的严重程度。例如,HIGHCRITICALMEDIUMLOW
    • ASSET_TYPE:支持的资源之一。请参阅支持的数据源
    • TAGS:规则的一个或多个标记。这些标记有助于过滤规则。
  • 软件包声明。例如 templates.google.compute.instance.label

  • import 语句。例如 data.validator.google.lib as lib

  • 规则定义:一组用于定义规则的指令。

示例规则

以下示例规则可在 GoogleCloudPlatform/workload-manager GitHub 代码库中找到。您可以将这些规则原封不动地上传到 Cloud Storage 存储桶,并使用它们来运行评估。或者,根据组织政策修改规则,然后将文件上传到 Cloud Storage 存储桶

  • 示例 1:确保您的虚拟机至少有一个标签。
  • 示例 2:确保工作负载不使用 Compute Engine 默认服务账号。
  • 示例 3:确保工作负载中的虚拟机不使用外部 IP 地址。

如需查看可在 Workload Manager 中使用的示例规则的完整列表,请参阅 GoogleCloudPlatform/workload-manager GitHub 代码库。

示例 1

确保 Compute Engine 资源至少有一个标记。

# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

########################################################################
# DETAILS:  MUST have atleast one tag
# SEVERITY: Medium
# ASSET_TYPE: compute.googleapis.com/Instance
# TAGS: Tags, Cost, Management, Compute Engine
########################################################################

package google.compute.instance.tags

import data.validator.google.lib as lib
import data.validator.google.lib.parameters as gparam
import future.keywords

asset := input.asset

params:=