שימוש ב-Google Antigravity כדי לשלוט בפעולות של KCC

1. מבוא

ב-Codelab הזה תלמדו על Google Antigravity (שנקראת Antigravity בהמשך המאמר), פלטפורמת פיתוח אג'נטית שמאפשרת לסביבת הפיתוח המשולבת (IDE) להתקדם לעידן שבו הסוכנים הם המפתחים הראשונים.

בניגוד לעוזרים רגילים לקידוד שמבצעים השלמה אוטומטית של שורות, Antigravity מספקת 'מרכז בקרה' לניהול סוכנים אוטונומיים שיכולים לתכנן, לקודד ואפילו לגלוש באינטרנט כדי לעזור לכם לבנות.

פלטפורמת Antigravity מתוכננת כפלטפורמה שבה הסוכנים הם המפתחים הראשונים. ההנחה היא שה-AI הוא לא רק כלי לכתיבת קוד, אלא גורם אוטונומי שיכול לתכנן, לבצע, לאמת ולשפר משימות הנדסיות מורכבות עם התערבות אנושית מינימלית.

מה תלמדו

  • התקנה והגדרה של Antigravity.
  • הסבר על מושגי יסוד ב-Antigravity כמו Agent Manager, ‏ Editor, ‏ Browser ועוד.
  • פיתוח מיומנות KCC Ops ברמת ייצור מאפס כדי לנהל משאבי Google Cloud בצורה בטוחה ותוך עמידה בדרישות.

מה תצטרכו

כרגע, Antigravity זמין כגרסת טרום-השקה לחשבונות Gmail אישיים. הוא כולל מכסת שימוש בחינם במודלים מתקדמים.

צריך להתקין את Antigravity באופן מקומי במערכת. המוצר זמין ב-Mac, ב-Windows ובגרסאות ספציפיות של Linux. בנוסף למחשב שלכם, תצטרכו את הדברים הבאים:

  • חשבון Gmail (חשבון Gmail אישי).
  • חשבון Google Cloud ופרויקט Google Cloud
  • דפדפן אינטרנט כמו Chrome שתומך במסוף Google Cloud וב-Cloud Shell

2. הגדרה ודרישות

הגדרת פרויקט

יצירת פרויקט ב-Google Cloud

  1. במסוף Google Cloud, בדף לבחירת הפרויקט, בוחרים פרויקט ב-Google Cloud או יוצרים פרויקט.
  2. הקפידו לוודא שהחיוב מופעל בפרויקט שלכם ב-Cloud. כך בודקים אם החיוב מופעל בפרויקט

שיעור ה-Codelab הזה מיועד למשתמשים ולמפתחים בכל הרמות (כולל מתחילים).

3. התקנה

אם עדיין לא התקנתם את Antigravity, נתחיל בהתקנה שלו. המוצר זמין כרגע בתצוגה מקדימה, ואפשר להשתמש בחשבון Gmail אישי כדי להתחיל להשתמש בו.

עוברים לדף הורדות ולוחצים על גרסת מערכת ההפעלה המתאימה למקרה שלכם. מפעילים את קובץ ההתקנה של האפליקציה ומתקינים אותה במחשב. אחרי שמסיימים את ההתקנה, מפעילים את אפליקציית Antigravity.

שלבים מרכזיים במהלך ההגדרה:

  • בחירת תהליך ההגדרה: מומלץ להתחיל מחדש את ה-codelab הזה.
  • פיתוח מבוסס-בדיקה (מומלץ): בוחרים באפשרות הזו. היא מאפשרת לסוכן לקבל החלטה ולחזור למשתמש כדי לקבל אישור, וזה חשוב מאוד לפעולות שקשורות לתשתית.

לאחר מכן, מגדירים את Editor ונכנסים אל Google. לבסוף, מאשרים את התנאים וההגבלות.

4. הגדרת התשתית: GKE ו-Config Connector

כדי ליצור את היכולת, צריך סביבת Google Cloud שבה מותקן Config Connector (KCC) באופן ידני ומוגדר במצב Namespaced. כך אפשר לנהל משאבי GCP כאובייקטים של Kubernetes.

