Kubernetes連携



はじめに

本章では、Qmonus SDKからKubernetesを操作する方法を解説します。Qmonus SDKとKubernetesを連携させることでアプリケーションのランタイムでコンテナ操作が可能になります。これによって例えばFaaS型アプリケーション、CICDツールの作成やテストケースのpreparation/cleanupでコンテナ化された周辺モックを生成/削除するなど、動的なインフラ制御によるアプリケーションのスケールが可能になります。

Warning

本機能はQmonus SDKが所属しているKubernetesクラスタ(インクラスタ)をスコープとして提供されます。Qmonus SDKのKubernetes連携機能において、リモートKubernetesクラスタのサポート予定はありません。

マニフェストファイルのCRUDについて

Qmonus SDKでは、https://github.com/instrumenta/kubernetes-json-schemaで定義されているスキーマを読み込み、Kubernetesのマニフェストを編集するGUIを提供しています。ここで作成したマニフェストは、そのままKubernetesに適用したり、Jinja2テンプレート形式で変数を自由に埋め込み、Templateサービスに登録できます。制御対象のKubernetesエンドポイントは、Kubernetesクラスタサービスに登録することで制御クライアントを利用できるようになります。Kubernetes制御クライアントを使うことで、事前登録したマニフェストテンプレートを使ったデプロイが可能になります。

Kubernetesクラスタ

Kubernetesクラスタは、Qmonus SDKが制御するKubernetesのエンドポイントとAPIトークンを管理するリソースです。
REPLやカスタムスクリプトからの操作には、Kube組込オブジェクトを利用します。

新規作成

Kubernetesクラスタを作成してデータベースに保存します。

  • API
POST /kubernetesV1
{
  "type": "object",
  "required": [
    "category",
    "name",
    "endpoint",
    "token"
  ],
  "properties": {
    "category": {
      "type": "string",
      "default": "default"
    },
    "name": {
      "type": "string",
    },
    "endpoint": {
      "type": "string",
      "default": "https://kubernetes.docker.internal:6443"
    },
    "token": {
      "type": "string"
    },
    "verify_ssl": {
      "type": "boolean",
      "default": false
    },
    "ssl_ca_cert": {
      "type": "string"
    }
  }
}


  • スクリプト
k = await Kube.generate(name="local", token=<TOKEN>)


変更

Kubernetesクラスタの情報を変更してデータベースに保存します。

  • API
PUT /kubernetesV1/{name}
{
  "type": "object",
  "required": [
    "category",
    "name",
    "endpoint",
    "token"
  ],
  "properties": {
    "category": {
      "type": "string"
    },
    "name": {
      "type": "string",
    },
    "endpoint": {
      "type": "string",
    },
    "token": {
      "type": "string",
    },
    "verify_ssl": {
      "type": "boolean",
    },
    "ssl_ca_cert": {
      "type": "string",
    }
  }
}


  • スクリプト
k = await Kube.load("local")...インスタンス読み出し
k.category = "tutorial"
await k.save()


削除

Kubernetesクラスタの情報をデータベースから削除します。

  • API
DELETE /kubernetesV1/{name}


  • スクリプト
k = await Kube.load("local")
await k.destroy()


取得

Kubernetesクラスタの情報をデータベースから取得します。

  • API
GET /kubernetesV1/{name}


  • スクリプト
k = await Kube.load("local")


一覧

Kubernetesクラスタの一覧をデータベースから取得します。

  • API
GET /kubernetesV1


  • スクリプト
ks = await Kube.retrieve()


名前空間に属さないKubernetesリソースのCRUDについて

名前空間に属さないKubernetesリソースのCRUDは、以下のパスで共通です。リソース種別は、CoreResourceKindで指定します。
対象リソースは、kubectl api-resources --namespaced=falseで出力されるオブジェクトです。

% kubectl api-resources --namespaced=false
NAME                              SHORTNAMES   APIGROUP                       NAMESPACED   KIND
componentstatuses                 cs                                          false        ComponentStatus
namespaces                        ns                                          false        Namespace
nodes                             no                                          false        Node
persistentvolumes                 pv                                          false        PersistentVolume
mutatingwebhookconfigurations                  admissionregistration.k8s.io   false        MutatingWebhookConfiguration
validatingwebhookconfigurations                admissionregistration.k8s.io   false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io           false        CustomResourceDefinition
apiservices                                    apiregistration.k8s.io         false        APIService
tokenreviews                                   authentication.k8s.io          false        TokenReview
selfsubjectaccessreviews                       authorization.k8s.io           false        SelfSubjectAccessReview
selfsubjectrulesreviews                        authorization.k8s.io           false        SelfSubjectRulesReview
subjectaccessreviews                           authorization.k8s.io           false        SubjectAccessReview
certificatesigningrequests        csr          certificates.k8s.io            false        CertificateSigningRequest
ingressclasses                                 networking.k8s.io              false        IngressClass
runtimeclasses                                 node.k8s.io                    false        RuntimeClass
podsecuritypolicies               psp          policy                         false        PodSecurityPolicy
clusterrolebindings                            rbac.authorization.k8s.io      false        ClusterRoleBinding
clusterroles                                   rbac.authorization.k8s.io      false        ClusterRole
priorityclasses                   pc           scheduling.k8s.io              false        PriorityClass
csidrivers                                     storage.k8s.io                 false        CSIDriver
csinodes                                       storage.k8s.io                 false        CSINode
storageclasses                    sc           storage.k8s.io                 false        StorageClass
volumeattachments                              storage.k8s.io                 false        VolumeAttachment


リソースの作成

指定されたマニフェストでリソースを作成します。

  • API
POST /kubernetesv1/{name}/{CoreResouceKind}
{"type": "object",
 "definitions": {"manifest": {"type": "object",
                              "description": "マニフェストファイルをデプロイします",
                              "required": ["manifest"],
                              "properties": {"manifest": {"type": "string", "format": "yaml"}}},
                 "template": {"type": "object",
                              "description": "マニフェストテンプレートファイルにparamsをレンダリングしてデプロイします",
                              "required": ["tag", "params"],
                              "properties": {"tag": {"type": "string", "format": "template tag"},
                                             "params": {"type": "object"}}}},
 "oneOf": [{"$ref": "#/definitions/manifest"},
           {"$ref": "#/definitions/template"}]}


