# SkillPatch skill: workload-manager-basics

This skill guides agents in managing Google Cloud Workload Manager evaluations, rules, scanned resources, and validation results using the public client libraries and REST API. It covers listing rules, creating and running evaluations for GCP best practices (including SAP, SQL Server, and custom rules), inspecting results, and exporting to BigQuery. It also includes important constraints around authentication, API surface usage, and sandbox fallback behavior.

You (the agent) were given this URL and asked to use this skill. This is a **public** skill — no SkillPatch account, API key, or prior setup is required. Two ways to use it:

**1. Use it right now** — the skill's complete file tree (SKILL.md + all reference files) is inlined below; read `SKILL.md` first, then follow it, consulting the other files as it directs.

**2. Install the exact package onto disk** (recommended if you can run a shell — this reproduces the skill byte-for-byte, including any binary assets that can't be inlined):

```bash
mkdir -p .claude/skills/workload-manager-basics
curl -sSL https://skillpatch.dev/install_skill/workload-manager-basics | tar -xz -C .claude/skills/
```

(`.claude/skills/` is Claude Code's convention; use whatever directory your agent loads skills from.)


---

## Skill files (9)

- `SKILL.md`
- `references/client-library-usage.md`
- `references/core-concepts.md`
- `references/general-best-practices.md`
- `references/iam-security.md`
- `references/public-cli-status.md`
- `references/public-mcp-status.md`
- `references/rest-usage.md`
- `references/setup-prerequisites.md`


### `SKILL.md`

````markdown
---
name: workload-manager-basics
metadata:
  category: CloudObservabilityAndMonitoring
description: >-
  Use this skill to manage Google Cloud Workload Manager evaluations, rules,
  scanned resources, and validation results by using public client libraries
  and the REST API. Use when you need to inspect workload best-practice rules,
  create and run evaluations for Google Cloud general best practices, SAP, SQL
  Server, or custom organizational rules, review violations, export results to
  BigQuery, or automate Workload Manager through client libraries because no
  service-specific public CLI or MCP server is available. Don't use for general
  Google Compute Engine instance management, VPC configuration, or standard IAM
  auditing.
---

# Workload Manager Basics

Workload Manager validates enterprise workloads against Google Cloud best
practices and recommendations. The public client libraries are centered on
evaluations: define a resource scope, choose built-in or custom rules, run an
evaluation, then inspect results and scanned resources.

## Use This Flow

```mermaid
flowchart LR
    Rules["List rules"] --> Eval["Create or update evaluation"]
    Resources["Project, folder, or org scope"] --> Eval
    Eval --> Run["Run evaluation"]
    Run --> Results["Inspect evaluation results"]
    Results --> Remediate["Remediate findings"]
    Results --> Export["Optional BigQuery export"]
```

## Core API Constraints

To ensure compatibility, security, and successful integration:

*   **Public Surface Only:** You MUST strictly interact with Workload Manager
    using the official public `google-cloud-workloadmanager` client library or
    the public REST API (`workloadmanager.googleapis.com/v1`).
*   **No Internal or Undocumented APIs:** Do NOT attempt to use internal RPC
    protocols, private service backends, or undocumented discovery mechanisms.
    They are not supported for public integrations and will fail.
*   **No Service-Specific CLI:** There is no public `gcloud workload-manager`
    CLI command group. Use `gcloud` only for authentication, IAM role
    assignment, and fetching raw REST tokens.
*   **Sandbox Execution Robustness (Auth/Mock Fallbacks):** When gcloud
    authentication or Workload Manager API calls fail in sandboxed or restricted
    environments (e.g., due to Context Aware Access token blocks, missing API
    enablement, or
    mock resources returning 404/403), immediately fall back to presenting
    example code and static findings from your references instead of entering
    retry loops. Present the correct client library code structure or REST API
    payload example, clearly explain the auth or resource limitation, and list
    typical rules or mock findings statically to satisfy the request.

## Prerequisites

1.  Enable the Workload Manager API:

    ```bash
    gcloud services enable workloadmanager.googleapis.com --quiet
    ```

2.  Authenticate locally using Application Default Credentials (ADC) before
    using client libraries:

    ```bash
    gcloud auth application-default login
    ```

3.  Ensure the Workload Manager service agent has the required roles granted in
    your project (mandatory for API/client library usage, see
    [IAM & Security](references/iam-security.md)).

4.  Grant the least-privileged role needed for the task. Start with
    `roles/workloadmanager.viewer` for read-only access to evaluation resources
    and use `roles/workloadmanager.evaluationAdmin` or
    `roles/workloadmanager.admin` only when creating, updating, running, or
    deleting evaluations.

## Quick Client Library Example

Use the Python client library for the first working automation path:

```bash
python3 -m pip install --upgrade google-cloud-workloadmanager
```

```python
from google.cloud import workloadmanager_v1

project_id = "PROJECT_ID"
location = "LOCATION"
parent = f"projects/{project_id}/locations/{location}"

client = workloadmanager_v1.WorkloadManagerClient()

rules = client.list_rules(
    request=workloadmanager_v1.ListRulesRequest(
        parent=parent,
        evaluation_type=workloadmanager_v1.Evaluation.EvaluationType.OTHER,
    )
)

for rule in rules.rules:
    print(rule.name, rule.display_name, rule.severity)
```

## Reference Directory

-   [Core Concepts](references/core-concepts.md): Evaluations, rules, results,
    scanned resources, supported workload types, and API shape.

-   [General Best Practices](references/general-best-practices.md): Google Cloud
    general best-practice posture checks, `OTHER` evaluation guidance, custom
    Rego rules, and scale/automation patterns.

-   [Client Libraries](references/client-library-usage.md): Python and Go client
    library examples for listing rules, creating evaluations, running
    evaluations, and reading findings.

-   [REST Usage](references/rest-usage.md): Direct REST examples for the public
    Workload Manager API and operations polling.

-   [Public CLI Status](references/public-cli-status.md): No documented
    service-specific `gcloud workload-manager` command group; use `gcloud` only
    for auth, IAM, API enablement, and REST tokens.

-   [Public MCP Status](references/public-mcp-status.md): No documented public
    Workload Manager MCP server; use client libraries or REST API instead.

-   [Setup Prerequisites](references/setup-prerequisites.md): Terraform examples
    only for adjacent prerequisites such as API enablement, IAM, BigQuery export
    datasets, and KMS keys. This is not Workload Manager resource management.

-   [IAM & Security](references/iam-security.md): Workload Manager roles,
    least-privilege guidance, service agents, data handling, and CMEK notes.

If product behavior or API fields are not covered here, check the current
Workload Manager product documentation and client library reference before
implementing.

## Authoritative References

-   [Workload Manager overview](https://docs.cloud.google.com/workload-manager/docs/overview)
-   [Google Cloud best practices](https://docs.cloud.google.com/workload-manager/docs/reference/best-practices-general)
-   [Workload Manager REST API](https://docs.cloud.google.com/workload-manager/docs/reference/rest)
-   [About custom rules](https://docs.cloud.google.com/workload-manager/docs/evaluate/custom-rules/about-custom-rules)
-   [Write custom rules using Rego](https://docs.cloud.google.com/workload-manager/docs/evaluate/custom-rules/rego-custom-rules)
-   [Python package](https://pypi.org/project/google-cloud-workloadmanager/)
-   [Workload Manager IAM roles](https://docs.cloud.google.com/iam/docs/roles-permissions/workloadmanager)
-   For additional information, use the Developer Knowledge MCP server `search_documents` tool.

## Additional Context

-   [Mastering cloud posture management with Workload Manager](https://discuss.google.dev/t/mastering-cloud-posture-management-security-reliability-and-finops-with-workload-manager/318258)

````


### `references/client-library-usage.md`

````markdown
# Workload Manager Client Libraries

Use client libraries when working with evaluation lifecycle resources. The
public Python client is Generally Available (GA) and supports Python 3.9 or
later.

## Python Setup

```bash
python3 -m venv .venv
source .venv/bin/activate
python3 -m pip install --upgrade google-cloud-workloadmanager
gcloud auth application-default login
```

## Python: List Rules

```python
from google.cloud import workloadmanager_v1

project_id = "PROJECT_ID"
location = "LOCATION"
parent = f"projects/{project_id}/locations/{location}"

client = workloadmanager_v1.WorkloadManagerClient()
response = client.list_rules(
    request=workloadmanager_v1.ListRulesRequest(
        parent=parent,
        evaluation_type=workloadmanager_v1.Evaluation.EvaluationType.SQL_SERVER,
    )
)

for rule in response.rules:
    print(rule.name, rule.display_name, rule.severity)
```

[Python API Reference](https://docs.cloud.google.com/python/docs/reference/google-cloud-workloadmanager/latest)

## Python: List General Best-Practice Rules

Use `OTHER` for the general/custom Workload Manager rule path. List rules at
runtime and select by name, tags, asset type, or severity instead of hardcoding
the full public catalog.

```python
from google.cloud import workloadmanager_v1

project_id = "PROJECT_ID"
location = "LOCATION"
parent = f"projects/{project_id}/locations/{location}"

client = workloadmanager_v1.WorkloadManagerClient()
response = client.list_rules(
    request=workloadmanager_v1.ListRulesRequest(
        parent=parent,
        evaluation_type=workloadmanager_v1.Evaluation.EvaluationType.OTHER,
    )
)

for rule in response.rules:
    tags = ", ".join(rule.tags)
    print(rule.name, rule.asset_type, rule.severity, tags)
```

## Python: Create a General Best-Practices Evaluation (Organization-Level Scope - Recommended)

This example creates a baseline `OTHER` evaluation targeting an organization
scope with a default daily scan schedule.

```python
from google.cloud import workloadmanager_v1

project_id = "PROJECT_ID"
org_id = "ORG_ID"
location = "LOCATION"
evaluation_id = "general-posture-prod"
parent = f"projects/{project_id}/locations/{location}"

client = workloadmanager_v1.WorkloadManagerClient()

# Gather all rules for general posture checks
rule_response = client.list_rules(
    request=workloadmanager_v1.ListRulesRequest(
        parent=parent,
        evaluation_type=workloadmanager_v1.Evaluation.EvaluationType.OTHER,
    )
)
rule_names = [rule.name for rule in rule_response.rules]

evaluation = workloadmanager_v1.Evaluation(
    description="General Google Cloud posture baseline",
    evaluation_type=workloadmanager_v1.Evaluation.EvaluationType.OTHER,
    resource_filter=workloadmanager_v1.ResourceFilter(
        scopes=[f"organizations/{org_id}"],
    ),
    schedule="0 0 * * *",
    rule_names=rule_names,
    labels={"owner": "platform", "baseline": "general"},
)

operation = client.create_evaluation(
    request=workloadmanager_v1.CreateEvaluationRequest(
        parent=parent,
        evaluation_id=evaluation_id,
        evaluation=evaluation,
    )
)
created = operation.result(timeout=600)
print(created.name)
```

## Python: Create a General Best-Practices Evaluation (Project-Level Scope - Fallback)

If organization-level access is not available, use project-level scope:

```python
from google.cloud import workloadmanager_v1

project_id = "PROJECT_ID"
location = "LOCATION"
evaluation_id = "general-posture-project"
parent = f"projects/{project_id}/locations/{location}"

client = workloadmanager_v1.WorkloadManagerClient()

# Gather all rules for general posture checks
rule_response = client.list_rules(
    request=workloadmanager_v1.ListRulesRequest(
        parent=parent,
        evaluation_type=workloadmanager_v1.Evaluation.EvaluationType.OTHER,
    )
)
rule_names = [rule.name for rule in rule_response.rules]

evaluation = workloadmanager_v1.Evaluation(
    description="General Google Cloud posture project baseline",
    evaluation_type=workloadmanager_v1.Evaluation.EvaluationType.OTHER,
    resource_filter=workloadmanager_v1.ResourceFilter(
        scopes=[f"projects/{project_id}"],
    ),
    schedule="0 0 * * *",
    rule_names=rule_names,
    labels={"owner": "platform", "baseline": "general"},
)

operation = client.create_evaluation(
    request=workloadmanager_v1.CreateEvaluationRequest(
        parent=parent,
        evaluation_id=evaluation_id,
        evaluation=evaluation,
    )
)
created = operation.result(timeout=600)
print(created.name)
```

## Python: Create a Custom Rules Evaluation

Use `custom_rules_bucket` only for custom Rego rules uploaded to Cloud Storage.
List rules from that bucket first, then create an `OTHER` evaluation with the
selected custom rule names.

```python
from google.cloud import workloadmanager_v1

project_id = "PROJECT_ID"
location = "LOCATION"
evaluation_id = "custom-org-policies-prod"
custom_rules_bucket = "CUSTOM_RULES_BUCKET"
parent = f"projects/{project_id}/locations/{location}"

client = workloadmanager_v1.WorkloadManagerClient()
rule_response = client.list_rules(
    request=workloadmanager_v1.ListRulesRequest(
        parent=parent,
        custom_rules_bucket=custom_rules_bucket,
        evaluation_type=workloadmanager_v1.Evaluation.EvaluationType.OTHER,
    )
)
rule_names = [rule.name for rule in rule_response.rules]

evaluation = workloadmanager_v1.Evaluation(
    description="Organization policy-as-code checks",
    evaluation_type=workloadmanager_v1.Evaluation.EvaluationType.OTHER,
    custom_rules_bucket=custom_rules_bucket,
    resource_filter=workloadmanager_v1.ResourceFilter(
        scopes=[f"projects/{project_id}"],
    ),
    rule_names=rule_names,
    labels={"owner": "platform", "baseline": "custom-rules"},
)

operation = client.create_evaluation(
    request=workloadmanager_v1.CreateEvaluationRequest(
        parent=parent,
        evaluation_id=evaluation_id,
        evaluation=evaluation,
    )
)
created = operation.result(timeout=600)
print(created.name)
```

## Python: Create an Evaluation (Organization-Level Scope - Recommended)

Fetch valid rule names first, then create the evaluation targeting organization
scope with a default daily schedule.

```python
from google.cloud import workloadmanager_v1

project_id = "PROJECT_ID"
org_id = "ORG_ID"
location = "LOCATION"
evaluation_id = "sql-server-prod"
parent = f"projects/{project_id}/locations/{location}"

client = workloadmanager_v1.WorkloadManagerClient()

rule_response = client.list_rules(
    request=workloadmanager_v1.ListRulesRequest(
        parent=parent,
        evaluation_type=workloadmanager_v1.Evaluation.EvaluationType.SQL_SERVER,
    )
)
rule_names = [rule.name for rule in rule_response.rules]

evaluation = workloadmanager_v1.Evaluation(
    description="SQL Server production validation",
    evaluation_type=workloadmanager_v1.Evaluation.EvaluationType.SQL_SERVER,
    resource_filter=workloadmanager_v1.ResourceFilter(
        scopes=[f"organizations/{org_id}"],
    ),
    schedule="0 0 * * *",
    rule_names=rule_names,
    labels={"owner": "platform", "workload": "sql-server"},
)

operation = client.create_evaluation(
    request=workloadmanager_v1.CreateEvaluationRequest(
        parent=parent,
        evaluation_id=evaluation_id,
        evaluation=evaluation,
    )
)
created = operation.result(timeout=600)
print(created.name)
```

## Python: Create an Evaluation (Project-Level Scope - Fallback)

```python
from google.cloud import workloadmanager_v1

project_id = "PROJECT_ID"
location = "LOCATION"
evaluation_id = "sql-server-prod-project"
parent = f"projects/{project_id}/locations/{location}"

client = workloadmanager_v1.WorkloadManagerClient()

rule_response = client.list_rules(
    request=workloadmanager_v1.ListRulesRequest(
        parent=parent,
        evaluation_type=workloadmanager_v1.Evaluation.EvaluationType.SQL_SERVER,
    )
)
rule_names = [rule.name for rule in rule_response.rules]

evaluation = workloadmanager_v1.Evaluation(
    description="SQL Server project validation",
    evaluation_type=workloadmanager_v1.Evaluation.EvaluationType.SQL_SERVER,
    resource_filter=workloadmanager_v1.ResourceFilter(
        scopes=[f"projects/{project_id}"],
    ),
    schedule="0 0 * * *",
    rule_names=rule_names,
    labels={"owner": "platform", "workload": "sql-server"},
)

operation = client.create_evaluation(
    request=workloadmanager_v1.CreateEvaluationRequest(
        parent=parent,
        evaluation_id=evaluation_id,
        evaluation=evaluation,
    )
)
created = operation.result(timeout=600)
print(created.name)
```

## Python: Run an Evaluation

```python
import uuid

from google.cloud import workloadmanager_v1

project_id = "PROJECT_ID"
location = "LOCATION"
evaluation_id = "sql-server-prod"
execution_id = "manual-run-001"
evaluation_name = (
    f"projects/{project_id}/locations/{location}/evaluations/{evaluation_id}"
)

client = workloadmanager_v1.WorkloadManagerClient()
operation = client.run_evaluation(
    request=workloadmanager_v1.RunEvaluationRequest(
        name=evaluation_name,
        execution_id=execution_id,
        execution=workloadmanager_v1.Execution(
            labels={"trigger": "manual"},
        ),
        request_id=str(uuid.uuid4()),
    )
)
execution = operation.result(timeout=1200)
print(execution.name, execution.state)
```

## Python: Read Findings

```python
from google.cloud import workloadmanager_v1

execution_name = (
    "projects/PROJECT_ID/locations/LOCATION/evaluations/EVALUATION_ID/"
    "executions/EXECUTION_ID"
)

client = workloadmanager_v1.WorkloadManagerClient()
for result in client.list_execution_results(
    request=workloadmanager_v1.ListExecutionResultsRequest(
        parent=execution_name,
        # All findings are listed by default. Note that filter string values must be nested-quoted:
        # filter='severity="HIGH"'
    )
):
    print(result.rule, result.severity, result.resource.name)
    print(result.violation_message)
    print(result.documentation_url)
```

## Python: Update an Evaluation Schedule

```python
from google.cloud import workloadmanager_v1
from google.protobuf import field_mask_pb2

evaluation_name = (
    "projects/PROJECT_ID/locations/LOCATION/evaluations/EVALUATION_ID"
)

client = workloadmanager_v1.WorkloadManagerClient()
evaluation = client.get_evaluation(name=evaluation_name)
evaluation.schedule = "0 0 */1 * *"

operation = client.update_evaluation(
    request=workloadmanager_v1.UpdateEvaluationRequest(
        evaluation=evaluation,
        update_mask=field_mask_pb2.FieldMask(paths=["schedule"]),
    )
)
updated = operation.result(timeout=600)
print(updated.schedule)
```

## Go Setup

```bash
go get cloud.google.com/go/workloadmanager/apiv1
```

## Go: List Evaluations

```go
package main

import (
    "context"
    "fmt"
    "log"

    workloadmanager "cloud.google.com/go/workloadmanager/apiv1"
    workloadmanagerpb "cloud.google.com/go/workloadmanager/apiv1/workloadmanagerpb"
    "google.golang.org/api/iterator"
)

func main() {
    ctx := context.Background()
    client, err := workloadmanager.NewClient(ctx)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    req := &workloadmanagerpb.ListEvaluationsRequest{
        Parent: "projects/PROJECT_ID/locations/LOCATION",
    }
    it := client.ListEvaluations(ctx, req)
    for {
        evaluation, err := it.Next()
        if err == iterator.Done {
            break
        }
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(evaluation.GetName())
    }
}
```

## Practical Guardrails

-   Check the current client library reference before using resources outside
    the evaluation lifecycle; some REST resources may not be generated into
    every client library yet.
-   Treat long-running operations as asynchronous. Always call
    `operation.result` with a timeout or poll explicitly.
-   Use request objects instead of mixing request objects and flattened keyword
    arguments in the same call.
-   Store execution result exports in a dedicated BigQuery dataset when using
    `BigQueryDestination`.

````


### `references/core-concepts.md`

````markdown
# Workload Manager Core Concepts

Workload Manager provides validation and automation tooling for enterprise
workloads on Google Cloud. Public documentation describes it as a service for
automating workload deployment and validating workloads against best practices
and recommendations.

## Resource Model

```mermaid
flowchart TD
    Scope["Scope: project, folder, or organization"] --> Filter["ResourceFilter"]
    Filter --> Evaluation["Evaluation"]
    Rules["Rule names or evaluation type"] --> Evaluation
    Evaluation --> Execution["Execution"]
    Execution --> RuleResults["Rule execution results"]
    Execution --> Findings["Execution results"]
    Execution --> Scanned["Scanned resources"]
    Findings --> Commands["Remediation commands"]
    Evaluation --> BQ["Optional BigQuery destination"]
```

## Main Resources

-   **Evaluation**: Configuration that defines what to validate. It includes a
    resource filter, workload evaluation type, rule names, labels, optional
    fixed schedule, optional custom rules bucket, optional BigQuery destination,
    and optional CMEK key.
-   **Rule**: A best-practice check with display name, severity, categories,
    remediation text, tags, and asset type.
-   **Execution**: A run of an evaluation. Executions expose state, timing,
    engine, run type, rule results, notices, external data sources, and summary
    counts.
-   **ExecutionResult**: A finding or remediation result from an execution,
    including rule, severity, violation message, documentation URL, affected
    resource, details, and suggested commands.
-   **ScannedResource**: A resource scanned by an execution, optionally filtered
    by rule.

## Evaluation Types

The public v1 client libraries expose these evaluation types:

-   `SAP`: SAP best practices.
-   `SQL_SERVER`: SQL Server best practices.
-   `OTHER`: General Google Cloud best practices and custom organizational
    best-practice rules.

Use `list_rules` with an evaluation type before creating an evaluation. This
keeps the selected rule names aligned with the workload type and current public
rule catalog.

For `OTHER`, start by listing the available rules in the target location. Use
the built-in general best-practice catalog for baseline cloud posture checks,
and use `custom_rules_bucket` only when evaluating Rego rules uploaded to Cloud
Storage. See [General Best Practices](general-best-practices.md) for selection
patterns.

## Evaluation Scope

Use `ResourceFilter` to constrain blast radius:

-   `scopes`: `projects/{project_id}`, `folders/{folder_id}`, or
    `organizations/{organization_id}`.
-   `resource_id_patterns`: Regular-expression style resource ID patterns.
-   `inclusion_labels`: Required labels that must be present on included
    resources.
-   `gce_instance_filter.service_accounts`: Limits Compute Engine instances to
    selected service accounts.

Prefer the smallest project or label-filtered scope that answers the question.
Folder or organization scopes need broader permissions and can produce more
results, more logs, and more BigQuery export data.

## Scheduling

`Evaluation.schedule` accepts fixed cron strings documented in the client
libraries:

-   `0 */1 * * *`: hourly
-   `0 */6 * * *`: every 6 hours
-   `0 */12 * * *`: every 12 hours
-   `0 0 */1 * *`: daily
-   `0 0 */7 * *`: weekly
-   `0 0 */14 * *`: every 14 days
-   `0 0 1 */1 *`: monthly

If a user needs an ad hoc run, use `run_evaluation` instead of adding a
schedule.

## Public Surface Boundaries

The Python client library package `google-cloud-workloadmanager` and generated
Go client cover evaluation workflows: evaluations, executions, execution
results, rules, and scanned resources.

The REST reference may expose additional resources, such as deployments,
actuations, discovered profiles, insights, and operations. When a needed
resource is not available in a client library, use the REST API directly and
keep the request shape close to the REST reference.

````


### `references/general-best-practices.md`

````markdown
# Workload Manager General Best Practices

Use this reference when a user asks for Google Cloud general best-practice
posture checks, cloud security posture management, FinOps posture, reliability
posture, or custom organizational rules. In client library automation, use
`OTHER` for this general/custom rule path and verify the available rules by
listing them in the target location.

## Decision Flow

```mermaid
flowchart TD
    Need["Need a posture baseline?"] --> BuiltIn{"Built-in Google Cloud rule?"}
    BuiltIn -->|Yes| ListOther["List rules with evaluation_type=OTHER"]
    BuiltIn -->|No| Custom["Write Rego custom rule"]
    Custom --> Bucket["Upload rules to a Cloud Storage bucket"]
    Bucket --> ListCustom["List rules with custom_rules_bucket"]
    ListOther --> Eval["Create OTHER evaluation"]
    ListCustom --> Eval
    Eval --> Run["Run or schedule execution"]
    Run --> Findings["Review violations"]
    Findings --> Export["Optional regional BigQuery export"]
```

## Built-In General Best Practices

The Google Cloud best-practices reference is the source of truth for the public
general catalog. It covers cross-product rules and assigns severities to
non-compliant resources.

Use the catalog for baseline posture checks across:

-   API keys
-   AlloyDB
-   BigQuery
-   Cloud Billing
-   Cloud DNS
-   Cloud KMS
-   Cloud Pub/Sub
-   Cloud SQL
-   Cloud Storage
-   Compute Engine
-   Filestore
-   Google Kubernetes Engine
-   Identity and Access Management
-   Memorystore for Redis Cluster
-   OS Config and VM Manager
-   Resource Manager
-   Secret Manager
-   Spanner
-   Vertex AI
-   Vertex AI Workbench

Treat the online catalog as dynamic. Agents should list rules from the API in
the target project and location before creating evaluations, then select rules
by rule name, asset type, severity, and tags.

## Severity Guidance

Use severity to prioritize remediation:

-   `CRITICAL`: address immediately when the finding can affect availability,
    data integrity, or supported configuration.
-   `HIGH`: plan remediation in the next maintenance window.
-   `MEDIUM`: queue remediation for near-term operational hardening.
-   `LOW`: use as posture signal, cleanup, or governance reporting.

## Posture Themes

The general catalog and posture-management guidance are useful across three
operational themes:

-   **Security**: public exposure, API key restrictions, default service account
    use, external IP exposure, CMEK, certificate state, and IAM hygiene.
-   **Reliability**: backups, point-in-time recovery, automatic storage growth,
    maintenance policies, unsupported settings, and resource health.
-   **FinOps**: labels and tags, lifecycle settings, storage expiration,
    oversized or under-governed resources, and historical trend tracking.

Start with a small baseline rule set that answers the immediate posture
question. Expand by tag or asset category once the first execution output is
well understood.

## Custom Organizational Rules

Use custom rules when the built-in catalog does not encode an internal mandate.
Workload Manager custom rules use Rego. In client library automation, list them
through the `OTHER` rule path with `custom_rules_bucket`.

Common custom-rule use cases:

-   Require labels such as `CostCenter`, `Owner`, or `Environment`.
-   Disallow resources in unapproved regions.
-   Block Compute Engine default service account usage.
-   Require private-only VMs or disallow external IP addresses.
-   Enforce organization-specific tagging, network, or backup conventions.

Custom rule metadata should include:

-   `DETAILS`: short description of the policy.
-   `SEVERITY`: user-defined severity such as `CRITICAL`, `HIGH`, `MEDIUM`, or
    `LOW`.
-   `ASSET_TYPE`: supported Cloud Asset Inventory asset type.
-   `TAGS`: rule filter tags.

## Custom Rule Evaluation Notes

-   Upload custom Rego files to a Cloud Storage bucket and pass that bucket as
    `custom_rules_bucket`.
-   Enable Service Usage API and Cloud Monitoring API in the project where the
    custom-rule evaluation is created and run.
-   List rules from the bucket before creating the evaluation.
-   Keep evaluations scoped to the smallest project, folder, organization, label
    set, or resource ID pattern that answers the question.
-   Split large custom catalogs across evaluations when needed; public docs list
    a maximum of 300 custom rules per evaluation.
-   BigQuery result exports for custom rules must use regional datasets, not
    multi-region datasets.

## Operational Pattern

1.  Run a manual General Best Practices scan to establish baseline posture.
2.  Triage critical and high findings first, grouped by asset type and owner.
3.  Add a daily or weekly schedule only after rule scope and alert volume are
    validated.
4.  Export results to a regional BigQuery dataset when historical trend analysis
    or dashboarding is required.
5.  Add custom Rego rules for internal controls that do not exist in the
    built-in catalog.

Check expected evaluation volume and BigQuery storage/query costs before
enabling frequent schedules or broad organization-wide exports.

````


### `references/iam-security.md`

````markdown
# Workload Manager IAM and Security

Use least privilege and start read-only. Evaluation creation and runs can scan
resource metadata across a project, folder, or organization, so scope and role
choice matter.

## Common Roles

| Role                                     | Use                               |
| ---------------------------------------- | --------------------------------- |
| `roles/workloadmanager.viewer`           | Read Workload Manager resources.  |
| `roles/workloadmanager.evaluationViewer` | Read evaluation resources and     |
:                                          : results.                          :
| `roles/workloadmanager.evaluationAdmin`  | Create, update, run, and delete   |
:                                          : evaluations and executions.       :
| `roles/workloadmanager.admin`            | Full Workload Manager             |
:                                          : administration.                   :
| `roles/workloadmanager.deploymentViewer` | Read deployment resources exposed |
:                                          : by the REST API.                  :
| `roles/workloadmanager.deploymentAdmin`  | Manage deployment resources       |
:                                          : exposed by the REST API.          :
| `roles/workloadmanager.insightWriter`    | Write or delete Workload Manager  |
:                                          : insights exposed by the REST API. :
| `roles/workloadmanager.workloadViewer`   | View workload resources and       |
:                                          : metadata.                         :
| `roles/workloadmanager.worker`           | Worker execution role for         |
:                                          : service-managed operations.       :
| `roles/workloadmanager.serviceAgent`     | Service agent role; do not grant  |
:                                          : to humans or general automation   :
:                                          : identities.                       :

## Role Selection

-   Listing rules, evaluations, executions, results, and scanned resources:
    `roles/workloadmanager.viewer` or `roles/workloadmanager.evaluationViewer`.
-   Creating or updating evaluations: `roles/workloadmanager.evaluationAdmin`.
-   Running evaluations: `roles/workloadmanager.evaluationAdmin`.
-   Full administration across Workload Manager resources:
    `roles/workloadmanager.admin`.
-   Folder or organization scope: grant roles at that scope only when project
    scope cannot answer the request.

## Data Handling

-   Results can include resource names, service accounts, labels, observed
    settings, violation messages, remediation commands, and documentation URLs.
-   BigQuery export datasets should have restricted dataset-level IAM.
-   Logs and client library debug output can include request metadata. Do not
    persist debug logs in broad-access locations.
-   Use a dedicated automation service account instead of user credentials for
    recurring evaluations.

## Workload Manager Service Agent & Service Account

To evaluate workloads or perform deployments, Workload Manager requires service
identities with appropriate metadata reading and resource actuation roles:

### 1. Google-Managed Service Agent (Evaluation/Validation)

When evaluations are executed, the Workload Manager Google-managed service agent
(`service-PROJECT_NUMBER@gcp-sa-workloadmanager.iam.gserviceaccount.com`) scans
GCP resources in the defined evaluation scope.

*   **Required Permissions**: The service agent must be granted roles that allow
    it to read resource configurations.
*   **Roles to Grant**:
    *   `roles/viewer` or `roles/browser` at the project, folder, or
        organization level of the evaluation scope to allow metadata scanning of
        Compute Engine, Cloud SQL, GKE, and other resources.
    *   For detailed role mappings, refer to the
        [Workload Manager Evaluation Roles documentation](https://docs.cloud.google.com/workload-manager/docs/evaluate/roles).

### 2. Deployment Service Account (Actuation/Deployments)

If you are using Workload Manager to automate deployments (e.g., deploying the
SAP agent or other enterprise software):

*   You must create a dedicated, customer-managed deployment Service Account in
    your project.
*   **Required Permissions**: The deployment service account requires
    permissions to write metadata and deploy agents on Compute Engine VM
    instances.
*   For setup steps, refer to the
    [Workload Manager Deployment Service Account Prerequisites](https://docs.cloud.google.com/workload-manager/docs/deploy/prerequisites#wlm-service-account).

## CMEK

`Evaluation.kms_key` accepts a key in this format:

```text
projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY
```

Make sure the Workload Manager service agent has the needed KMS permissions
before creating a CMEK-backed evaluation.

## Deletion and Idempotency

-   Use `request_id` for create, update, run, and delete requests when
    available.
-   Use `force=true` on evaluation deletion only when child executions should be
    deleted as part of the same request.
-   Before deleting, list executions and confirm whether any results need to be
    retained or exported.

````


### `references/public-cli-status.md`

````markdown
# Workload Manager Public CLI Status

Public documentation does not currently describe a dedicated `gcloud
workload-manager` command group. Do not write examples that imply Workload
Manager evaluations, executions, rules, deployments, or actuations can be
managed through a service-specific `gcloud` command.

Use `gcloud` only for adjacent Google Cloud setup tasks: project configuration,
authentication, IAM, service enablement, and access tokens. Use public client
libraries or the REST API for Workload Manager resources.

## Enable the API

```bash
gcloud services enable workloadmanager.googleapis.com --quiet
```

## Set Project and Location Defaults

```bash
gcloud config set project PROJECT_ID
export PROJECT_ID="$(gcloud config get-value project)"
export LOCATION="LOCATION"
```

## Authenticate for Local Client Library Usage

```bash
gcloud auth application-default login
```

## Authenticate for REST Usage

```bash
export TOKEN="$(gcloud auth print-access-token)"
```

## Grant a Workload Manager Role

```bash
gcloud projects add-iam-policy-binding PROJECT_ID \
  --member="user:USER_EMAIL" \
  --role="roles/workloadmanager.evaluationAdmin" \
  --quiet
```

Use `roles/workloadmanager.viewer` when read-only access is enough.

## REST Bridge

```bash
curl -sS \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  "https://workloadmanager.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/evaluations"
```

## Operational Notes

-   Do not invent service-specific CLI commands unless they appear in current
    public `gcloud` documentation.
-   Do not describe `gcloud` as a Workload Manager management surface.
-   `gcloud services`, `gcloud auth`, `gcloud projects add-iam-policy-binding`,
    and `gcloud logging` remain useful around the Workload Manager API.
-   Enabling the API has no direct charge by itself. Evaluations can create
    logs, scan resource metadata, and optionally export detailed results to
    BigQuery, which can incur normal service charges.

````


### `references/public-mcp-status.md`

````markdown
# Workload Manager Public MCP Status

No public Workload Manager MCP server is currently documented. Do not write
examples that imply Workload Manager has a public MCP integration.

Use public client libraries or the REST API for production workflows.

## Current Recommendation

```mermaid
flowchart LR
    Request["User request"] --> Check["Need Workload Manager resource?"]
    Check --> ClientLib["Use Python or Go client libraries for evaluations"]
    Check --> REST["Use REST for uncovered resources"]
    ClientLib --> Verify["Verify operation and findings"]
    REST --> Verify
```

## Safety Rules

-   Require a project, location, evaluation ID, and explicit resource scope for
    mutating operations.
-   Default list operations to read-only roles.
-   Require confirmation before deleting evaluations or executions.
-   Surface BigQuery export destinations and CMEK key names before creating or
    updating evaluations.

````


### `references/rest-usage.md`

````markdown
# Workload Manager REST Usage

Use REST when the client libraries do not cover a needed resource, when
debugging raw requests, or when building language-agnostic automation.

## Setup

```bash
export PROJECT_ID="PROJECT_ID"
export LOCATION="LOCATION"
export TOKEN="$(gcloud auth print-access-token)"
export BASE_URL="https://workloadmanager.googleapis.com/v1"
```

## List Rules

```bash
curl -sS \
  -H "Authorization: Bearer ${TOKEN}" \
  "${BASE_URL}/projects/${PROJECT_ID}/locations/${LOCATION}/rules"
```

Filter by evaluation type when selecting rules for a specific workload:

```bash
curl -sS \
  -H "Authorization: Bearer ${TOKEN}" \
  "${BASE_URL}/projects/${PROJECT_ID}/locations/${LOCATION}/rules?evaluationType=SQL_SERVER"
```

List built-in Google Cloud general best-practice rules with `OTHER`:

```bash
curl -sS \
  -H "Authorization: Bearer ${TOKEN}" \
  "${BASE_URL}/projects/${PROJECT_ID}/locations/${LOCATION}/rules?evaluationType=OTHER"
```

List uploaded custom Rego rules by passing the custom rules bucket:

```bash
export CUSTOM_RULES_BUCKET="CUSTOM_RULES_BUCKET"

curl -sS \
  -H "Authorization: Bearer ${TOKEN}" \
  "${BASE_URL}/projects/${PROJECT_ID}/locations/${LOCATION}/rules?evaluationType=OTHER&customRulesBucket=${CUSTOM_RULES_BUCKET}"
```

## Create an Evaluation (Organization-Level Scope - Recommended)

This example creates a SQL Server evaluation targeting an organization scope
with a default daily schedule.

```bash
export EVALUATION_ID="sql-server-prod"
export REQUEST_ID="$(uuidgen | tr '[:upper:]' '[:lower:]')"
export ORG_ID="ORG_ID"

curl -sS -X POST \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  "${BASE_URL}/projects/${PROJECT_ID}/locations/${LOCATION}/evaluations?evaluationId=${EVALUATION_ID}&requestId=${REQUEST_ID}" \
  -d @- <<'JSON'
{
  "description": "SQL Server production validation",
  "evaluationType": "SQL_SERVER",
  "resourceFilter": {
    "scopes": ["organizations/ORG_ID"]
  },
  "schedule": "0 0 * * *",
  "ruleNames": [
    "projects/PROJECT_ID/locations/LOCATION/rules/RULE_ID"
  ],
  "labels": {
    "owner": "platform",
    "workload": "sql-server"
  }
}
JSON
```

Replace `PROJECT_ID`, `LOCATION`, `ORG_ID`, and `RULE_ID` before running.

## Create an Evaluation (Project-Level Scope - Fallback)

If organization-level access is not available, use project-level scope:

```bash
export EVALUATION_ID="sql-server-prod-project"
export REQUEST_ID="$(uuidgen | tr '[:upper:]' '[:lower:]')"

curl -sS -X POST \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  "${BASE_URL}/projects/${PROJECT_ID}/locations/${LOCATION}/evaluations?evaluationId=${EVALUATION_ID}&requestId=${REQUEST_ID}" \
  -d @- <<'JSON'
{
  "description": "SQL Server project validation",
  "evaluationType": "SQL_SERVER",
  "resourceFilter": {
    "scopes": ["projects/PROJECT_ID"]
  },
  "schedule": "0 0 * * *",
  "ruleNames": [
    "projects/PROJECT_ID/locations/LOCATION/rules/RULE_ID"
  ],
  "labels": {
    "owner": "platform",
    "workload": "sql-server"
  }
}
JSON
```

## Create a General Best-Practices Evaluation (Organization-Level Scope - Recommended)

This example creates a general posture check evaluation targeting organization
scope with a default daily schedule.

```bash
export EVALUATION_ID="general-posture-prod"
export REQUEST_ID="$(uuidgen | tr '[:upper:]' '[:lower:]')"
export ORG_ID="ORG_ID"

curl -sS -X POST \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  "${BASE_URL}/projects/${PROJECT_ID}/locations/${LOCATION}/evaluations?evaluationId=${EVALUATION_ID}&requestId=${REQUEST_ID}" \
  -d @- <<'JSON'
{
  "description": "General Google Cloud posture baseline",
  "evaluationType": "OTHER",
  "resourceFilter": {
    "scopes": ["organizations/ORG_ID"]
  },
  "schedule": "0 0 * * *",
  "ruleNames": [
    "projects/PROJECT_ID/locations/LOCATION/rules/RULE_ID"
  ],
  "labels": {
    "owner": "platform",
    "baseline": "general"
  }
}
JSON
```

Replace `PROJECT_ID`, `LOCATION`, `ORG_ID`, and `RULE_ID` before running.

## Create a General Best-Practices Evaluation (Project-Level Scope - Fallback)

```bash
export EVALUATION_ID="general-posture-project"
export REQUEST_ID="$(uuidgen | tr '[:upper:]' '[:lower:]')"

curl -sS -X POST \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  "${BASE_URL}/projects/${PROJECT_ID}/locations/${LOCATION}/evaluations?evaluationId=${EVALUATION_ID}&requestId=${REQUEST_ID}" \
  -d @- <<'JSON'
{
  "description": "General Google Cloud posture project baseline",
  "evaluationType": "OTHER",
  "resourceFilter": {
    "scopes": ["projects/PROJECT_ID"]
  },
  "schedule": "0 0 * * *",
  "ruleNames": [
    "projects/PROJECT_ID/locations/LOCATION/rules/RULE_ID"
  ],
  "labels": {
    "owner": "platform",
    "baseline": "general"
  }
}
JSON
```

## Poll an Operation

```bash
export OPERATION_NAME="projects/${PROJECT_ID}/locations/${LOCATION}/operations/OPERATION_ID"

curl -sS \
  -H "Authorization: Bearer ${TOKEN}" \
  "${BASE_URL}/${OPERATION_NAME}"
```

The operation response contains `done: true` when complete. If an error is
present, fix that error before retrying with a new request ID.

## Run an Evaluation

```bash
export EVALUATION_ID="sql-server-prod"
export EXECUTION_ID="manual-run-001"
export REQUEST_ID="$(uuidgen | tr '[:upper:]' '[:lower:]')"

curl -sS -X POST \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  "${BASE_URL}/projects/${PROJECT_ID}/locations/${LOCATION}/evaluations/${EVALUATION_ID}/executions:run" \
  -d @- <<JSON
{
  "executionId": "${EXECUTION_ID}",
  "execution": {
    "labels": {
      "trigger": "manual"
    }
  },
  "requestId": "${REQUEST_ID}"
}
JSON
```

## List Executions

```bash
curl -sS \
  -H "Authorization: Bearer ${TOKEN}" \
  "${BASE_URL}/projects/${PROJECT_ID}/locations/${LOCATION}/evaluations/${EVALUATION_ID}/executions"
```

## List Execution Results

```bash
export EXECUTION_ID="EXECUTION_ID"

curl -sS \
  -H "Authorization: Bearer ${TOKEN}" \
  "${BASE_URL}/projects/${PROJECT_ID}/locations/${LOCATION}/evaluations/${EVALUATION_ID}/executions/${EXECUTION_ID}/results"
```

## List Scanned Resources

```bash
curl -sS \
  -H "Authorization: Bearer ${TOKEN}" \
  "${BASE_URL}/projects/${PROJECT_ID}/locations/${LOCATION}/evaluations/${EVALUATION_ID}/executions/${EXECUTION_ID}/scannedResources"
```

## Delete an Evaluation

Use `force=true` only when associated child resources should also be deleted.

```bash
export REQUEST_ID="$(uuidgen | tr '[:upper:]' '[:lower:]')"

curl -sS -X DELETE \
  -H "Authorization: Bearer ${TOKEN}" \
  "${BASE_URL}/projects/${PROJECT_ID}/locations/${LOCATION}/evaluations/${EVALUATION_ID}?requestId=${REQUEST_ID}&force=true"
```

## REST-Only Resources

If client libraries do not expose a Workload Manager resource yet, consult the
REST reference for endpoints such as deployments, actuations, discovered
profiles, insights, and operations. Keep automation defensive because generated
client libraries and REST resources can land at different times.

````


### `references/setup-prerequisites.md`

````markdown
# Workload Manager Setup Prerequisites

This file is not Workload Manager infrastructure-as-code support. Public
Terraform examples here cover only adjacent prerequisites around Workload
Manager: API enablement, IAM, BigQuery export datasets, and KMS keys.

Do not write examples that imply Terraform can manage Workload Manager
evaluations, executions, rules, deployments, actuations, or insights unless a
current provider reference explicitly documents those resources. Manage Workload
Manager resources through public client libraries or the REST API.

## Terraform: Enable API

```terraform
resource "google_project_service" "workload_manager" {
  project            = var.project_id
  service            = "workloadmanager.googleapis.com"
  disable_on_destroy = false
}

resource "google_project_service" "service_usage" {
  project            = var.project_id
  service            = "serviceusage.googleapis.com"
  disable_on_destroy = false
}

resource "google_project_service" "monitoring" {
  project            = var.project_id
  service            = "monitoring.googleapis.com"
  disable_on_destroy = false
}
```

The Service Usage and Cloud Monitoring APIs are required when creating and
running custom-rule evaluations.

## Terraform: Grant Evaluation Admin

```terraform
resource "google_project_iam_member" "workload_manager_evaluation_admin" {
  project = var.project_id
  role    = "roles/workloadmanager.evaluationAdmin"
  member  = "serviceAccount:${google_service_account.automation.email}"
}
```

## Terraform: BigQuery Export Dataset

```terraform
resource "google_bigquery_dataset" "workload_manager_results" {
  project    = var.project_id
  dataset_id = "workload_manager_results"
  location   = var.location
}
```

Reference this dataset from the client libraries or REST API with
`Evaluation.big_query_destination.destination_dataset`. Use a regional dataset
in the same region as the evaluation data; multi-region datasets are not
supported for Workload Manager result exports.

## Terraform: CMEK Prerequisites

```terraform
resource "google_kms_key_ring" "workload_manager" {
  project  = var.project_id
  name     = "workload-manager"
  location = var.location
}

resource "google_kms_crypto_key" "evaluations" {
  name            = "evaluations"
  key_ring        = google_kms_key_ring.workload_manager.id
  rotation_period = "7776000s"
}
```

Reference the key from the client libraries or REST API with
`Evaluation.kms_key` in this format:

```text
projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY
```

## Automation Boundary

```mermaid
flowchart LR
    TF["Terraform prerequisites"] --> API["Enable API"]
    TF --> IAM["Grant IAM roles"]
    TF --> BQ["Create BigQuery dataset"]
    TF --> KMS["Create KMS key"]
    ClientLib["Client Libraries or REST"] --> Eval["Create and run evaluations"]
    Eval --> BQ
    Eval --> KMS
```

Keep prerequisite setup and evaluation execution separate. Evaluation runs are
operational actions with long-running operation state, so they fit better in
controlled client library or REST API automation than in a Terraform plan.

````
