Nắm vững các hoạt động của KCC bằng Google Antigravity

1. Giới thiệu

Trong lớp học lập trình này, bạn sẽ tìm hiểu về Google Antigravity (gọi tắt là Antigravity trong phần còn lại của tài liệu), một nền tảng phát triển tác nhân, giúp IDE phát triển thành kỷ nguyên ưu tiên tác nhân.

Không giống như các trợ lý lập trình tiêu chuẩn chỉ tự động hoàn thành các dòng, Antigravity cung cấp một "Trung tâm kiểm soát" để quản lý các tác nhân tự quản có thể lập kế hoạch, lập trình và thậm chí duyệt web để giúp bạn xây dựng.

Antigravity được thiết kế dưới dạng một nền tảng ưu tiên tác nhân. Điều này giả định rằng AI không chỉ là một công cụ để viết mã mà còn là một tác nhân tự quản có khả năng lập kế hoạch, thực thi, xác thực và lặp lại các nhiệm vụ kỹ thuật phức tạp mà không cần nhiều sự can thiệp của con người.

Kiến thức bạn sẽ học được

  • Cài đặt và định cấu hình Antigravity.
  • Khám phá các khái niệm chính của Antigravity như Agent Manager, Editor, Browser và nhiều khái niệm khác.
  • Xây dựng Kỹ năng Ops KCC cấp sản xuất từ đầu để quản lý các tài nguyên trên Google Cloud một cách an toàn và tuân thủ.

Bạn cần có

Hiện tại, Antigravity được cung cấp dưới dạng bản dùng thử cho tài khoản Gmail cá nhân. Bạn có hạn mức miễn phí để sử dụng các mô hình hàng đầu.

Bạn cần cài đặt Antigravity trên hệ thống của mình. Sản phẩm này có trên máy Mac, Windows và một số bản phân phối Linux cụ thể. Ngoài máy tính của riêng mình, bạn sẽ cần những thứ sau:

  • Tài khoản Gmail (Tài khoản Gmail cá nhân).
  • Tài khoản Google Cloud và dự án trên Google Cloud
  • Một trình duyệt web như Chrome hỗ trợ Google Cloud Console và Cloud Shell

2. Thiết lập và yêu cầu

Thiết lập dự án

Tạo một dự án trên Google Cloud

  1. Trong Google Cloud Console, trên trang chọn dự án, hãy chọn hoặc tạo một dự án trên đám mây của Google Cloud.
  2. Đảm bảo bạn đã bật tính năng thanh toán cho dự án trên Cloud. Tìm hiểu cách kiểm tra xem tính năng thanh toán có được bật trong một dự án hay không.

Lớp học lập trình này dành cho người dùng và nhà phát triển ở mọi cấp độ (kể cả người mới bắt đầu).

3. Cài đặt

Nếu bạn chưa cài đặt Antigravity, hãy bắt đầu bằng cách cài đặt Antigravity. Hiện tại, sản phẩm này đang ở giai đoạn xem trước và bạn có thể sử dụng tài khoản Gmail cá nhân để bắt đầu sử dụng.

Truy cập vào trang tải xuống rồi nhấp vào phiên bản hệ điều hành phù hợp với trường hợp của bạn. Khởi chạy trình cài đặt ứng dụng và cài đặt ứng dụng đó trên máy của bạn. Sau khi hoàn tất quá trình cài đặt, hãy chạy ứng dụng Antigravity.

Các bước chính trong quá trình thiết lập:

  • Chọn quy trình thiết lập: Bạn nên bắt đầu lại từ đầu cho lớp học lập trình này.
  • Phát triển dựa trên quy trình xem xét (nên dùng): Chọn phương án này. Điều này cho phép tác nhân đưa ra quyết định và quay lại người dùng để phê duyệt, điều này rất quan trọng đối với các hoạt động về cơ sở hạ tầng.

Tiếp theo, hãy Định cấu hình Editor và Đăng nhập vào Google. Cuối cùng, hãy chấp nhận Điều khoản sử dụng.

4. Thiết lập cơ sở hạ tầng: GKE và Config Connector

Trước khi có thể tạo kỹ năng, bạn cần có một môi trường Google Cloud đã cài đặt Config Connector (KCC) theo cách thủ công và được định cấu hình ở Chế độ có không gian tên. Việc này cho phép bạn quản lý các tài nguyên GCP dưới dạng các đối tượng Kubernetes.

Bước 0: Chuẩn bị môi trường

1. Điều kiện tiên quyết về cụm