リソースの変更

指定されたリソースにマニフェストを適用してリソースを更新します。

  • API
PUT /kubernetesv1/{name}/{CoreResouceKind}/{CoreResourceName}
{"type": "object",
 "definitions": {"manifest": {"type": "object",
                              "description": "マニフェストファイルをデプロイします",
                              "required": ["manifest"],
                              "properties": {"manifest": {"type": "string", "format": "yaml"}}},
                 "template": {"type": "object",
                              "description": "マニフェストテンプレートファイルにparamsをレンダリングしてデプロイします",
                              "required": ["tag", "params"],
                              "properties": {"tag": {"type": "string", "format": "template tag"},
                                             "params": {"type": "object"}}}},
 "oneOf": [{"$ref": "#/definitions/manifest"},
           {"$ref": "#/definitions/template"}]}


リソースの削除

指定されたリソースを削除します。

DELETE /kubernetesv1/{name}/{CoreResouceKind}/{CoreResourceName}


リソースの一覧

指定されたリソースの一覧を取得します。

GET /kubernetesv1/{name}/{CoreResourceKind}


リソースの取得

指定されたリソースを取得します。

GET /kubernetesv1/{name}/{CoreResourceKind}/{CoreResourceName}


サンプル

  • ネームスペースを作成して削除する例
>>> k = await Kube.load("local")↵
>>> m = k8s.V1Namespace(api_version="v1", kind="Namespace", metadata=k8s.V1ObjectMeta(name="sample-namespace"))↵
>>> y = await k.to_yaml(m)↵
>>> print(y)↵
... ↵
↵
apiVersion: v1
kind: Namespace
metadata:
  name: sample-namespace
>>> r = await k.createNamespace(m)↵
... ↵
↵
>>> print(r)↵
... ↵
↵
{'api_version': 'v1',
 'kind': 'Namespace',
 'metadata': {'annotations': None,
              'cluster_name': None,
              'creation_timestamp': datetime.datetime(2021, 4, 27, 4, 45, 25, tzinfo=tzutc()),
              'deletion_grace_period_seconds': None,
              'deletion_timestamp': None,
              'finalizers': None,
              'generate_name': None,
              'generation': None,
              'labels': None,
              'managed_fields': [{'api_version': 'v1',
                                  'fields_type': 'FieldsV1',
                                  'fields_v1': {'f:status': {'f:phase': {}}},
                                  'manager': 'OpenAPI-Generator',
                                  'operation': 'Update',
                                  'time': datetime.datetime(2021, 4, 27, 4, 45, 25, tzinfo=tzutc())}],
              'name': 'sample-namespace',
              'namespace': None,
              'owner_references': None,
              'resource_version': '412469',
              'self_link': '/api/v1/namespaces/sample-namespace',
              'uid': 'e64c4152-87ca-46b1-aef0-03da18dc6909'},
 'spec': {'finalizers': ['kubernetes']},
 'status': {'conditions': None, 'phase': 'Active'}}
>>> r = await k.deleteNamespace("sample-namespace")↵
... ↵
↵
>>> print(r)↵
... ↵
↵
{'api_version': 'v1',
 'code': None,
 'details': None,
 'kind': 'Namespace',
 'message': None,
 'metadata': {'_continue': None,
              'remaining_item_count': None,
              'resource_version': '412719',
              'self_link': '/api/v1/namespaces/sample-namespace'},
 'reason': None,
 'status': "{'phase': 'Terminating'}"}
>>>


  • ConfigMapを作成して削除する例
>>> k = await Kube.load("local")↵
... ↵
↵
>>> m = k8s.V1ConfigMap(api_version="v1",↵
...                     kind="ConfigMap",↵
...                     data=dict(host="localhost", port="19099"),↵
...                     metadata=k8s.V1ObjectMeta(name="sample-configmap"))↵
... ↵
↵
>>> y = await k.to_yaml(m)↵
>>> print(y)↵
... ↵
↵
apiVersion: v1
data:
  host: localhost
  port: '19099'
kind: ConfigMap
metadata:
  name: sample-configmap
>>> r = await k.createConfigMap(manifest)↵
... print(r)↵
... ↵
↵
{'api_version': 'v1',
 'binary_data': None,
 'data': {'host': 'localhost', 'port': '19099'},
 'kind': 'ConfigMap',
 'metadata': {'annotations': None,
              'cluster_name': None,
              'creation_timestamp': datetime.datetime(2021, 4, 27, 5, 14, 52, tzinfo=tzutc()),
              'deletion_grace_period_seconds': None,
              'deletion_timestamp': None,
              'finalizers': None,
              'generate_name': None,
              'generation': None,
              'labels': None,
              'managed_fields': [{'api_version': 'v1',
                                  'fields_type': 'FieldsV1',
                                  'fields_v1': {'f:data': {'.': {},
                                                           'f:host': {},
                                                           'f:port': {}}},
                                  'manager': 'OpenAPI-Generator',
                                  'operation': 'Update',
                                  'time': datetime.datetime(2021, 4, 27, 5, 14, 52, tzinfo=tzutc())}],
              'name': 'sample-configmap',
              'namespace': 'default',
              'owner_references': None,
              'resource_version': '415535',
              'self_link': '/api/v1/namespaces/default/configmaps/sample-configmap',
              'uid': '5ccb934e-c2cf-4386-ad06-8f7ff743c038'}}
>>> r = await k.deleteConfigMap("sample-configmap")↵
... print(r)↵
... ↵
↵
{'api_version': 'v1',
 'code': None,
 'details': None,
 'kind': 'ConfigMap',
 'message': None,
 'metadata': {'_continue': None,
              'remaining_item_count': None,
              'resource_version': '415597',
              'self_link': '/api/v1/namespaces/default/configmaps/sample-configmap'},
 'reason': None,
 'status': None}
>>>


名前空間に属するKubernetesリソースのCRUDについて

