🎉 DevOps Interview Prep Bundle is live — 1000+ Q&A across 20 topicsGet it →
All Articles

Build an AI Kubernetes Cluster Migration Assistant with Claude API

Migrating workloads between Kubernetes clusters — a version upgrade via blue-green, a cloud provider switch, a region move — means translating manifests, checking for provider-specific dependencies, and sequencing the cutover safely. Build an assistant that plans this with Claude API.

Shubham4 min read
Share:Tweet

Cluster-to-cluster migrations fail in predictable ways: a manifest references a cloud-specific storage class that doesn't exist on the new cluster, an ingress annotation is provider-specific, or a StatefulSet's PVC binding mode doesn't translate cleanly. This tool scans your manifests against the target cluster's actual capabilities and flags what needs translation before you cut over, not after.

Setup

bash
pip install anthropic kubernetes pyyaml

Source and Target Cluster Inspector

python
import anthropic
from kubernetes import client, config
import yaml
 
client_ai = anthropic.Anthropic()
 
 
def inspect_cluster_capabilities(context_name: str) -> dict:
    """Gather what the target cluster actually provides — storage classes,
    ingress controller, available CRDs — everything a migrated manifest
    might implicitly depend on."""
    config.load_kube_config(context=context_name)
    v1 = client.CoreV1Api()
    storage_v1 = client.StorageV1Api()
    apiextensions = client.ApiextensionsV1Api()
 
    return {
        "storage_classes": [sc.metadata.name for sc in storage_v1.list_storage_class().items],
        "default_storage_class": next(
            (sc.metadata.name for sc in storage_v1.list_storage_class().items
             if sc.metadata.annotations and sc.metadata.annotations.get("storageclass.kubernetes.io/is-default-class") == "true"),
            None
        ),
        "ingress_class": get_ingress_controller(v1),
        "installed_crds": [crd.metadata.name for crd in apiextensions.list_custom_resource_definition().items],
        "node_labels": get_common_node_labels(v1),
    }

Manifest Compatibility Analysis

python
ANALYZE_PROMPT = """Analyze whether these Kubernetes manifests will work
unmodified on the target cluster, or need translation.
 
Manifests:
{manifests}
 
Source cluster capabilities:
{source_capabilities}
 
Target cluster capabilities:
{target_capabilities}
 
For each manifest, check specifically for:
1. StorageClass references that don't exist on target (common when
   moving between cloud providers — gp3 vs pd-ssd vs premium-lrs)
2. Ingress class/annotations that are provider-specific (alb vs nginx vs gce)
3. CRDs the manifest depends on (operators, custom resources) that
   aren't installed on the target cluster
4. NodeSelector/affinity rules referencing labels that won't exist
   on the target's node pools
 
Respond with ONLY valid JSON:
{{"issues": [
  {{"file": "...", "issue": "...", "fix": "...", "blocking": true/false}}
], "safe_to_migrate_unmodified": [...]}}"""
 
 
def analyze_compatibility(manifests: list[dict], source_caps: dict, target_caps: dict) -> dict:
    response = client_ai.messages.create(
        model="claude-sonnet-5",
        max_tokens=3000,
        messages=[{
            "role": "user",
            "content": ANALYZE_PROMPT.format(
                manifests=manifests, source_capabilities=source_caps, target_capabilities=target_caps
            )
        }]
    )
    text = response.content[0].text.strip()
    if text.startswith("```"):
        text = text.split("```")[1].replace("json", "", 1).strip()
    import json
    return json.loads(text)

Migration Sequencing Plan

python
SEQUENCE_PROMPT = """Generate a safe migration sequence for moving these
workloads from the source to target cluster.
 
Workloads and their dependencies (what depends on what):
{workload_graph}
 
Stateful resources requiring data migration (databases, PVCs with data):
{stateful_resources}
 
Generate an ordered migration plan considering:
1. Stateless services can usually migrate in any order, or blue-green cut over
2. Stateful services need explicit data migration steps BEFORE traffic cutover
3. Services with tight coupling (shared database, synchronous calls) should
   migrate together, not have one half on each cluster during the transition
4. What can run on BOTH clusters simultaneously during migration (dual-write,
   traffic splitting) vs what requires a hard cutover
 
Format as an ordered runbook."""
 
 
def generate_migration_sequence(workload_graph: dict, stateful_resources: list) -> str:
    response = client_ai.messages.create(
        model="claude-sonnet-5",
        max_tokens=2500,
        messages=[{
            "role": "user",
            "content": SEQUENCE_PROMPT.format(workload_graph=workload_graph, stateful_resources=stateful_resources)
        }]
    )
    return response.content[0].text

Example Output

Compatibility Issues Found (3 blocking):

k8s/database-statefulset.yaml — storageClass "gp3" not found on target
  (GKE cluster uses "premium-rwo"). BLOCKING.
  Fix: change storageClassName to "premium-rwo", verify PVC access mode compatibility

k8s/api-ingress.yaml — annotation "alb.ingress.kubernetes.io/scheme" is
  AWS ALB Controller specific, target uses GKE Ingress. BLOCKING.
  Fix: rewrite as GCE-compatible ingress annotations or install ALB-compatible
  ingress class on target if staying multi-cloud is required

k8s/cache-operator-cr.yaml — depends on CRD "redisclusters.cache.example.com"
  which is not installed on target. BLOCKING.
  Fix: install the Redis operator on target cluster before migrating this resource

Migration Sequence:
1. Install missing CRDs and operators on target (Redis operator)
2. Migrate stateless services first: api-gateway, notification-service (blue-green)
3. Set up dual-write for the primary database (source stays authoritative)
4. Migrate database with replication, verify data consistency
5. Cut over stateful services (payments-api, orders-api) as a group — tightly
   coupled via shared database, must move together
6. Flip traffic weight from source to target over 24h with monitoring
7. Decommission source cluster resources only after 48h of stable target-only traffic

Why This Stays Advisory

Cluster migrations are exactly the kind of operation where a wrong automated decision (cutting over a stateful service before its data migration completes) causes real data loss or extended downtime. This tool's job is surfacing the compatibility gaps and generating a reviewable sequencing plan — the actual migration execution should always go through a human-reviewed runbook, ideally rehearsed in a staging environment first.


More Kubernetes platform tooling? Read our Build AI Kubernetes upgrade impact analyzer with Claude API and AWS EKS vs GKE vs AKS managed Kubernetes.

🔧

Today I Fixed

Short real fixes from production — posted daily

Browse fixes
Newsletter

Stay ahead of the curve

Get the latest DevOps, Kubernetes, AWS, and AI/ML guides delivered straight to your inbox. No spam — just practical engineering content.

Related Articles

Comments