Tạo một cụm GKE mới có các tính năng cần thiết đã bật:

# 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. Cài đặt Config Connector Operator

Trình thao tác sẽ giúp bạn luôn cập nhật bản cài đặt.

# 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. Định cấu hình Chế độ có không gian tên

Tạo một tài nguyên ConfigConnector để chỉ định chế độ hoạt động.

# 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. Tạo danh tính và không gian tên

Đối với lớp học này, chúng ta sẽ sử dụng không gian tên default và Tài khoản dịch vụ chuyên dụng của 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. Định cấu hình Không gian tên

Tạo một ConfigConnectorContext để theo dõi không gian tên.

# 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. Xác minh quá trình cài đặt

Chờ bộ điều khiển sẵn sàng cho không gian tên 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 phân nhánh nền tảng Visual Studio Code (VS Code) mã nguồn mở nhưng thay đổi đáng kể trải nghiệm người dùng để ưu tiên việc quản lý tác nhân hơn là chỉnh sửa văn bản. Giao diện này được chia thành 2 cửa sổ chính riêng biệt: Editor và Agent Manager.

Người quản lý của đại lý

Khi khởi chạy Antigravity, người dùng thường được chào đón bởi Trình quản lý tác nhân. Giao diện này đóng vai trò là trang tổng quan Trung tâm điều khiển. Đây là một công cụ được thiết kế để điều phối ở cấp độ cao, cho phép nhà phát triển tạo, giám sát và tương tác với nhiều tác nhân hoạt động không đồng bộ trên nhiều không gian làm việc hoặc tác vụ.

Trong trường hợp này, nhà phát triển đóng vai trò là một kiến trúc sư. Họ xác định các mục tiêu cấp cao. Mỗi yêu cầu này sẽ tạo ra một phiên bản tác nhân chuyên dụng. Giao diện người dùng cung cấp hình ảnh trực quan về các luồng công việc song song này, cho thấy trạng thái của từng tác nhân, Artifacts (Hiện vật) mà tác nhân đã tạo ra (kế hoạch, kết quả, sự khác biệt) và mọi yêu cầu đang chờ phê duyệt của con người.

6. Antigravity Browser & Artifacts

Antigravity tạo ra Artifacts (Hiện vật) khi lập kế hoạch và hoàn thành công việc. Đây là các tệp markdown phong phú, sơ đồ cấu trúc, hình ảnh, bản ghi trình duyệt và các khác biệt về mã.

Các cấu phần phần mềm giúp giải quyết "Khoảng trống về độ tin cậy"

Khi một nhân viên hỗ trợ tuyên bố "Tôi đã khắc phục lỗi này", trước đây, nhà phát triển phải đọc mã để xác minh. Trong Antigravity, tác nhân tạo ra một hiện vật để chứng minh điều đó.

Tệp phần mềm

Sau đây là các cấu phần phần mềm chính do Antigravity tạo ra:

  • Task Lists: Kế hoạch có cấu trúc được tạo trước khi viết mã.
  • Implementation Plan: Các thay đổi về cấu trúc với thông tin chi tiết về kỹ thuật.
  • Walkthrough: Bản tóm tắt các thay đổi và cách kiểm thử các thay đổi đó.
  • Browser Recordings: Bản ghi video về các phiên trình duyệt để xác minh giao diện người dùng.

Trình duyệt Antigravity

Khi cần tương tác với web, tác nhân sẽ gọi một tác nhân phụ của trình duyệt. Trợ lý ảo này có thể nhấp, cuộn, nhập và đọc nhật ký trên bảng điều khiển. Công cụ này sử dụng một mô hình chuyên biệt để hoạt động trên các trang đang mở trong trình duyệt do Antigravity quản lý.

7. Trải nghiệm của người chỉnh sửa

Trình chỉnh sửa vẫn giữ được sự quen thuộc của VS Code. Nó bao gồm trình khám phá tệp tiêu chuẩn, tính năng làm nổi bật cú pháp và hệ sinh thái tiện ích.

Các tính năng chính của Trình chỉnh sửa:

  • Tự động hoàn thành: Đề xuất thông minh được chấp nhận bằng cách nhấn phím Tab.
  • Thẻ nhập: Đề xuất thêm các phần phụ thuộc bị thiếu.
  • Lệnh (Cmd + I): Kích hoạt tính năng hoàn thành dòng bằng ngôn ngữ tự nhiên.
  • Bảng điều khiển bên của tác nhân (Cmd + L): Bật/tắt bảng điều khiển của tác nhân để đặt câu hỏi hoặc tham khảo tệp bằng cách sử dụng @.

