Mit Sammlungen den Überblick behalten
Sie können Inhalte basierend auf Ihren Einstellungen speichern und kategorisieren.
In diesem Dokument wird beschrieben, wie Sie benutzerdefinierte Regeln mit der Rego-Richtliniensprache schreiben.
Sie können diese Regeln im Arbeitslastmanager verwenden, um Ihre Arbeitslasten anhand der für Ihre Organisation definierten Best Practices zu bewerten.
Google stellt ein Beispiel-GitHub-Repository mit einer Reihe vordefinierter Regeln zur Verfügung, mit denen Sie Ihre Arbeitslasten bewerten können. Diese Beispiele decken mehrere Anwendungsfälle ab.
Wählen Sie Regeln aus dem Repository aus oder erstellen Sie eine Regeldatei (.rego), in der Ihre Bewertungsanforderungen beschrieben werden.
Eine benutzerdefinierte Regel besteht aus den folgenden Abschnitten:
Metadaten Die folgenden Felder definieren die Metadaten der Regel:
DETAILS: Eine kurze Beschreibung der Regel.
SEVERITY: Ein benutzerdefinierter Wert, der den Schweregrad des Verstoßes gegen die Regel definiert. Beispiel: HIGH, CRITICAL, MEDIUM oder LOW.
Importanweisungen Beispiel: data.validator.google.lib as lib.
Regeldefinitionen: Eine Reihe von Anweisungen, die die Regel definieren.
Beispielregeln
Die folgenden Beispielregeln sind im GitHub-Repository GoogleCloudPlatform/workload-manager verfügbar. Sie können diese Regeln unverändert in Ihren Cloud Storage-Bucket hochladen und damit Ihre Auswertungen ausführen. Alternativ können Sie die Regeln gemäß den Richtlinien Ihrer Organisation ändern und die Dateien dann in einen Cloud Storage-Bucket hochladen.
Beispiel 1: Es ist mindestens ein Label für Ihre VMs vorhanden.
Beispiel 2: sorgt dafür, dass für Ihre Arbeitslast nicht das Compute Engine-Standarddienstkonto verwendet wird.
Beispiel 3: sorgt dafür, dass VMs in Ihrer Arbeitslast keine externe IP-Adresse verwenden.
Eine vollständige Liste von Beispielregeln, die Sie in Workload Manager verwenden können, finden Sie im GitHub-Repository GoogleCloudPlatform/workload-manager.
[[["Leicht verständlich","easyToUnderstand","thumb-up"],["Mein Problem wurde gelöst","solvedMyProblem","thumb-up"],["Sonstiges","otherUp","thumb-up"]],[["Schwer verständlich","hardToUnderstand","thumb-down"],["Informationen oder Beispielcode falsch","incorrectInformationOrSampleCode","thumb-down"],["Benötigte Informationen/Beispiele nicht gefunden","missingTheInformationSamplesINeed","thumb-down"],["Problem mit der Übersetzung","translationIssue","thumb-down"],["Sonstiges","otherDown","thumb-down"]],["Zuletzt aktualisiert: 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)."]]