名前空間に属するKubernetesリソースのCRUDは、以下のパスで共通です。リソース種別は、Resourcekindで指定します。
対象リソースは、kubectl api-resources --namespaced=trueで出力されるオブジェクトです。

% kubectl api-resources --namespaced=true
NAME                        SHORTNAMES   APIGROUP                    NAMESPACED   KIND
bindings                                                             true         Binding
configmaps                  cm                                       true         ConfigMap
endpoints                   ep                                       true         Endpoints
events                      ev                                       true         Event
limitranges                 limits                                   true         LimitRange
persistentvolumeclaims      pvc                                      true         PersistentVolumeClaim
pods                        po                                       true         Pod
podtemplates                                                         true         PodTemplate
replicationcontrollers      rc                                       true         ReplicationController
resourcequotas              quota                                    true         ResourceQuota
secrets                                                              true         Secret
serviceaccounts             sa                                       true         ServiceAccount
services                    svc                                      true         Service
controllerrevisions                      apps                        true         ControllerRevision
daemonsets                  ds           apps                        true         DaemonSet
deployments                 deploy       apps                        true         Deployment
replicasets                 rs           apps                        true         ReplicaSet
statefulsets                sts          apps                        true         StatefulSet
localsubjectaccessreviews                authorization.k8s.io        true         LocalSubjectAccessReview
horizontalpodautoscalers    hpa          autoscaling                 true         HorizontalPodAutoscaler
cronjobs                    cj           batch                       true         CronJob
jobs                                     batch                       true         Job
leases                                   coordination.k8s.io         true         Lease
endpointslices                           discovery.k8s.io            true         EndpointSlice
events                      ev           events.k8s.io               true         Event
ingresses                   ing          extensions                  true         Ingress
ingresses                   ing          networking.k8s.io           true         Ingress
networkpolicies             netpol       networking.k8s.io           true         NetworkPolicy
poddisruptionbudgets        pdb          policy                      true         PodDisruptionBudget
rolebindings                             rbac.authorization.k8s.io   true         RoleBinding
roles                                    rbac.authorization.k8s.io   true         Role


リソースの作成

指定されたマニフェストでリソースを作成します。

  • API
POST /kubernetesv1/{name}/Namespace/{namespace}/{ResourceKind}
{"type": "object",
 "definitions": {"manifest": {"type": "object",
                              "description": "マニフェストファイルをデプロイします",
                              "required": ["manifest"],
                              "properties": {"manifest": {"type": "string", "format": "yaml"}}},
                 "template": {"type": "object",
                              "description": "マニフェストテンプレートファイルにparamsをレンダリングしてデプロイします",
                              "required": ["tag", "params"],
                              "properties": {"tag": {"type": "string", "format": "template tag"},
                                             "params": {"type": "object"}}}},
 "oneOf": [{"$ref": "#/definitions/manifest"},
           {"$ref": "#/definitions/template"}]}


リソースの変更

指定されたリソースにマニフェストを適用してリソースを更新します。

  • API
PUT /kubernetesv1/{name}/Namespace/{namespace}/{ResourceKind}/{AppResourceName}
{"type": "object",
 "definitions": {"manifest": {"type": "object",
                              "description": "マニフェストファイルをデプロイします",
                              "required": ["manifest"],
                              "properties": {"manifest": {"type": "string", "format": "yaml"}}},
                 "template": {"type": "object",
                              "description": "マニフェストテンプレートファイルにparamsをレンダリングしてデプロイします",
                              "required": ["tag", "params"],
                              "properties": {"tag": {"type": "string", "format": "template tag"},
                                             "params": {"type": "object"}}}},
 "oneOf": [{"$ref": "#/definitions/manifest"},
           {"$ref": "#/definitions/template"}]}


リソースの削除

指定されたリソースを削除します。

DELETE /kubernetesv1/{name}/Namespace/{namespace}/{ResourceKind}/{AppResourceName}


リソースの一覧

指定されたリソースの一覧を取得します。

GET /kubernetesv1/{name}/Namespace/{namespace}/{ResourceKind}


リソースの取得

指定されたリソースを取得します。

GET /kubernetesv1/{name}/Namespace/{namespace}/{ResourceKind}/{AppResourceName}


サンプル

  • Deploymentを作成して削除する例
>>> k = await Kube.load("local")↵
... ↵
↵
>>> container = k8s.V1Container(name="nginx",↵
...                             image="nginx:1.15.4",↵
...                             ports=[k8s.V1ContainerPort(container_port=80)],↵
...                             resources=k8s.V1ResourceRequirements(requests={"cpu": "100m",↵
...                                                                            "memory": "200Mi"},↵
...                                                                  limits={"cpu": "500m",↵
...                                                                          "memory": "500Mi"}))↵
... template = k8s.V1PodTemplateSpec(metadata=k8s.V1ObjectMeta(labels={"app": "nginx"}),↵
...                                  spec=k8s.V1PodSpec(containers=[container]))↵
... spec = k8s.V1DeploymentSpec(replicas=3,↵
...                             template=template,↵
...                             selector={"matchLabels": {"app": "nginx"}})↵
... m = k8s.V1Deployment(api_version="apps/v1",↵
...                      kind="Deployment",↵
...                      metadata=k8s.V1ObjectMeta(name="nginx-deployment"),↵
...                      spec=spec)↵
... ↵
↵
>>> y = await k.to_yaml(m)↵
>>> print(y)↵
... ↵
↵
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx:1.15.4
        name: nginx
        ports:
        - containerPort: 80
        resources:
          limits:
            cpu: 500m
            memory: 500Mi
          requests:
            cpu: 100m
            memory: 200Mi
