[쿠버네티스] 클라이언트 라이브러리(Client Libraries)


클라이언트 라이브러리가 무엇이냐? 그것을 알아보자.


Kubernetes Client Libraries

쿠버네티스 API를 사용하기 위해서 공식적으로 지원되는 쿠버네티스 클라이언트 라이브러리를 사용한다.

쿠버네티스 REST API를 사용해 애플리케이션을 작성하기 위해 API 호출 또는 요청/응답 타입을 직접 구현할 필요는 없다. 사용하고 있는 프로그래밍 언어를 위한 클라이언트 라이브러리를 사용하면 된다

  • 말 그대로 내가 직접 API 안만들어도 클라이언트 라이브러리로 요청/응답해서 요리조리 이것저것 CRUD할 수 있다.
  • 아래와 같이 이렇게만 쓰면 내가 필요한 정보나 CRUD를 할수 있다. 더 무시무시한걸 할 수 있겠지만 나는 여기까지만 해봤다.
from kubernetes import client, config

config.load_kube_config()

v1=client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
    print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
  • 라이브러리에 구현되어있는 함수를 통해서 쿠버네티스 API /api/v1/pods 를 호출하게 된다.
...
return self.api_client.call_api('/api/v1/pods', 'GET',
                        path_params,
                        query_params,
                        header_params,
                        body=body_params,
                        post_params=form_params,
                        files=local_var_files,
                        response_type='V1PodList',
                        auth_settings=auth_settings,
                        async_req=params.get('async_req'),
                        _return_http_data_only=params.get('_return_http_data_only'),
                        _preload_content=params.get('_preload_content', True),
                        _request_timeout=params.get('_request_timeout'),
                        collection_formats=collection_formats)

실습

  • 아래와 같이하면 deploy가 된다. 미쳤다. 간단하다. 인생이 편하다
"""
Creates a deployment using AppsV1Api from file nginx-deployment.yaml.
"""

from os import path

import yaml

from kubernetes import client, config


def main():
    # Configs can be set in Configuration class directly or using helper
    # utility. If no argument provided, the config will be loaded from
    # default location.
    config.load_kube_config()

    with open(path.join(path.dirname(__file__), "nginx-deployment.yaml")) as f:
        dep = yaml.safe_load(f)
        k8s_apps_v1 = client.AppsV1Api()
        resp = k8s_apps_v1.create_namespaced_deployment(
            body=dep, namespace="default")
        print("Deployment created. status='%s'" % resp.metadata.name)


if __name__ == '__main__':
    main()
  • 그럼 서비스는 어떻게 하냐면 아래와 같이하면 서비스를 CRUD할 수 있다.
"""
This example demonstrates the following:
    - Creation of a k8s service using dynamic-client
    - List, patch(update), delete the service
"""

from kubernetes import config, dynamic
from kubernetes.client import api_client


def main():
    # Creating a dynamic client
    client = dynamic.DynamicClient(
        api_client.ApiClient(configuration=config.load_kube_config())
    )

    # fetching the service api
    api = client.resources.get(api_version="v1", kind="Service")

    name = "frontend-service"

    service_manifest = {
        "apiVersion": "v1",
        "kind": "Service",
        "metadata": {"labels": {"name": name}, "name": name, "resourceversion": "v1"},
        "spec": {
            "ports": [
                {"name": "port", "port": 80, "protocol": "TCP", "targetPort": 80}
            ],
            "selector": {"name": name},
        },
    }

    # Creating service `frontend-service` in the `default` namespace

    service = api.create(body=service_manifest, namespace="default")

    print("\n[INFO] service `frontend-service` created\n")

    # Listing service `frontend-service` in the `default` namespace
    service_created = api.get(name=name, namespace="default")

    print("%s\t%s" % ("NAMESPACE", "NAME"))
    print(
        "%s\t\t%s\n"
        % (service_created.metadata.namespace, service_created.metadata.name)
    )

    # Patching the `spec` section of the `frontend-service`

    service_manifest["spec"]["ports"] = [
        {"name": "new", "port": 8080, "protocol": "TCP", "targetPort": 8080}
    ]

    service_patched = api.patch(body=service_manifest, name=name, namespace="default")

    print("\n[INFO] service `frontend-service` patched\n")
    print("%s\t%s\t\t\t%s" % ("NAMESPACE", "NAME", "PORTS"))
    print(
        "%s\t\t%s\t%s\n"
        % (
            service_patched.metadata.namespace,
            service_patched.metadata.name,
            service_patched.spec.ports,
        )
    )

    # Deleting service `frontend-service` from the `default` namespace
    service_deleted = api.delete(name=name, body={}, namespace="default")

    print("\n[INFO] service `frontend-service` deleted\n")

if __name__ == "__main__":
    main()

끝..




© 2018. by statssy

Powered by statssy