jpskill.com
🎨 デザイン コミュニティ

kubernetes-python

Kubernetes APIをPythonで操作し、PodやDeploymentなどのリソース管理、自動化、コントローラー構築を効率的に行い、Kubernetesクラスターをプログラムで制御するSkill。

📜 元の英語説明(参考)

Kubernetes Python client for programmatic cluster management. Use when working with Kubernetes API, managing pods, deployments, services, namespaces, configmaps, secrets, jobs, CRDs, EKS clusters, watching resources, automating K8s operations, or building Kubernetes controllers.

🇯🇵 日本人クリエイター向け解説

一言でいうと

Kubernetes APIをPythonで操作し、PodやDeploymentなどのリソース管理、自動化、コントローラー構築を効率的に行い、Kubernetesクラスターをプログラムで制御するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o kubernetes-python.zip https://jpskill.com/download/9440.zip && unzip -o kubernetes-python.zip && rm kubernetes-python.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/9440.zip -OutFile "$d\kubernetes-python.zip"; Expand-Archive "$d\kubernetes-python.zip" -DestinationPath $d -Force; ri "$d\kubernetes-python.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して kubernetes-python.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → kubernetes-python フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Kubernetes Python Client Skill

Kubernetes の公式 Python クライアントライブラリです。自動化、カスタムツール、およびアプリケーション統合のために、Kubernetes API へのプログラムによるアクセスを提供します。

クイックスタート

インストール

pip install kubernetes

基本的な使い方

from kubernetes import client, config

# kubeconfig のロード
config.load_kube_config()

# API クライアントの作成
v1 = client.CoreV1Api()

# Pod のリスト表示
pods = v1.list_pod_for_all_namespaces(limit=10)
for pod in pods.items:
    print(f"{pod.metadata.namespace}/{pod.metadata.name}")

コアコンセプト

クライアント初期化パターン

ローカル開発 (kubeconfig を使用):

from kubernetes import client, config

config.load_kube_config()
v1 = client.CoreV1Api()

In-Cluster (Kubernetes 内部で実行):

from kubernetes import client, config

config.load_incluster_config()
v1 = client.CoreV1Api()

特定のコンテキスト:

config.load_kube_config(context='production-cluster')
v1 = client.CoreV1Api()

リソースタイプ別 API クライアント

API Client Resources Usage
CoreV1Api Pods, Services, ConfigMaps, Secrets, Namespaces, PVCs client.CoreV1Api()
AppsV1Api Deployments, StatefulSets, DaemonSets, ReplicaSets client.AppsV1Api()
BatchV1Api Jobs, CronJobs client.BatchV1Api()
NetworkingV1Api Ingresses, NetworkPolicies client.NetworkingV1Api()
CustomObjectsApi Custom Resources (CRDs) client.CustomObjectsApi()

一般的な操作

Deployment の作成

from kubernetes import client

apps_v1 = client.AppsV1Api()

deployment = client.V1Deployment(
    metadata=client.V1ObjectMeta(name="nginx-deployment"),
    spec=client.V1DeploymentSpec(
        replicas=3,
        selector=client.V1LabelSelector(
            match_labels={"app": "nginx"}
        ),
        template=client.V1PodTemplateSpec(
            metadata=client.V1ObjectMeta(labels={"app": "nginx"}),
            spec=client.V1PodSpec(
                containers=[
                    client.V1Container(
                        name="nginx",
                        image="nginx:1.14.2",
                        ports=[client.V1ContainerPort(container_port=80)]
                    )
                ]
            )
        )
    )
)

apps_v1.create_namespaced_deployment(
    namespace="default",
    body=deployment
)

リソースの読み取り

# 単一の Pod を読み取る
pod = v1.read_namespaced_pod(name="my-pod", namespace="default")

# ラベルセレクターで Pod をリスト表示
pods = v1.list_namespaced_pod(
    namespace="default",
    label_selector="app=nginx,env=production"
)