>>> r = await k.getNamespace("default").createDeployment(manifest)↵
... ↵
↵
>>> r = await k.getNamespace("default").listDeployment()↵
... for i in r.items:↵
...     if i.metadata.name == "nginx-deployment":↵
...         print(json.dumps(i.to_dict(), indent=4))↵
...         break↵
... ↵
↵
{
    "api_version": null,
    "kind": null,
    "metadata": {
        "annotations": {
            "deployment.kubernetes.io/revision": "1"
        },
        "cluster_name": null,
        "creation_timestamp": "2021-04-27T07:45:45+00:00",
        "deletion_grace_period_seconds": null,
        "deletion_timestamp": null,
        "finalizers": null,
        "generate_name": null,
        "generation": 1,
        "labels": null,
        "managed_fields": [
            {
                "api_version": "apps/v1",
                "fields_type": "FieldsV1",
                "fields_v1": {
                    "f:spec": {
                        "f:progressDeadlineSeconds": {},
                        "f:replicas": {},
                        "f:revisionHistoryLimit": {},
                        "f:selector": {
                            "f:matchLabels": {
                                ".": {},
                                "f:app": {}
                            }
                        },
                        "f:strategy": {
                            "f:rollingUpdate": {
                                ".": {},
                                "f:maxSurge": {},
                                "f:maxUnavailable": {}
                            },
                            "f:type": {}
                        },
                        "f:template": {
                            "f:metadata": {
                                "f:labels": {
                                    ".": {},
                                    "f:app": {}
                                }
                            },
                            "f:spec": {
                                "f:containers": {
                                    "k:{\"name\":\"nginx\"}": {
                                        ".": {},
                                        "f:image": {},
                                        "f:imagePullPolicy": {},
                                        "f:name": {},
                                        "f:ports": {
                                            ".": {},
                                            "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": {
                                                ".": {},
                                                "f:containerPort": {},
                                                "f:protocol": {}
                                            }
                                        },
                                        "f:resources": {
                                            ".": {},
                                            "f:limits": {
                                                ".": {},
                                                "f:cpu": {},
                                                "f:memory": {}
                                            },
                                            "f:requests": {
                                                ".": {},
                                                "f:cpu": {},
                                                "f:memory": {}
                                            }
                                        },
                                        "f:terminationMessagePath": {},
                                        "f:terminationMessagePolicy": {}
                                    }
                                },
                                "f:dnsPolicy": {},
                                "f:restartPolicy": {},
                                "f:schedulerName": {},
                                "f:securityContext": {},
                                "f:terminationGracePeriodSeconds": {}
                            }
                        }
                    }
                },
                "manager": "OpenAPI-Generator",
                "operation": "Update",
                "time": "2021-04-27T07:45:45+00:00"
            },
            {
                "api_version": "apps/v1",
                "fields_type": "FieldsV1",
                "fields_v1": {
                    "f:metadata": {
                        "f:annotations": {
                            ".": {},
                            "f:deployment.kubernetes.io/revision": {}
                        }
                    },
                    "f:status": {
                        "f:availableReplicas": {},
                        "f:conditions": {
                            ".": {},
                            "k:{\"type\":\"Available\"}": {
                                ".": {},
                                "f:lastTransitionTime": {},
                                "f:lastUpdateTime": {},
                                "f:message": {},
                                "f:reason": {},
                                "f:status": {},
                                "f:type": {}
                            },
                            "k:{\"type\":\"Progressing\"}": {
                                ".": {},
                                "f:lastTransitionTime": {},
                                "f:lastUpdateTime": {},
                                "f:message": {},
                                "f:reason": {},
                                "f:status": {},
                                "f:type": {}
                            }
                        },
                        "f:observedGeneration": {},
                        "f:readyReplicas": {},
                        "f:replicas": {},
                        "f:updatedReplicas": {}
                    }
                },
                "manager": "kube-controller-manager",
                "operation": "Update",
                "time": "2021-04-27T07:45:51+00:00"
            }
        ],
        "name": "nginx-deployment",
        "namespace": "default",
        "owner_references": null,
        "resource_version": "431245",
        "self_link": "/apis/apps/v1/namespaces/default/deployments/nginx-deployment",
        "uid": "8c4f5348-a1ac-4a3c-81f3-f70136b73f13"
    },
    "spec": {
        "min_ready_seconds": null,
        "paused": null,
        "progress_deadline_seconds": 600,
        "replicas": 3,
        "revision_history_limit": 10,
        "selector": {
            "match_expressions": null,
            "match_labels": {
                "app": "nginx"
            }
        },
        "strategy": {
            "rolling_update": {
                "max_surge": "25%",
                "max_unavailable": "25%"
            },
            "type": "RollingUpdate"
        },
        "template": {
            "metadata": {
                "annotations": null,
                "cluster_name": null,
                "creation_timestamp": null,
                "deletion_grace_period_seconds": null,
                "deletion_timestamp": null,
                "finalizers": null,
                "generate_name": null,
                "generation": null,
                "labels": {
                    "app": "nginx"
                },
                "managed_fields": null,
                "name": null,
                "namespace": null,
                "owner_references": null,
                "resource_version": null,
                "self_link": null,
                "uid": null
            },
            "spec": {
                "active_deadline_seconds": null,
                "affinity": null,
                "automount_service_account_token": null,
                "containers": [
                    {
                        "args": null,
                        "command": null,
                        "env": null,
                        "env_from": null,
                        "image": "nginx:1.15.4",
                        "image_pull_policy": "IfNotPresent",
                        "lifecycle": null,
                        "liveness_probe": null,
                        "name": "nginx",
                        "ports": [
                            {
                                "container_port": 80,
                                "host_ip": null,
                                "host_port": null,
                                "name": null,
                                "protocol": "TCP"
                            }
                        ],
                        "readiness_probe": null,
                        "resources": {
                            "limits": {
                                "cpu": "500m",
                                "memory": "500Mi"
                            },
                            "requests": {
                                "cpu": "100m",
                                "memory": "200Mi"
                            }
                        },
                        "security_context": null,
                        "startup_probe": null,
                        "stdin": null,
                        "stdin_once": null,
                        "termination_message_path": "/dev/termination-log",
                        "termination_message_policy": "File",
                        "tty": null,
                        "volume_devices": null,
                        "volume_mounts": null,
                        "working_dir": null
                    }
                ],
                "dns_config": null,
                "dns_policy": "ClusterFirst",
                "enable_service_links": null,
                "ephemeral_containers": null,
                "host_aliases": null,
                "host_ipc": null,
                "host_network": null,
                "host_pid": null,
                "hostname": null,
                "image_pull_secrets": null,
                "init_containers": null,
                "node_name": null,
                "node_selector": null,
                "overhead": null,
                "preemption_policy": null,
                "priority": null,
                "priority_class_name": null,
                "readiness_gates": null,
                "restart_policy": "Always",
                "runtime_class_name": null,
                "scheduler_name": "default-scheduler",
                "security_context": {
                    "fs_group": null,
                    "run_as_group": null,
                    "run_as_non_root": null,
                    "run_as_user": null,
                    "se_linux_options": null,
                    "supplemental_groups": null,
                    "sysctls": null,
                    "windows_options": null
                },
                "service_account": null,
                "service_account_name": null,
                "share_process_namespace": null,
                "subdomain": null,
                "termination_grace_period_seconds": 30,
                "tolerations": null,
                "topology_spread_constraints": null,
                "volumes": null
            }
        }
    },
    "status": {
        "available_replicas": 3,
        "collision_count": null,
        "conditions": [
            {
                "last_transition_time": "2021-04-27T07:45:51+00:00",
                "last_update_time": "2021-04-27T07:45:51+00:00",
                "message": "Deployment has minimum availability.",
                "reason": "MinimumReplicasAvailable",
                "status": "True",
                "type": "Available"
            },
            {
                "last_transition_time": "2021-04-27T07:45:45+00:00",
                "last_update_time": "2021-04-27T07:45:51+00:00",
                "message": "ReplicaSet \"nginx-deployment-5dd6f4f544\" has successfully progressed.",
                "reason": "NewReplicaSetAvailable",
                "status": "True",
                "type": "Progressing"
            }
        ],
        "observed_generation": 1,
        "ready_replicas": 3,
        "replicas": 3,
        "unavailable_replicas": null,
        "updated_replicas": 3
    }
}
>>> r = await k.getNamespace("default").deleteDeployment("nginx-deployment")↵
... print(r.status)↵
... ↵
↵
{'observedGeneration': 1, 'replicas': 3, 'updatedReplicas': 3, 'readyReplicas': 3, 'availableReplicas': 3, 'conditions': [{'type': 'Available', 'status': 'True', 'lastUpdateTime': '2021-04-27T07:45:51Z', 'lastTransitionTime': '2021-04-27T07:45:51Z', 'reason': 'MinimumReplicasAvailable', 'message': 'Deployment has minimum availability.'}, {'type': 'Progressing', 'status': 'True', 'lastUpdateTime': '2021-04-27T07:45:51Z', 'lastTransitionTime': '2021-04-27T07:45:45Z', 'reason': 'NewReplicaSetAvailable', 'message': 'ReplicaSet "nginx-deployment-5dd6f4f544" has successfully progressed.'}]}
>>>


  • リソースを一括作成する例