שלב 0: הכנת הסביבה

1. דרישות מוקדמות לאשכול

יוצרים אשכול GKE חדש עם התכונות הנדרשות:

# Set your variables
export PROJECT_ID=$(gcloud config get-value project)
export CLUSTER_NAME="kcc-ops-cluster"
export REGION="us-central1"

# Create the cluster
gcloud container clusters create ${CLUSTER_NAME} \
    --region ${REGION} \
    --release-channel "regular" \
    --workload-pool=${PROJECT_ID}.svc.id.goog \
    --logging=SYSTEM \
    --monitoring=SYSTEM

# Get cluster credentials
gcloud container clusters get-credentials ${CLUSTER_NAME} --region ${REGION}

2. מתקינים את Config Connector Operator

הספק דואג שההתקנה תהיה עדכנית.

# Download the latest Config Connector operator
gcloud storage cp gs://configconnector-operator/latest/release-bundle.tar.gz release-bundle.tar.gz

# Extract the bundle
tar zxvf release-bundle.tar.gz

# Install the operator (Standard Cluster)
kubectl apply -f operator-system/configconnector-operator.yaml

3. הגדרה של מצב עם מרחבי שמות

יוצרים משאב ConfigConnector כדי לציין את מצב הפעולה.

# configconnector.yaml
apiVersion: core.cnrm.cloud.google.com/v1beta1
kind: ConfigConnector
metadata:
  name: configconnector.core.cnrm.cloud.google.com
spec:
  mode: namespaced
  stateIntoSpec: Absent
kubectl apply -f configconnector.yaml

4. יצירת זהות ומרחב שמות

במעבדה הזו נשתמש במרחב השמות default ובחשבון שירות ייעודי של Google ‏ (GSA).

# Set your variables
export PROJECT_ID=$(gcloud config get-value project)
export NAMESPACE="default"

# Create the Google Service Account
gcloud iam service-accounts create kcc-identity --project ${PROJECT_ID}

# Grant permissions on the project
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
    --member="serviceAccount:kcc-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
    --role="roles/owner"

# Grant Metric Writer permissions
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
    --member="serviceAccount:kcc-identity@${PROJECT_ID}.iam.gserviceaccount.com" \
    --role="roles/monitoring.metricWriter"

# Bind GSA to KSA via Workload Identity
gcloud iam service-accounts add-iam-policy-binding \
    kcc-identity@${PROJECT_ID}.iam.gserviceaccount.com \
    --member="serviceAccount:${PROJECT_ID}.svc.id.goog[cnrm-system/cnrm-controller-manager-${NAMESPACE}]" \
    --role="roles/iam.workloadIdentityUser"

5. הגדרת מרחב השמות

יוצרים ConfigConnectorContext כדי לעקוב אחרי מרחב השמות.

# configconnectorcontext.yaml
apiVersion: core.cnrm.cloud.google.com/v1beta1
kind: ConfigConnectorContext
metadata:
  name: configconnectorcontext.core.cnrm.cloud.google.com
  namespace: default
spec:
  googleServiceAccount: "kcc-identity@${PROJECT_ID}.iam.gserviceaccount.com"
  stateIntoSpec: Absent
kubectl apply -f configconnectorcontext.yaml

6. אימות ההתקנה

מחכים שהבקר יהיה מוכן למרחב השמות default.

kubectl wait -n cnrm-system \
    --for=condition=Ready pod \
    -l cnrm.cloud.google.com/component=cnrm-controller-manager \
    -l cnrm.cloud.google.com/scoped-namespace=default

5. Agent Manager: Mission Control

‫Antigravity מסתמך על הקוד הפתוח של Visual Studio Code ‏ (VS Code), אבל משנה באופן קיצוני את חוויית המשתמש כדי לתת עדיפות לניהול סוכנים על פני עריכת טקסט. הממשק מחולק לשני חלונות ראשיים נפרדים: Editor ו-Agent Manager.

מנהל סוכנים