# フィールドセレクターで Pod をリスト表示
running_pods = v1.list_namespaced_pod(
    namespace="default",
    field_selector="status.phase=Running"
)

リソースの更新

Patch (部分的な更新、推奨):

deployment = apps_v1.read_namespaced_deployment(
    name="nginx-deployment",
    namespace="default"
)

deployment.spec.replicas = 5

apps_v1.patch_namespaced_deployment(
    name="nginx-deployment",
    namespace="default",
    body=deployment
)

Replace (完全な更新):

deployment.metadata.resource_version = existing.metadata.resource_version
apps_v1.replace_namespaced_deployment(
    name="nginx-deployment",
    namespace="default",
    body=deployment
)

リソースの削除

v1.delete_namespaced_pod(
    name="my-pod",
    namespace="default"
)

# グレースピリオドを指定して削除
apps_v1.delete_namespaced_deployment(
    name="nginx-deployment",
    namespace="default",
    grace_period_seconds=30
)

エラー処理

from kubernetes.client.rest import ApiException

try:
    pod = v1.read_namespaced_pod(name="my-pod", namespace="default")
except ApiException as e:
    if e.status == 404:
        print("Pod not found")
    elif e.status == 403:
        print("Permission denied")
    else:
        print(f"API error: {e}")

作成または更新パターン (冪等性)

from kubernetes.client.rest import ApiException

def create_or_update_deployment(apps_v1, namespace, deployment):
    """Create deployment if it doesn't exist, otherwise update it."""
    name = deployment.metadata.name

    try:
        existing = apps_v1.read_namespaced_deployment(
            name=name,
            namespace=namespace
        )

        deployment.metadata.resource_version = existing.metadata.resource_version
        response = apps_v1.replace_namespaced_deployment(
            name=name,
            namespace=namespace,
            body=deployment
        )
        print(f"Deployment {name} updated")
        return response

    except ApiException as e:
        if e.status == 404:
            response = apps_v1.create_namespaced_deployment(
                namespace=namespace,
                body=deployment
            )
            print(f"Deployment {name} created")
            return response
        else:
            raise

リソースの監視

リソースの変更をリアルタイムで監視します。

from kubernetes import watch

w = watch.Watch()

# タイムアウトを指定して Pod を監視
for event in w.stream(
    v1.list_namespaced_pod,
    namespace="default",
    timeout_seconds=60
):
    print(f"{event['type']}: {event['object'].metadata.name}")

w.stop()

イベントタイプ

  • ADDED: リソースが作成されました
  • MODIFIED: リソースが更新されました
  • DELETED: リソースが削除されました
  • ERROR: 監視エラーが発生しました

ConfigMap と Secret の操作

ConfigMap

configmap = client.V1ConfigMap(
    metadata=client.V1ObjectMeta(name="my-config"),
    data={"key1": "value1", "key2": "value2"}
)

v1.create_namespaced_config_map(
    namespace="default",
    body=configmap
)

Secret


import base64