以下は、Namespace、Deployment、Serviceリソースを一括作成するためのマニフェストです。Templateサービスに事前登録してください。

- expire_seconds: 3600
  schema:
    properties: {}
    required: []
    type: object
  tag: nginx
  template: |-
    apiVersion: v1
    kind: Namespace
    metadata:
      name: sample-namespace
    ---
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: sample-nginx
      namespace: sample-namespace
    spec:
      selector:
        matchLabels:
          app: nginx
      replicas: 3
      template:
        metadata:
          labels:
            app: nginx
        spec:
          containers:
          - name: nginx
            image: nginx:latest
            ports:
            - containerPort: 80
    ---
    apiVersion: v1
    kind: Service
    metadata:
      name: sample-service
      namespace: sample-namespace
    spec:
      type: NodePort
      ports:
        - port: 80
          nodePort: 30000
      selector:
        app: nginx


事前登録したTemplateからマニフェストを作成してapplyメソッドで一括作成します。

>>> manifests = await rendering("nginx", {})↵
... print(manifests)↵
... ↵
↵
apiVersion: v1
kind: Namespace
metadata:
  name: sample-namespace
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: sample-nginx
  namespace: sample-namespace
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 3
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: sample-service
  namespace: sample-namespace
spec:
  type: NodePort
  ports:
    - port: 80
      nodePort: 30000
  selector:
    app: nginx
>>> k = await Kube.load("local")↵
... r = await k.apply(manifests)↵
... ↵
↵
>>> for i in r:↵
...     print(f"{i.kind} {i.metadata.namespace} {i.metadata.name}")↵
... ↵
↵
Namespace None sample-namespace
Deployment sample-namespace sample-nginx
Service sample-namespace sample-service
>>> r = await callout(url="http://localhost:30000")↵
... print(r.body.decode("utf-8"))↵
... ↵
↵
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
>>>


付録: Kube組込オブジェクトの使用方法について

Kube組込オブジェクトは、https://github.com/tomplus/kubernetes_asyncioをラップしています。

インスタンス化する

インスタンス化は以下のように行います。インスタンス化はメモリ空間のみに存在し、データベースには書き込まれません。
endpointには、制御対象のKubernetesのエンドポイントを指定します。kubectl config viewなどのkubectlコマンドで確認できます。
tokenには、APIトークンを指定します。kubectl describe secretなどのkubectlコマンドで確認できます。

>>> k = Kube(name="local",
             category="default",
             endpoint="https://kubernetes.docker.internal:6443",
             token=<TOKEN>,
             verify_ssl=False,
             ssl_ca_cert=None)


データベースに永続化する

永続化は、saveインスタンスメソッドで行います。インスタンス情報をデータベースに保存します。

>>> await k.save()


永続化されたインスタンスを生成する

永続化されたインスタンスを生成するには、generateクラスメソッドで行います。インスタンス化してsaveインスタンスメソッドを実行した場合と同じ結果です。

>>> k = await Kube.generate(name="local",
                            category="default",
                            endpoint="https://kubernetes.docker.internal:6443",
                            token=<TOKEN>,
                            verify_ssl=False,
                            ssl_ca_cert=None)


データベースからインスタンスを取得する

データベースからのインスタンス化は、loadクラスメソッドで行います。Kubeオブジェクトのnameを指定する必要があります。

