Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Este documento descreve como escrever regras personalizadas usando a
linguagem de política Rego.
É possível usar essas regras no Gerenciador de cargas de trabalho para avaliar suas cargas de trabalho em relação às práticas recomendadas definidas para sua organização.
O Google oferece um repositório de amostra do GitHub com um conjunto de regras predefinidas que
você pode usar para avaliar suas cargas de trabalho. Esses exemplos abrangem vários casos de uso.
Selecione regras no repositório ou crie um arquivo de regra (.rego) que descreva seus requisitos de avaliação.
Uma regra personalizada tem as seguintes seções:
Metadados. Os campos a seguir definem os metadados da regra:
DETAILS: uma breve descrição da regra.
SEVERITY: um valor definido pelo usuário que define a gravidade da violação da
regra. Por exemplo, HIGH, CRITICAL, MEDIUM ou LOW.
Exemplo 1: garante que haja pelo menos um rótulo para suas VMs.
Exemplo 2: garante que sua carga de trabalho não use a conta de serviço padrão do Compute Engine.
Exemplo 3: garante que as VMs na sua carga de trabalho não usem um endereço IP externo.
Para uma lista completa de regras de amostra que podem ser usadas no Workload Manager, consulte o repositório
GoogleCloudPlatform/workload-manager
do GitHub.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-04 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)."]]