Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
En este documento, se describe cómo escribir reglas personalizadas con el lenguaje de políticas Rego.
Puedes usar estas reglas en Workload Manager para evaluar tus cargas de trabajo en función de las prácticas recomendadas definidas para tu organización.
Google proporciona un repositorio de GitHub de muestra con un conjunto de reglas predefinidas que puedes usar para evaluar tus cargas de trabajo. Estas muestras abarcan varios casos de uso.
Selecciona reglas del repositorio o crea un archivo de reglas (.rego) que describa tus requisitos de evaluación.
Una regla personalizada tiene las siguientes secciones:
Metadatos. Los siguientes campos definen los metadatos de la regla:
DETAILS: Es una descripción breve de la regla.
SEVERITY: Es un valor definido por el usuario que define la gravedad del incumplimiento de la regla. Por ejemplo: HIGH, CRITICAL, MEDIUM o LOW.
TAGS: Una o más etiquetas para la regla. Estas etiquetas ayudan a filtrar las reglas.
Declaración del paquete Por ejemplo, templates.google.compute.instance.label
Declaraciones de importación Por ejemplo, data.validator.google.lib as lib
Definiciones de reglas: Es un conjunto de instrucciones que definen la regla.
Ejemplos de reglas
Las siguientes reglas de muestra están disponibles en el repositorio de GitHub GoogleCloudPlatform/workload-manager. Puedes subir estas reglas tal como están a tu bucket de Cloud Storage y usarlas para ejecutar tus evaluaciones. Como alternativa, puedes modificar las reglas según las políticas de tu organización y, luego, subir los archivos a un bucket de Cloud Storage.
Ejemplo 1: Garantiza que haya al menos una etiqueta para tus VMs.
Ejemplo 2: Garantiza que tu carga de trabajo no use la cuenta de servicio predeterminada de Compute Engine.
Ejemplo 3: Garantiza que las VMs de tu carga de trabajo no usen una dirección IP externa.
Para obtener una lista completa de las reglas de muestra que puedes usar en Workload Manager, consulta el repositorio de GitHub GoogleCloudPlatform/workload-manager.
Después de crear el archivo .rego, súbelo a un bucket de Cloud Storage. El nivel superior de tu bucket de Cloud Storage debe incluir las carpetas /lib y /rules:
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-09 (UTC)"],[],[],null,["# Write custom rules using Rego\n\nThis document describes how to write custom rules using the\n[Rego policy language](https://www.openpolicyagent.org/docs/latest/policy-language/).\nYou can use these rules in Workload Manager to evaluate your\nworkloads against the best practices defined for your organization.\n\nFor more information, see [About custom rules in Workload Manager](/workload-manager/docs/evaluate/custom-rules/about-custom-rules).\n\nBefore you begin\n----------------\n\n- Be familiar with [Rego policy language](https://www.openpolicyagent.org/docs/latest/policy-language/).\n\nWrite custom rules using Rego\n-----------------------------\n\nGoogle provides a sample GitHub repository with a set of predefined rules that\nyou can use to evaluate your workloads. These samples cover multiple use cases.\nSelect rules from the repository or create a rule (`.rego`) file that describes\nyour evaluation requirements.\n\nA custom rule has the following sections:\n\n- **Metadata**. The following fields define the rule metadata:\n\n - `DETAILS`: a short description for the rule.\n - `SEVERITY`: a user-defined value that defines the severity of violation of the rule. For example, `HIGH`, `CRITICAL`, `MEDIUM`, or `LOW`.\n - `ASSET_TYPE`: one of the supported assets. See [Supported data sources](/workload-manager/docs/evaluate/custom-rules/about-custom-rules#supported-data-sources).\n - `TAGS`: one or more tags for the rule. These tags help filter the rules.\n- **Package declaration** . For example, `templates.google.compute.instance.label`.\n\n- **Import statements** . For example, `data.validator.google.lib as lib`.\n\n- **Rule definitions**. a set of instructions that defines the rule.\n\n### Example rules\n\nThe following sample rules are available in the\n[GoogleCloudPlatform/workload-manager](https://github.com/GoogleCloudPlatform/workload-manager) GitHub repository. You can\nupload these rules as they are to your Cloud Storage bucket and use it to run\nyour evaluations. Alternatively, modify the rules as per your organization\npolicies and then [upload the files to a Cloud Storage bucket](#upload-custom-rules).\n\n- Example 1: ensures that there is at least one label for your VMs.\n- Example 2: ensures that your workload does not use the Compute Engine default service account.\n- Example 3: ensures that VMs in your workload don't use an external IP address.\n\nFor a full list of sample rules that you can use in Workload Manager, see the\n[GoogleCloudPlatform/workload-manager](https://github.com/GoogleCloudPlatform/workload-manager)\nGitHub repository. \n\n### Example 1\n\nEnsures that there is at least one tag for the Compute Engine resources.\n\n\n # Copyright 2024 Google LLC\n #\n # Licensed under the Apache License, Version 2.0 (the \"License\");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # https://www.apache.org/licenses/LICENSE-2.0\n #\n # Unless required by applicable law or agreed to in writing, software\n # distributed under the License is distributed on an \"AS IS\" BASIS,\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n\n ########################################################################\n # DETAILS: MUST have atleast one tag\n # SEVERITY: Medium\n # ASSET_TYPE: compute.googleapis.com/Instance\n # TAGS: Tags, Cost, Management, Compute Engine\n ########################################################################\n\n package google.compute.instance.tags\n\n import data.validator.google.lib as lib\n import data.validator.google.lib.parameters as gparam\n import future.keywords\n\n asset := input.asset\n\n params:= lib.get_default(gparam.global_parameters,\"compute\",{})\n\n deny [{\"msg\": message, \"details\": metadata}] {\n\n \t# Check if resource is in exempt list\n \texempt_list := lib.get_default(params, \"exemptions\", [])\n \texempt := {asset.name} & {ex | ex := exempt_list[_]}\n \tnot count(exempt) != 0\n\n \ttags := lib.get_default(asset.resource.data, \"tags\", {\"items\": []})\n \tcount(tags.items) == 0\n\n \tmessage:=\"Compute resource is missing tags. Ensure appropriate tags are applied.\"\n\n \tmetadata:={\"name\": asset.name}\n }\n\n\u003cbr /\u003e\n\n### Example 2\n\nEnsures that your workload does not use the Compute Engine default service account\n\n\n # Copyright 2024 Google LLC\n #\n # Licensed under the Apache License, Version 2.0 (the \"License\");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # https://www.apache.org/licenses/LICENSE-2.0\n #\n # Unless required by applicable law or agreed to in writing, software\n # distributed under the License is distributed on an \"AS IS\" BASIS,\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n\n ########################################################################\n # DETAILS: MUST NOT use default service account\n # SEVERITY: Medium\n # ASSET_TYPE: compute.googleapis.com/Instance\n # TAGS: Defaults, Management, Compute Engine\n ########################################################################\n\n package google.compute.defaultserviceAccount\n\n import data.validator.google.lib as lib\n import data.validator.google.lib.parameters as gparam\n import future.keywords\n\n asset := input.asset\n\n input_enriched := object.union({\"resource\": {\"data\": {\"serviceAccounts\": []}}}, asset)\n\n params := lib.get_default(gparam.global_parameters, \"compute\", {})\n\n deny[{\n \t\"msg\": \"Disallowed default service account\",\n \t\"details\": {\"name\": asset.name},\n }] {\n\n \taccount = input_enriched.resource.data.serviceAccounts[_]\n \tendswith(account.email, params.default_sa)\n }\n\n\u003cbr /\u003e\n\n### Example 3\n\nEnsures that VMs in your workload don't use an external IP address.\n\n\n # Copyright 2024 Google LLC\n #\n # Licensed under the Apache License, Version 2.0 (the \"License\");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # https://www.apache.org/licenses/LICENSE-2.0\n #\n # Unless required by applicable law or agreed to in writing, software\n # distributed under the License is distributed on an \"AS IS\" BASIS,\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n\n ########################################################################\n # DETAILS: Ensure VMs dont have External IP\n # SEVERITY: High\n # ASSET_TYPE: compute.googleapis.com/Instance\n # TAGS: Security, Network, Compute Engine, External IP, VM, Virtual Machine\n ########################################################################\n\n package google.compute.instance.approved.external.ip\n\n import data.validator.google.lib as lib\n import data.validator.google.lib.parameters as gparam\n import future.keywords\n\n asset := input.asset\n\n params := lib.get_default(gparam.global_parameters, \"compute\", {})\n\n deny [{\"msg\": message, \"details\": metadata}] {\n\n \t# Check if resource is in exempt list\n \texempt_list := lib.get_default(params, \"exemptions\", [])\n \texempt := {asset.name} & {ex | ex := exempt_list[_]}\n \tnot count(exempt) != 0\n\n \t# Find network access config block w/ external IP\n \tinstance := asset.resource.data\n \taccess_config := instance.networkInterfaces[_].accessConfigs\n \tcount(access_config) \u003e 0\n\n \tmessage := sprintf(\"%v : VM Instance has external IP. current config: %v\",[asset.name, access_config])\n \tmetadata := {\"name\": asset.name}\n }\n\n\u003cbr /\u003e\n\nUpload the rule to a Cloud Storage bucket\n-----------------------------------------\n\nAfter you create the `.rego` file, [upload it a Cloud Storage bucket](/storage/docs/uploading-objects). The\ntop level of your Cloud Storage bucket must include the `/lib` and `/rules` folders:\n\n- `lib`\n - `parameters.rego`\n - `utils.rego`\n- `/rules`\n - \u003cvar translate=\"no\"\u003erule_name1\u003c/var\u003e`.rego`\n - \u003cvar translate=\"no\"\u003erule_name2\u003c/var\u003e`.rego`\n\nWhat's next\n-----------\n\n- Learn more [about workload evaluations](/workload-manager/docs/about-evaluations).\n- Learn how to [create and run an evaluation](/workload-manager/docs/create-evaluation)."]]