>>> k = await Kube.load("local")


データベースからインスタンス一覧を取得する

データベースからインスタンス一覧を取得するには、retrieveクラスメソッドで行います。

>>> ks = await Kube.retrieve()


APIリソース情報を取得する

kubectl api-resources -o wideで出力されるようなAPIリソース情報を取得するには、resourcesクラスメソッドで行います。

>>> k = await Kube.load("local")↵
... r = await k.resources()↵
... print(MU(r).yaml_format)↵
... ↵
↵
APIService:
  group: apiregistration.k8s.io/v1
  name: apiservices
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
Binding:
  group: v1
  name: bindings
  namespaced: true
  verbs:
  - create
CSIDriver:
  group: storage.k8s.io/v1
  name: csidrivers
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
CSINode:
  group: storage.k8s.io/v1
  name: csinodes
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
CertificateSigningRequest:
  group: certificates.k8s.io/v1beta1
  name: certificatesigningrequests
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
ClusterRole:
  group: rbac.authorization.k8s.io/v1
  name: clusterroles
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
ClusterRoleBinding:
  group: rbac.authorization.k8s.io/v1
  name: clusterrolebindings
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
ComponentStatus:
  group: v1
  name: componentstatuses
  namespaced: false
  verbs:
  - get
  - list
ConfigMap:
  group: v1
  name: configmaps
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
ControllerRevision:
  group: apps/v1
  name: controllerrevisions
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
CronJob:
  group: batch/v1beta1
  name: cronjobs
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
CustomResourceDefinition:
  group: apiextensions.k8s.io/v1
  name: customresourcedefinitions
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
DaemonSet:
  group: apps/v1
  name: daemonsets
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
Deployment:
  group: apps/v1
  name: deployments
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
Endpoints:
  group: v1
  name: endpoints
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
Event:
  group: v1
  name: events
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
Eviction:
  group: v1
  name: pods/eviction
  namespaced: true
  verbs:
  - create
HorizontalPodAutoscaler:
  group: autoscaling/v1
  name: horizontalpodautoscalers
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
Ingress:
  group: extensions/v1beta1
  name: ingresses
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
IngressClass:
  group: networking.k8s.io/v1
  name: ingressclasses
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
Job:
  group: batch/v1
  name: jobs
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
Lease:
  group: coordination.k8s.io/v1
  name: leases
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
LimitRange:
  group: v1
  name: limitranges
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
LocalSubjectAccessReview:
  group: authorization.k8s.io/v1
  name: localsubjectaccessreviews
  namespaced: true
  verbs:
  - create
MutatingWebhookConfiguration:
  group: admissionregistration.k8s.io/v1
  name: mutatingwebhookconfigurations
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
Namespace:
  group: v1
  name: namespaces
  namespaced: false
  verbs:
  - create
  - delete
  - get
  - list
  - patch
  - update
  - watch
NetworkPolicy:
  group: networking.k8s.io/v1
  name: networkpolicies
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
Node:
  group: v1
  name: nodes
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
NodeProxyOptions:
  group: v1
  name: nodes/proxy
  namespaced: false
  verbs:
  - create
  - delete
  - get
  - patch
  - update
PersistentVolume:
  group: v1
  name: persistentvolumes
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
PersistentVolumeClaim:
  group: v1
  name: persistentvolumeclaims
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
Pod:
  group: v1
  name: pods
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
PodAttachOptions:
  group: v1
  name: pods/attach
  namespaced: true
  verbs:
  - create
  - get
PodDisruptionBudget:
  group: policy/v1beta1
  name: poddisruptionbudgets
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
PodExecOptions:
  group: v1
  name: pods/exec
  namespaced: true
  verbs:
  - create
  - get
PodPortForwardOptions:
  group: v1
  name: pods/portforward
  namespaced: true
  verbs:
  - create
  - get
PodProxyOptions:
  group: v1
  name: pods/proxy
  namespaced: true
  verbs:
  - create
  - delete
  - get
  - patch
  - update
PodSecurityPolicy:
  group: policy/v1beta1
  name: podsecuritypolicies
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
PodTemplate:
  group: v1
  name: podtemplates
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
PriorityClass:
  group: scheduling.k8s.io/v1
  name: priorityclasses
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
ReplicaSet:
  group: apps/v1
  name: replicasets
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
ReplicationController:
  group: v1
  name: replicationcontrollers
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
ResourceQuota:
  group: v1
  name: resourcequotas
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
Role:
  group: rbac.authorization.k8s.io/v1
  name: roles
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
RoleBinding:
  group: rbac.authorization.k8s.io/v1
  name: rolebindings
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
RuntimeClass:
  group: node.k8s.io/v1beta1
  name: runtimeclasses
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
Scale:
  group: apps/v1
  name: deployments/scale
  namespaced: true
  verbs:
  - get
  - patch
  - update
Secret:
  group: v1
  name: secrets
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
SelfSubjectAccessReview:
  group: authorization.k8s.io/v1
  name: selfsubjectaccessreviews
  namespaced: false
  verbs:
  - create
SelfSubjectRulesReview:
  group: authorization.k8s.io/v1
  name: selfsubjectrulesreviews
  namespaced: false
  verbs:
  - create
Service:
  group: v1
  name: services
  namespaced: true
  verbs:
  - create
  - delete
  - get
  - list
  - patch
  - update
  - watch
ServiceAccount:
  group: v1
  name: serviceaccounts
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
ServiceProxyOptions:
  group: v1
  name: services/proxy
  namespaced: true
  verbs:
  - create
  - delete
  - get
  - patch
  - update
StatefulSet:
  group: apps/v1
  name: statefulsets
  namespaced: true
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
StorageClass:
  group: storage.k8s.io/v1
  name: storageclasses
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
SubjectAccessReview:
  group: authorization.k8s.io/v1
  name: subjectaccessreviews
  namespaced: false
  verbs:
  - create
TokenReview:
  group: authentication.k8s.io/v1
  name: tokenreviews
  namespaced: false
  verbs:
  - create