בדרך כלל, כשמפעילים את Antigravity, מוצג למשתמש מנהל הסוכנים. הממשק הזה משמש כלוח בקרה של מרכז הבקרה. הוא מיועד לתיאום ברמה גבוהה, ומאפשר למפתחים ליצור סוכנים, לעקוב אחריהם ולקיים איתם אינטראקציה. הסוכנים פועלים באופן אסינכרוני בסביבות עבודה או במשימות שונות.

בתצוגה הזו, המפתח פועל כאדריכל. הם מגדירים מטרות כלליות. כל אחת מהבקשות האלה יוצרת מופע ייעודי של נציג. בממשק המשתמש מוצגת המחשה חזותית של תהליכי העבודה המקבילים האלה, עם הסטטוס של כל סוכן, הארטיפקטים שהוא יצר (תוכניות, תוצאות, הבדלים) וכל בקשה בהמתנה לאישור אנושי.

6. Antigravity Browser & Artifacts

במהלך התכנון והביצוע של העבודה, Antigravity יוצר חפצים. אלה קבצי Markdown עשירים, דיאגרמות של ארכיטקטורה, תמונות, הקלטות של דפדפנים והשוואות בין גרסאות של קוד.

איך ארטיפקטים פותרים את בעיית הפער באמון

בעבר, כשהסוכן טען שהוא תיקן את הבאג, המפתח היה צריך לקרוא את הקוד כדי לוודא זאת. ב-Antigravity, הסוכן יוצר ארטיפקט כדי להוכיח את זה.

תוצרי הפגישה

אלה הארטיפקטים העיקריים שנוצרים על ידי Antigravity:

  • Task Lists: תוכנית מובנית שנוצרת לפני כתיבת הקוד.
  • Implementation Plan: שינויים בארכיטקטורה עם פרטים טכניים.
  • Walkthrough: סיכום של השינויים והסבר על אופן הבדיקה שלהם.
  • Browser Recordings: הקלטות וידאו של סשנים בדפדפן לצורך אימות ממשק המשתמש.

Antigravity Browser

כשהסוכן צריך ליצור אינטראקציה עם האינטרנט, הוא מפעיל סוכן משנה של דפדפן. הסוכן המשני הזה יכול ללחוץ, לגלול, להקליד ולקרוא יומני מסוף. הוא משתמש במודל ייעודי כדי לפעול בדפים שפתוחים בדפדפן שמנוהל על ידי Antigravity.

7. חוויית העריכה

העורך שומר על המראה המוכר של VS Code. הוא כולל את סייר הקבצים הרגיל, הדגשת תחביר ומערכת אקולוגית של תוספים.

תכונות מרכזיות של העורך:

  • השלמה אוטומטית: הצעות חכמות שאפשר לאשר אותן בהקשה על Tab.
  • כרטיסייה לייבוא: מציעה להוסיף תלויות חסרות.
  • פקודות (Cmd + I): הפעלת השלמות מוטבעות באמצעות שפה טבעית.
  • החלונית הצדדית של הסוכן (Cmd + L): אפשר להפעיל או להשבית את החלונית של הסוכן כדי לשאול שאלות או לעיין בקבצים באמצעות @.

8. שליחת משוב

היתרון המרכזי של Antigravity הוא היכולת שלו לאסוף את המשוב שלכם בקלות. הארטיפקטים האלה מאפשרים לכם לספק משוב לסוכן בתגובות בסגנון Google Docs.

כשמוסיפים תגובה לתוכנית או למשימה, חשוב לזכור לשלוח את התגובה. כך מכוונים את הסוכן לכיוון הרצוי.

9. פיתוח מיומנות KCC Ops

עכשיו, אחרי שהבנתם את הפלטפורמה, נבנה את KCC Ops Skill.

בעזרת Kubernetes Config Connector‏ (KCC) אפשר לנהל משאבי GCP כאובייקטים של K8s. עם זאת, נדרשים אמצעי הגנה כדי למנוע סטיות בהגדרות, הפרות של תאימות ויצירה מחדש של משאבים בטעות.

שלב 1: יוצרים את המבנה של ה-Skill

בספריית השורש של סביבת העבודה, יוצרים את מבנה הספרייה של המיומנות:

mkdir -p .agents/skills/kcc-ops/scripts
mkdir -p .agents/skills/kcc-ops/resources/policies/templates
mkdir -p .agents/skills/kcc-ops/resources/policies/constraints