secret = client.V1Secret(
    metadata=client.V1ObjectMeta(name="my-secret"),
    type="Opaque",
    data={
        "username": base64.b64encode(b"admin").decode('utf-8'),
        "pa
(原文がここで切り詰められています)
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Kubernetes Python Client Skill

Official Python client library for Kubernetes, providing programmatic access to the Kubernetes API for automation, custom tooling, and application integration.

Quick Start

Installation

pip install kubernetes

Basic Usage

from kubernetes import client, config

# Load kubeconfig
config.load_kube_config()

# Create API client
v1 = client.CoreV1Api()

# List pods
pods = v1.list_pod_for_all_namespaces(limit=10)
for pod in pods.items:
    print(f"{pod.metadata.namespace}/{pod.metadata.name}")

Core Concepts

Client Initialization Patterns

Local Development (using kubeconfig):

from kubernetes import client, config

config.load_kube_config()
v1 = client.CoreV1Api()

In-Cluster (running inside Kubernetes):

from kubernetes import client, config

config.load_incluster_config()
v1 = client.CoreV1Api()

Specific Context:

config.load_kube_config(context='production-cluster')
v1 = client.CoreV1Api()

API Clients by Resource Type

API Client Resources Usage
CoreV1Api Pods, Services, ConfigMaps, Secrets, Namespaces, PVCs client.CoreV1Api()
AppsV1Api Deployments, StatefulSets, DaemonSets, ReplicaSets client.AppsV1Api()
BatchV1Api Jobs, CronJobs client.BatchV1Api()
NetworkingV1Api Ingresses, NetworkPolicies client.NetworkingV1Api()
CustomObjectsApi Custom Resources (CRDs) client.CustomObjectsApi()

Common Operations

Creating a Deployment

from kubernetes import client

apps_v1 = client.AppsV1Api()

deployment = client.V1Deployment(
    metadata=client.V1ObjectMeta(name="nginx-deployment"),
    spec=client.V1DeploymentSpec(
        replicas=3,
        selector=client.V1LabelSelector(
            match_labels={"app": "nginx"}
        ),
        template=client.V1PodTemplateSpec(
            metadata=client.V1ObjectMeta(labels={"app": "nginx"}),
            spec=client.V1PodSpec(
                containers=[
                    client.V1Container(
                        name="nginx",
                        image="nginx:1.14.2",
                        ports=[client.V1ContainerPort(container_port=80)]
                    )
                ]
            )
        )
    )
)

apps_v1.create_namespaced_deployment(
    namespace="default",
    body=deployment
)

Reading Resources

# Read single pod
pod = v1.read_namespaced_pod(name="my-pod", namespace="default")

# List pods with label selector
pods = v1.list_namespaced_pod(
    namespace="default",
    label_selector="app=nginx,env=production"
)

# List pods with field selector
running_pods = v1.list_namespaced_pod(
    namespace="default",
    field_selector="status.phase=Running"
)

Updating Resources

Patch (partial update, preferred):

deployment = apps_v1.read_namespaced_deployment(
    name="nginx-deployment",
    namespace="default"
)

deployment.spec.replicas = 5

apps_v1.patch_namespaced_deployment(
    name="nginx-deployment",
    namespace="default",
    body=deployment
)

Replace (full update):

deployment.metadata.resource_version = existing.metadata.resource_version
apps_v1.replace_namespaced_deployment(
    name="nginx-deployment",
    namespace="default",
    body=deployment
)

Deleting Resources

v1.delete_namespaced_pod(
    name="my-pod",
    namespace="default"
)

# Delete with grace period
apps_v1.delete_namespaced_deployment(
    name="nginx-deployment",
    namespace="default",
    grace_period_seconds=30
)

Error Handling

from kubernetes.client.rest import ApiException

try:
    pod = v1.read_namespaced_pod(name="my-pod", namespace="default")
except ApiException as e:
    if e.status == 404:
        print("Pod not found")
    elif e.status == 403:
        print("Permission denied")
    else:
        print(f"API error: {e}")

Create or Update Pattern (Idempotent)

from kubernetes.client.rest import ApiException

def create_or_update_deployment(apps_v1, namespace, deployment):
    """Create deployment if it doesn't exist, otherwise update it."""
    name = deployment.metadata.name

    try:
        existing = apps_v1.read_namespaced_deployment(
            name=name,
            namespace=namespace
        )

        deployment.metadata.resource_version = existing.metadata.resource_version
        response = apps_v1.replace_namespaced_deployment(
            name=name,
            namespace=namespace,
            body=deployment
        )
        print(f"Deployment {name} updated")
        return response

    except ApiException as e:
        if e.status == 404:
            response = apps_v1.create_namespaced_deployment(
                namespace=namespace,
                body=deployment
            )
            print(f"Deployment {name} created")
            return response
        else:
            raise

Watch Resources

Watch for resource changes in real-time:

from kubernetes import watch

w = watch.Watch()

# Watch pods with timeout
for event in w.stream(
    v1.list_namespaced_pod,
    namespace="default",
    timeout_seconds=60
):
    print(f"{event['type']}: {event['object'].metadata.name}")

w.stop()

Event Types

  • ADDED: Resource was created
  • MODIFIED: Resource was updated
  • DELETED: Resource was deleted
  • ERROR: Watch error occurred

Working with ConfigMaps and Secrets

ConfigMap

configmap = client.V1ConfigMap(
    metadata=client.V1ObjectMeta(name="my-config"),
    data={"key1": "value1", "key2": "value2"}
)

v1.create_namespaced_config_map(
    namespace="default",
    body=configmap
)

Secret

import base64

secret = client.V1Secret(
    metadata=client.V1ObjectMeta(name="my-secret"),
    type="Opaque",
    data={
        "username": base64.b64encode(b"admin").decode('utf-8'),
        "password": base64.b64encode(b"secretpass").decode('utf-8')
    }
)

v1.create_namespaced_secret(
    namespace="default",
    body=secret
)

Custom Resources (CRDs)

custom_api = client.CustomObjectsApi()

# List custom resources
custom_objects = custom_api.list_namespaced_custom_object(
    group="example.com",
    version="v1",
    namespace="default",
    plural="mycustomresources"
)

# Create custom resource
custom_object = {
    "apiVersion": "example.com/v1",
    "kind": "MyCustomResource",
    "metadata": {"name": "my-cr"},
    "spec": {"replicas": 3}
}

custom_api.create_namespaced_custom_object(
    group="example.com",
    version="v1",
    namespace="default",
    plural="mycustomresources",
    body=custom_object
)

Production Patterns

Timeout Configuration

# Set timeout for operations
pods = v1.list_namespaced_pod(
    namespace="default",
    _request_timeout=10  # 10 second timeout
)

Pagination for Large Lists

def list_all_pods_paginated(namespace, page_size=100):
    """List all pods with pagination."""
    all_pods = []
    continue_token = None

    while True:
        if continue_token:
            response = v1.list_namespaced_pod(
                namespace=namespace,
                limit=page_size,
                _continue=continue_token
            )
        else:
            response = v1.list_namespaced_pod(
                namespace=namespace,
                limit=page_size
            )

        all_pods.extend(response.items)

        continue_token = response.metadata._continue
        if not continue_token:
            break

    return all_pods

Server-Side Filtering

# Good: Filter server-side (efficient)
running_pods = v1.list_pod_for_all_namespaces(
    field_selector='status.phase=Running'
)

# Bad: Fetch all and filter client-side (inefficient)
all_pods = v1.list_pod_for_all_namespaces()
running_pods = [p for p in all_pods.items if p.status.phase == 'Running']

Reference Documentation

For detailed information, see:

Key Features

Strengths

  • Official Kubernetes client (SIG API Machinery)
  • Complete API coverage (all resources)
  • Production-ready and battle-tested
  • Multiple authentication methods
  • Real-time watch/stream capabilities
  • Full CRD support

Considerations

  • Auto-generated code (less Pythonic)
  • Performance can degrade in very large clusters (3000+ resources)
  • No native async support (use kubernetes_asyncio package)
  • EKS requires manual token refresh (15-minute expiry)

Version Compatibility

Match client version to Kubernetes cluster version:

Client Version K8s 1.29 K8s 1.30 K8s 1.31
29.y.z +- -
30.y.z +- +-
31.y.z +- +-
  • ✓ = Exact feature/API parity
  • +- = Most APIs work, some new/removed
  • - = Not recommended

Security Best Practices

  1. Least Privilege: Never use cluster-admin for applications
  2. RBAC: Use Roles (namespaced) instead of ClusterRoles when possible
  3. Secrets: Don't log secret data, load credentials from environment
  4. SSL Verification: Always verify SSL in production (verify_ssl=True)
  5. In-Cluster Config: Use service accounts for in-cluster applications

Quick Reference Links