ValidatingWebhookConfiguration:
  group: admissionregistration.k8s.io/v1
  name: validatingwebhookconfigurations
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
VolumeAttachment:
  group: storage.k8s.io/v1
  name: volumeattachments
  namespaced: false
  verbs:
  - create
  - delete
  - deletecollection
  - get
  - list
  - patch
  - update
  - watch
>>>


Note

APIリソース情報をAPI経由で取得する場合は、GET /kubernetesv1/{name}?resources=trueで同じ情報を取得することができます。


名前空間に属さないリソースを操作する

Kubeオブジェクトのリソース操作を行うメソッドは、プレフィックスが統一されています。リソース種別に関わらず、createpatchdeletelistが接頭辞となり、その後ろにリソース種別を結合したものがメソッド名となります。内部的には、共通接頭辞を元にKubernetes標準クライアントライブラリをリフレクションして関数を呼び出しています。

名前空間に属さないリソースを作成する

名前空間に属さないリソースの作成メソッドの接頭辞は、createです。以下のイメージで関数定義されています。引数は、マニフェストのyaml文字列か辞書オブジェクト、もしくはhttps://github.com/tomplus/kubernetes_asyncio/tree/master/kubernetes_asyncio/client/modelsを使ったリソースオブジェクトを渡すことができます。

coroutine def create{kind}(manifest, namespace=None):
    pass

Note

Namespaceを作成する場合は、r = await k.createNamespace(manifest)のように呼び出します。


名前空間に属さないリソースを変更する

名前空間に属さないリソースの変更メソッドの接頭辞は、patchです。以下のイメージで関数定義されています。第一引数は、変更対象のリソース名です。第二引数のマニフェストは、作成時と同じオブジェクト型を渡すことができます。

coroutine def patch{kind}(name, manifest, namespace=None):
    pass


名前空間に属さないリソースを削除する

名前空間に属さないリソースの削除メソッドの接頭辞は、deleteです。以下のイメージで関数定義されています。引数は、削除対象のリソース名です。

coroutine def delete{kind}(name, namespace=None, propagation_policy="Foreground", grace_period_seconds=5):
    pass


名前空間に属さないリソースを一覧する

名前空間に属さないリソースの一覧メソッドの接頭辞は、listです。以下のイメージで関数定義されています。nameキーワード引数にリソース名を指定すると対象リソースオブジェクトのみが返却されます。

coroutine def list{kind}(name=None, namespace=None):
    pass


名前空間に属するリソースを操作する

Kubeオブジェクトの名前空間に属するリソースを操作するには、getNamespace(<namespace>)インスタンスメソッドでNamespaceオブジェクトを取得し、そのNamespaceオブジェクトに対して名前空間に属さないリソース同様の共通プレフィックス付きメソッド呼び出しを行います。Namespaceオブジェクトの取得は以下のように行います。

>>> ns = k.getNamespace("sample-namespace")


名前空間に属するリソースを作成する

名前空間に属するリソースの作成メソッドの接頭辞は、createです。以下のイメージで関数定義されています。引数は、マニフェストのyaml文字列か辞書オブジェクト、もしくはhttps://github.com/tomplus/kubernetes_asyncio/tree/master/kubernetes_asyncio/client/modelsを使ったリソースオブジェクトを渡すことができます。

coroutine def create{kind}(manifest):
    pass

Note

Deploymentを作成する場合は、r = await k.getNamespace("sample-namespace").createDeployment(manifest)のように呼び出します。

名前空間に属するリソースを変更する

名前空間に属するリソースの変更メソッドの接頭辞は、patchです。以下のイメージで関数定義されています。第一引数は、変更対象のリソース名です。第二引数のマニフェストは、作成時と同じオブジェクト型を渡すことができます。

coroutine def patch{kind}(name, manifest):
    pass


名前空間に属するリソースを削除する

名前空間に属するリソースの削除メソッドの接頭辞は、deleteです。以下のイメージで関数定義されています。引数は、削除対象のリソース名です。

coroutine def delete{kind}(name, propagation_policy="Foreground", grace_period_seconds=5):
    pass


名前空間に属するリソースを一覧する

名前空間に属するリソースの一覧メソッドの接頭辞は、listです。以下のイメージで関数定義されています。nameキーワード引数にリソース名を指定すると対象リソースオブジェクトのみが返却されます。

coroutine def list{kind}(name=None):
    pass


複数リソースを一括作成する

複数のリソースが定義されたマニフェストから一括作成する場合は、applyメソッドを利用できます。

coroutine def apply(manifest):
    pass


Tip

複数リソースの一括作成は、マニフェストyamlを---を結合定義します。上述のapplyをAPIで実行する場合は、以下のリクエストパスに送信してください。
POST /kubernetesv1/{name}


Podのログを取得する

Podのログを取得するには、tailメソッドを利用してください。

>>> k = await Kube.load("local")↵
... pods = await k.getNamespace("kube-system").listPod()↵
... for i in pods.items:↵
...     print(i.metadata.name)↵
... r = await k.getNamespace("kube-system").tail("etcd-docker-desktop", lines=100, since_seconds=180)↵
... print(json.dumps(r, indent=4))↵
... ↵
coredns-f9fd979d6-wjhm2
coredns-f9fd979d6-zfkrl
etcd-docker-desktop
kube-apiserver-docker-desktop
kube-controller-manager-docker-desktop
kube-proxy-zngfm
kube-scheduler-docker-desktop
storage-provisioner
vpnkit-controller
↵
{
    "etcd-docker-desktop.etcd": [
        "2021-05-11 04:16:25.969455 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:16:35.949577 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:16:45.949357 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:16:51.538309 I | mvcc: store.index: compact 666500\n",
        "2021-05-11 04:16:51.539053 I | mvcc: finished scheduled compaction at 666500 (took 538.298µs)\n",
        "2021-05-11 04:16:55.949088 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:17:05.928101 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:17:15.928263 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:17:25.928028 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:17:35.907371 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:17:45.907344 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:17:55.907415 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:18:05.886903 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:18:15.886710 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:18:25.886644 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:18:35.865867 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:18:45.866040 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:18:55.865932 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:19:05.830788 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n",
        "2021-05-11 04:19:15.830498 I | etcdserver/api/etcdhttp: /health OK (status code 200)\n"
    ]
}
>>>