שלב 2: כותבים את הקובץ SKILL.md (המוח)

התג SKILL.md מגדיר את המטא-נתונים ואת "כלל הזהב" העיקרי של הסוכן. יצירת .agents/skills/kcc-ops/SKILL.md:

---
name: kcc-ops
description: Assists with Config Connector (KCC) configuration, resource generation, and troubleshooting on Google Cloud.
---

# Config Connector (KCC) Operations Skill

Use this skill to manage Google Cloud resources using Kubernetes-style configuration (Config Connector).

## 🛑 GOLDEN RULE: Separate Generation from Application

**NEVER generate and apply a manifest in a single autonomous step.**

1. **Craft:** Write the generated manifest to a local file.
2. **Analyze:** Present the manifest to the user. Perform Impact Analysis and Dry Runs. Explain the consequences of the change (e.g., "If this topic is deleted, the attached subscription becomes orphaned").
3. **Wait:** Pause execution and explicitly wait for user permission to proceed.
4. **Apply:** Only run `kubectl apply` *after* the user has reviewed the manifest and the impact analysis, and then unequivocally confirmed you should proceed.

## Core Responsibilities

0. **Context Verification**: Verify the execution context (cluster, namespace, GCP project, user account) with the user before performing any operations.
1. **Installation & Health**: Verify KCC is properly installed and healthy on the target cluster.
2. **Resource Inventory**: Query and summarize existing KCC resources within a namespace.
3. **Brownfield Bulk Export (Adoption)**: Export existing GCP project resources into valid KCC YAML manifests.
4. **Manifest Generation**: Generate valid YAML manifests for GCP resources using KCC CRDs.
5. **Impact Analysis**: Identify ancillary services and resources (e.g., Cloud Run, Apps) that depend on a resource being modified.
6. **Change Differentiation**: Generate diff summaries for resource edits to support change control.
7. **Policy Compliance**: Vet KCC manifests against OPA/Gatekeeper policies.
8. **Troubleshooting**: Analyze resource status, and consult the troubleshooting guide to resolve reconciliation issues.

## Guidelines for Operations

### 0. Context Verification

Before performing **any operations or executing commands** (including health checks), you **MUST** verify the current execution context and obtain explicit user confirmation.

1. **Read Context:** Use commands like `kubectl config current-context`, `kubectl config view --minify -o jsonpath='{.contexts[0].context.namespace}'`, `gcloud config get-value project`, and `gcloud config get-value account` to determine the active environment.
2. **Present & Ask:** Show this information to the user clearly (e.g., "I see my context is X, namespace is Y, project is Z, and account is A. Is this correct?").
3. **Wait:** Do not proceed with any other steps or scripts until the user has confirmed or provided corrections.

### 1. Installation & Health Check

Before performing operations, ensure the environment is ready:

- **Automation**: You MUST use `./scripts/check-health.sh` to verify namespaces, controllers, and CRDs. Do not use manual kubectl commands for health checks, as the script enforces standard formatting and context verification.

### 2. Resource Inventory & Discovery

To understand the current state of infrastructure:

- **Automation**: You MUST use `./scripts/inventory.sh` to get a summary table of all KCC resources. Do not use manual kubectl queries, as the script is optimized to securely discover all CRDs with context validation.

### 3. Manifest Structure

- All KCC resources belong to the `cnrm.cloud.google.com` API group.
- Use the `cnrm.cloud.google.com/project-id` annotation for cross-project resource management if not using Namespaced Mode.
- Always include `apiVersion`, `kind`, `metadata`, and `spec`.

### 4. Official Resource Reference (Agent Action)