8. Đưa ra ý kiến phản hồi

Điểm cốt lõi của Antigravity là khả năng thu thập ý kiến phản hồi của bạn một cách dễ dàng. Các thành phần này là cách để bạn gửi ý kiến phản hồi cho nhân viên hỗ trợ dưới dạng nhận xét theo phong cách của Google Tài liệu.

Mỗi khi thêm nhận xét vào kế hoạch hoặc việc cần làm, hãy nhớ gửi nhận xét. Điều này sẽ hướng dẫn tác nhân theo hướng bạn muốn.

9. Xây dựng Kỹ năng vận hành KCC

Giờ đây, khi bạn đã hiểu rõ về nền tảng này, hãy cùng xây dựng KCC Ops Skill.

Kubernetes Config Connector (KCC) cho phép bạn quản lý các tài nguyên GCP dưới dạng các đối tượng K8s. Tuy nhiên, bạn cần có các biện pháp bảo vệ để ngăn chặn tình trạng sai lệch cấu hình, vi phạm quy định và vô tình tạo lại tài nguyên.

Bước 1: Cấu trúc Kỹ năng

Trong thư mục gốc của không gian làm việc, hãy tạo cấu trúc thư mục cho kỹ năng của bạn:

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

Bước 2: Soạn thảo SKILL.md (Phần nội dung)

SKILL.md xác định siêu dữ liệu và "Quy tắc vàng" cốt lõi cho tác nhân. Tạo .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
```

Bước 3: Triển khai Công cụ khoảng không quảng cáo

Tạo .agents/skills/kcc-ops/scripts/inventory.sh để khám phá các tài nguyên của 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

Bước 4: Thêm logic kiểm tra chính sách

Tạo .agents/skills/kcc-ops/scripts/vet-policy.sh. Tập lệnh này sẽ sử dụng gator để kiểm tra kỹ các tệp kê khai theo chính sách 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

Bước 5: Triển khai tính năng Bảo vệ trường bất biến

Đây là một biện pháp bảo vệ quan trọng. Tạo .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"

Bước 6: Khôi phục khẩn cấp (Xoá bắt buộc)

Tạo .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

Bước 7: Hoàn tất tài nguyên

Chạy tất cả tập lệnh:

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

10. Kiểm thử Skill mới

Bây giờ, hãy bắt đầu một cuộc trò chuyện mới và thử thách kỹ năng của bạn:

  1. Khám phá: @kcc-ops Show me all KCC resources in my cluster.
  2. Tuân thủ: Tạo tệp bucket.yaml bằng StorageBucket. Hỏi: @kcc-ops Vet my bucket.yaml manifest.
  3. An toàn: Cố gắng cập nhật location của một nhóm hiện có trong bucket.yaml. Hỏi: @kcc-ops Verify my bucket.yaml for immutable changes.

Hãy chú ý cách tác nhân chọn kịch bản phù hợp một cách thông minh và tuân theo "Quy tắc vàng" trong SKILL.md.

11. Bảo mật tác nhân

Việc cấp cho một tác nhân AI quyền truy cập vào thiết bị đầu cuối của bạn là một việc làm mạnh mẽ nhưng cần có các chế độ kiểm soát.

Chuyển đến Antigravity – Settings – Terminal (Antigravity – Cài đặt – Thiết bị đầu cuối) rồi khám phá Danh sách cho phép và Danh sách từ chối.

  • Danh sách cho phép: Thêm ls, kubectl get và các tập lệnh kỹ năng của bạn vào đây.
  • Danh sách từ chối: Thêm sudo, rm -rf hoặc các lệnh phá huỷ khác để đảm bảo tác nhân LUÔN yêu cầu cấp quyền.

12. Kết luận

Xin chúc mừng! Bạn đã chuyển từ việc cài đặt Antigravity sang xây dựng Kỹ năng vận hành KCC có độ trung thực cao.

Bạn đã tìm hiểu:

  • Cách mở rộng tác nhân bằng các công cụ bash tuỳ chỉnh.
  • Cách mã hoá "Quy tắc vàng" về hoạt động thành một SKILL.md.
  • Cách cung cấp các biện pháp bảo vệ cho việc quản lý cơ sở hạ tầng phức tạp.

Các bước tiếp theo

Mở rộng thư mục resources/policies bằng nhiều ràng buộc OPA hơn hoặc thêm tập lệnh check-health.sh để tự động hoá các quy trình kiểm tra trạng thái sẵn sàng của cụm!