Note

Podのログ取得をAPIで行いたい場合は、以下のエンドポイントに送信してください。
GET /kubernetesv1/{name}/Namespace/{namespace}/Pod/{podName}?lines={lineCount}&since_seconds={sinceSeconds}


Podで任意のコマンドを実行する

Podでコマンドを実行するには、execメソッドを利用してください。

>>> k = await Kube.load("local")↵
... pods = await k.getNamespace("sample-namespace").listPod()↵
... for i in pods.items:↵
...     print(i.metadata.name)↵
... ↵
↵
sample-nginx-585449566-ldv66
sample-nginx-585449566-p8pmn
sample-nginx-585449566-sbgf2
>>> r = await k.getNamespace("sample-namespace").exec("sample-nginx-585449566-ldv66", commands=["/bin/sh", "-c", "cat /proc/mounts"])↵
>>> print(r)↵
>>> ↵
↵
↵
↵
overlay / overlay rw,relatime,lowerdir=/var/lib/docker/overlay2/l/7PI6U73CPC3SEPMNAAGUFPE2N5:/var/lib/docker/overlay2/l/I33B7S3RLANXCVUY2RKURTBRN6:/var/lib/docker/overlay2/l/HGB42RAL45ZAPO3RWFE22T5M27:/var/lib/docker/overlay2/l/WJHHWHG6LSOXYR6UZKRV3CK5VB:/var/lib/docker/overlay2/l/VT6JODZLIUJGXFEURTETPRDXQZ:/var/lib/docker/overlay2/l/6FTGYJ73OSWFGWIEWUYBKCM5P6:/var/lib/docker/overlay2/l/HNA3FAXN5EYO4EDOQ27SO3NI5G,upperdir=/var/lib/docker/overlay2/31d66b38dd2643a625f68873f6392eeac26d56780e1bc26324f9bb7f7ddc72c1/diff,workdir=/var/lib/docker/overlay2/31d66b38dd2643a625f68873f6392eeac26d56780e1bc26324f9bb7f7ddc72c1/work 0 0
proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0
tmpfs /dev tmpfs rw,nosuid,size=65536k,mode=755 0 0
devpts /dev/pts devpts rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=666 0 0
sysfs /sys sysfs ro,nosuid,nodev,noexec,relatime 0 0
tmpfs /sys/fs/cgroup tmpfs rw,nosuid,nodev,noexec,relatime,mode=755 0 0
cpuset /sys/fs/cgroup/cpuset cgroup ro,nosuid,nodev,noexec,relatime,cpuset 0 0
cpu /sys/fs/cgroup/cpu cgroup ro,nosuid,nodev,noexec,relatime,cpu 0 0
cpuacct /sys/fs/cgroup/cpuacct cgroup ro,nosuid,nodev,noexec,relatime,cpuacct 0 0
blkio /sys/fs/cgroup/blkio cgroup ro,nosuid,nodev,noexec,relatime,blkio 0 0
memory /sys/fs/cgroup/memory cgroup ro,nosuid,nodev,noexec,relatime,memory 0 0
devices /sys/fs/cgroup/devices cgroup ro,nosuid,nodev,noexec,relatime,devices 0 0
freezer /sys/fs/cgroup/freezer cgroup ro,nosuid,nodev,noexec,relatime,freezer 0 0
net_cls /sys/fs/cgroup/net_cls cgroup ro,nosuid,nodev,noexec,relatime,net_cls 0 0
perf_event /sys/fs/cgroup/perf_event cgroup ro,nosuid,nodev,noexec,relatime,perf_event 0 0
net_prio /sys/fs/cgroup/net_prio cgroup ro,nosuid,nodev,noexec,relatime,net_prio 0 0
hugetlb /sys/fs/cgroup/hugetlb cgroup ro,nosuid,nodev,noexec,relatime,hugetlb 0 0
pids /sys/fs/cgroup/pids cgroup ro,nosuid,nodev,noexec,relatime,pids 0 0
rdma /sys/fs/cgroup/rdma cgroup ro,nosuid,nodev,noexec,relatime,rdma 0 0
cgroup /sys/fs/cgroup/systemd cgroup ro,nosuid,nodev,noexec,relatime,name=systemd 0 0
mqueue /dev/mqueue mqueue rw,nosuid,nodev,noexec,relatime 0 0
/dev/vda1 /dev/termination-log ext4 rw,relatime 0 0
/dev/vda1 /etc/resolv.conf ext4 rw,relatime 0 0
/dev/vda1 /etc/hostname ext4 rw,relatime 0 0
/dev/vda1 /etc/hosts ext4 rw,relatime 0 0
shm /dev/shm tmpfs rw,nosuid,nodev,noexec,relatime,size=65536k 0 0
tmpfs /run/secrets/kubernetes.io/serviceaccount tmpfs ro,relatime 0 0
proc /proc/bus proc ro,relatime 0 0
proc /proc/fs proc ro,relatime 0 0
proc /proc/irq proc ro,relatime 0 0
proc /proc/sys proc ro,relatime 0 0
proc /proc/sysrq-trigger proc ro,relatime 0 0
tmpfs /proc/acpi tmpfs ro,relatime 0 0
tmpfs /proc/kcore tmpfs rw,nosuid,size=65536k,mode=755 0 0
tmpfs /proc/keys tmpfs rw,nosuid,size=65536k,mode=755 0 0
tmpfs /proc/timer_list tmpfs rw,nosuid,size=65536k,mode=755 0 0
tmpfs /proc/sched_debug tmpfs rw,nosuid,size=65536k,mode=755 0 0
tmpfs /sys/firmware tmpfs ro,relatime 0 0
>>>


Note

Podのコマンド実行をAPIで行いたい場合は、以下のエンドポイントに送信してください。
PATCH /kubernetesv1/{name}/Namespace/{namespace}/Pod/{podName}
{"type": "object", "properties": {"commands": {"type": "array", "items": {"type": "string"}, "minItems": 1}}, "required": ["commands"]}