When generating or troubleshooting manifests, you **must not guess** the API schema. Always consult the [Official Config Connector Reference](https://cloud.google.com/config-connector/docs/reference/overview) for the exact API version, kind, and required fields for the specific resource and cross reference with the official [github repository](https://github.com/GoogleCloudPlatform/k8s-config-connector/tree/master/config/crds/resources).

### 5. Troubleshooting Checklist

When a resource is not reconciling (check `kubectl get <kind> <name> -o yaml`):

- **Ready Condition**: Look for `status.conditions` where `type: Ready` and `status: "False"`.
- **Reason/Message**: Check the `reason` and `message` fields in the status conditions.
- **Consult the Guide**: Immediately check `./resources/troubleshooting-guide.md` for definitions of the error reason (e.g. `DependencyInvalid`, `ManagementConflict`) and follow its resolution steps.
- **Common Issues**:
  - Permissions: The KCC service account lacks IAM roles.
  - Quotas: GCP project quota exceeded.
  - Conflicts: Resource already exists or is managed by another tool.
  - Immutable Fields: Attempting to change a field that requires resource recreation. Look for "Update failed" errors related to immutable fields.
  - Reference Resolution: Check if the resource is waiting for a dependency (e.g., `referenced project not found`).

### 6. Impact Analysis (Ancillary Services)

Before modifying a resource (e.g., GCS Bucket, Pub/Sub Topic), verify whatElse depends on it:

- **Reference Search (Cluster-wide)**: Search for other KCC resources that reference the item.

  ```bash
  # Example: Find resources referencing a bucket named 'my-data-bucket'
  kubectl get-all -n <namespace> -o yaml | grep -C 5 "my-data-bucket"
  ```

- **IAM-based Analysis**: Check for IAM Service Accounts that have roles on the specific resource. A Cloud Run job or GKE Workload Identity might be using those permissions.
- **Common Ancillary Dependencies**:
  - **Storage Buckets**: Look for Cloud Run/GKE mounts (CSI), Cloud Functions triggers, or Dataflow jobs.
  - **Networks**: Check for Firewall rules, Forwarding rules, and GKE cluster assignments.
  - **IAM Policies**: Changing a policy might break access for external applications not managed by KCC.
- **Resource Graph**: Use `gcloud asset search-all-resources` to find resources that might have implicit links.

### 3. Policy Compliance & Best Practices

Evaluate KCC manifests against security and governance policies. The vetting tool supports three source modes:

- **Built-in Mode (Default)**: Uses the skill's high-fidelity `v1beta1` library (300+ Anthos constraints).
  - `Usage: ./scripts/vet-policy.sh <manifest-path>`
- **Remote Mode**: Clones and vets against an external Git repository.
  - `Usage: ./scripts/vet-policy.sh <manifest-path> <repo-url> [git-ref]`
  - ⚠️ **Note**: External libraries like the legacy GCP Policy Library may be out-of-date and cause schema validation errors with modern `gator`.
- **Local Mode**: Vets against a local directory of policies.
  - `Usage: ./scripts/vet-policy.sh <manifest-path> /path/to/local/policies`

**Interaction Model:**

1. Call `./scripts/vet-policy.sh` with the appropriate arguments.
2. Interpret the `=== KCC Best Practices ===` and `=== OPA/Gatekeeper ===` reports.
3. Supplement automated findings with manual review for specific security features not yet covered by OPA (e.g., `publicAccessPrevention: enforced`, `versioning: {enabled: true}`).

  ```bash
  # Run the skill's helper script (repo URL and branch are optional)
  ./scripts/vet-policy.sh manifest.yaml [policy-repo-url] [policy-ref]
  ```

## Skill Assets

This skill includes additional resources to streamline operations:

- **`scripts/`**: Automation scripts (e.g., `vet-policy.sh`, `bulk-export.sh`).
- **`examples/`**: Reference KCC manifests (e.g., `restricted-bucket.yaml`).
- **`resources/`**: Common templates, documentation snippets, and troubleshooting guides (e.g., `troubleshooting-guide.md`).

### 4. Safety Rails for Applying Manifests

Before applying any KCC manifest update to an existing resource, you MUST:

- **Verify Immutable Fields**: Call `./scripts/verify-immutable.sh <manifest-path>` to detect updates to fields (like `location`, `name`, `project-id`) that trigger destructive resource recreation.
- **Explain Impact**: If destructive changes are detected, you MUST warn the user and explain the downtime/data loss implications before requesting approval.

### 5. Emergency Recovery & Troubleshooting

If a resource is stuck in a "Deletion" or "Error" state:

- **Check for Abondon Flag**: Check if the resource has the `cnrm.cloud.google.com/deletion-policy: abandon` annotation. If it does, you will need to remove the annotation and then force delete the resource.
- **Force Delete**: Call `./scripts/force-delete.sh <kind> <name> [namespace]` to bypass Kubernetes finalizers and remove the resource from the cluster.
- **Orphan Warning**: Inform the user that force-deleting a KCC object may leave an orphaned resource in Google Cloud that requires manual cleanup.

### 6. Change Differentiation

When editing an existing resource, always generate a diff to summarize the change for reviewers or Git history:

- **Local Diff**:

  ```bash
  # Diff a local file against the cluster state
  kubectl diff -f modified-resource.yaml
  ```

- **Commit Summary Template**:

  ```text
  [KCC Change] Update <ResourceName> (<Kind>)
  - Field 'spec.foo' changed from 'X' to 'Y'
  - Impact: Ancillary service <ServiceName> will see updated <Config>
  ```

### 9. Best Practices

- **Namespaced Mode**: Prefer namespaced mode for better isolation.
- **Sensitive Data**: Use `spec.credential.secretRef` or similar for sensitive fields.
- **Resource Naming**: Use consistent naming conventions that match your Kubernetes/GCP standards.
- **Annotations**:
  - `cnrm.cloud.google.com/deletion-policy: abandon`: Keep GCP resource on KCC deletion.
  - `cnrm.cloud.google.com/state-into-spec: absent`: Prevents KCC from syncing GCP state back into the Kubernetes object (useful for avoiding reconciliation loops on fields like node counts).

## Common Resource Examples

### Compute Instance

```yaml
apiVersion: compute.cnrm.cloud.google.com/v1beta1
kind: ComputeInstance
metadata:
  name: instance-sample
  annotations:
    cnrm.cloud.google.com/project-id: "my-project-id"
spec:
  machineType: n1-standard-1
  zone: us-central1-a
  bootDisk:
    initializeParams:
      sourceImage: projects/debian-cloud/global/images/family/debian-11
  networkInterface:
    - networkRef:
        name: default
```

### Storage Bucket

```yaml
apiVersion: storage.cnrm.cloud.google.com/v1beta1
kind: StorageBucket
metadata:
  name: bucket-sample
spec:
  location: US
```

### Pub/Sub Topic & Subscription

```yaml
apiVersion: pubsub.cnrm.cloud.google.com/v1beta1
kind: PubSubTopic
metadata:
  name: order-events-topic
---
apiVersion: pubsub.cnrm.cloud.google.com/v1beta1
kind: PubSubSubscription
metadata:
  name: order-processor-sub
spec:
  topicRef:
    name: order-events-topic
  ackDeadlineSeconds: 30
```

שלב 3: הטמעה של כלי המלאי

יוצרים .agents/skills/kcc-ops/scripts/inventory.sh כדי לגלות משאבי KCC:

#!/bin/bash
# List all resources in the cnrm.cloud.google.com group
KCC_KINDS=$(kubectl api-resources --no-headers | awk '/\.cnrm\.cloud\.google\.com/ {print $1}')
KCC_KINDS_CSV=$(echo "$KCC_KINDS" | paste -sd, -)

printf "%-40s %-30s %-10s %s\n" "KIND" "NAME" "READY" "STATUS/MESSAGE"
kubectl get "$KCC_KINDS_CSV" -A -o custom-columns="KIND:.kind,NAME:.metadata.name,READY:.status.conditions[?(@.type=='Ready')].status,MSG:.status.conditions[?(@.type=='Ready')].message" --ignore-not-found --no-headers

שלב 4: הוספת הלוגיקה של בדיקת המדיניות

יצירת .agents/skills/kcc-ops/scripts/vet-policy.sh. הסקריפט הזה ישתמש ב-gator כדי לבדוק מניפסטים בהתאם למדיניות OPA:

#!/bin/bash
MANIFEST=$1
SKILL_ROOT=$(dirname "$(dirname "$0")")
POLICY_SRC="$SKILL_ROOT/resources/policies"

echo "=== OPA/Gatekeeper Policy Vetting ==="
if command -v gator >/dev/null 2>&1; then
    gator test -f "$MANIFEST" -f "$POLICY_SRC/templates" -f "$POLICY_SRC/constraints"
else
    echo "Gator not found. Skipping OPA audit."
fi

שלב 5: הטמעה של הגנה על שדות שלא ניתן לשנות

זהו אמצעי בטיחות קריטי. יצירת .agents/skills/kcc-ops/scripts/verify-immutable.sh:

#!/bin/bash
MANIFEST=$1
KIND=$(grep "^kind:" "$MANIFEST" | awk '{print $2}')
NAME=$(grep "name:" "$MANIFEST" | head -n 1 | awk '{print $2}')

# Check for changes in common immutable fields
IMMUTABLE_FIELDS=("location" "project-id" "name" "zone" "region")
TEMP_FILE=$(mktemp)
kubectl get "$KIND" "$NAME" -o yaml > "$TEMP_FILE" 2>/dev/null

for field in "${IMMUTABLE_FIELDS[@]}"; do
    NEW=$(grep "$field:" "$MANIFEST" | awk '{print $2}')
    OLD=$(grep "$field:" "$TEMP_FILE" | awk '{print $2}')
    if [ -n "$NEW" ] && [ -n "$OLD" ] && [ "$NEW" != "$OLD" ]; then
        echo "🚨 WARNING: Immutable field '$field' is changing! Potential resource recreation."
    fi
done
rm "$TEMP_FILE"

שלב 6: שחזור במקרה חירום (מחיקה בכוח)

יצירת .agents/skills/kcc-ops/scripts/force-delete.sh:

#!/bin/bash
KIND=$1; NAME=$2; NS=${3:-default}
echo "Removing finalizers for $KIND/$NAME in $NS..."
kubectl patch "$KIND" "$NAME" -n "$NS" -p '{"metadata":{"finalizers":null}}' --type=merge
kubectl delete "$KIND" "$NAME" -n "$NS" --wait=false

שלב 7: סיום ההגדרה של המשאבים

הופכים את כל הסקריפטים לניתנים להרצה:

chmod +x .agents/skills/kcc-ops/scripts/*.sh

10. בדיקת המיומנות החדשה

עכשיו, מתחילים שיחה חדשה ובודקים את היכולת:

  1. Discovery: @kcc-ops Show me all KCC resources in my cluster.
  2. תאימות: יוצרים קובץ bucket.yaml עם StorageBucket. שאלה: @kcc-ops Vet my bucket.yaml manifest.
  3. בטיחות: מנסים לעדכן את location של קטגוריה קיימת ב-bucket.yaml. שאלה: @kcc-ops Verify my bucket.yaml for immutable changes.

שימו לב איך הנציג בוחר בצורה חכמה את התסריט הנכון ופועל לפי 'כלל הזהב' מתוך SKILL.md.

11. אבטחת הסוכן

מתן גישה לסוכן AI למסוף הוא דבר עוצמתי, אבל נדרשים אמצעי בקרה.

עוברים אל Antigravity - Settings - Terminal (אנטי-גרביטציה – הגדרות – מסוף) ומעיינים ברשימת ההיתרים וברשימת החסימות.

  • רשימת ההיתרים: מוסיפים כאן את ls, kubectl get ואת סקריפטים של מיומנויות.
  • רשימת דחייה: מוסיפים את הפקודות sudo, rm -rf או פקודות הרסניות אחרות כדי לוודא שהסוכן תמיד יבקש הרשאה.

12. סיכום

מעולה! עברתם מהתקנת Antigravity לבניית מיומנות הפעלה של KCC ברמת דיוק גבוהה.

למדתם:

  • איך מרחיבים את הסוכן באמצעות כלים מותאמים אישית של bash.
  • איך מקודדים 'כללי זהב' תפעוליים ב-SKILL.md.
  • איך מספקים אמצעי הגנה לניהול תשתית מורכבת.

מה השלב הבא?

אפשר להרחיב את התיקייה resources/policies עם עוד הגבלות של OPA, או להוסיף סקריפט check-health.sh כדי להפוך את בדיקות המוכנות של האשכול לאוטומטיות.