python3 kubernetes api use

First, install

github:https://github.com/kubernetes-client/python

installation

pip install kubernetes

 

 

Second, certification

1, kubeconfig document authentication

First introduced SDK support libraries. Then copy the contents of config file ~ / .kube to a local directory, saved to a file kubeconfig.yaml, and then run the following python code.

[root@k8s-m ~]# cp .kube/config    kubeconfig.yaml

#使用
from kubernetes import client, config
config.kube_config.load_kube_config(config_file="/root/kubeconfig.yaml")

 

 

 

Three, api use

1, lists the resource information

from Kubernetes Import Client, config 
config.kube_config.load_kube_config (config_file = " /root/kubeconfig.yaml " ) 

# get the API CoreV1Api version of the object 
v1 = client.CoreV1Api () 

# list Namespaces 
for ns in v1.list_namespace (). items:
     Print (ns.metadata.name) 
    
# lists all Services 
RET = v1.list_service_for_all_namespaces (Watch = False)
 for I in ret.items:
     Print ( " % S \ T% S \ T% S \ T% S \ T% S \ n- " % (i.kind, i.metadata.namespace, i.metadata.name, i.spec.cluster_ip, i.spec.ports ))
    
#列出所有的pod
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))

#列出所有deploy
ret = v1.list_deployments_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))
    
## Listed above and other similar resources, do not understand you can view (kubectl api-resources)

 

2, create a resource object k8s


github:https://github.com/kubernetes-client/python/tree/master/examples

Create a resource (written in advance yaml list of resources)

#创建deploy
[root@k8s-m ~]# cat create_deploy.py
from os import path
import yaml
from kubernetes import client, config

def main():
    config.load_kube_config()

    with open(path.join(path.dirname(__file__), "/root/deploy.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)
main()

[root@k8s-m ~]# kubectl get pod 
NAME                        READY   STATUS    RESTARTS   AGE
mydeploy-6946c867dc-bgcld   1/1     Running   0          40s
mydeploy-6946c867dc-rdnvj   1/1     Running   0          40s
[root@k8s-m ~]# kubectl get deploy
NAME       READY   UP-TO-DATE   AVAILABLE   AGE
mydeploy   2/2      2             2            44S 


# Create a pod example (other resources have to check their own to find their own source code corresponding API) 
[root @ K8S -m ~] # CAT create_pod.py 
from os path Import 

Import YAML 

from Kubernetes Import Client, config 


DEF main () : 
    config.load_kube_config () 

    with Open (. path the Join . (path dirname (__FILE__), " /root/pod.yaml " )) AS f: 
        DEP = yaml.safe_load (f) 
        k8s_core_v1 = client.CoreV1Api () 
        RESP = k8s_core_v1.create_namespaced_pod ( 
            body=dep, namespace="default")
        print("Pod created. status='%s'" % resp.metadata.name)


if __name__ == '__main__':
    main()

##
[root@k8s-m ~]# python3  create_pod.py 
Pod created. status='nginx-pod'
[root@k8s-m ~]# kubectl get pod  nginx-pod
NAME        READY   STATUS    RESTARTS   AGE
nginx-pod   1/1     Running   0          8s

 

 

3, delete the resource (show me pod example, delete other resources almost)

Reference Address: /usr/local/python3/lib/python3.6/site-packages/kubernetes/client/

[root@k8s-m ~]# cat  dp.py
from os import path
import yaml
from kubernetes import client, config

def main():
    config.load_kube_config()
    k8s_core_v1 = client.CoreV1Api()
    resp = k8s_core_v1.delete_namespaced_pod(namespace="default",name='nginx-pod')
    print("delete Pod ")

[root@k8s-m ~]# python3 dp.py
delete Pod 

 

4, view the resource (similar kubectl get pod xxx -o json)

#查看(read)

[root@k8s-m ~]# cat  rp.py 
from os import path
import yaml
from kubernetes import client, config

def main():
    config.load_kube_config()
    k8s_core_v1 = client.CoreV1Api()
    resp = k8s_core_v1.read_namespaced_pod(namespace="default",name='nginx-pod')
    print("read Pod ")
    #详细信息
    print(resp)
    #指定信息
    print(resp.spec.containers[0].image)

if __name__ == '__main__':
    main()

[root@k8s-m ~]# python3   rp.py  |tail
            'host_ip': '172.31.250.229',
            'init_container_statuses': None,
            'message': None,
            'nominated_node_name': None,
            'phase': 'Running',
            'pod_ip': '10.244.167.134',
            'qos_class': 'BestEffort',
            'reason': None,
            'start_time': datetime.datetime(2019, 8, 30, 9, 13, 49, tzinfo=tzutc())}}
nginx

 

5, modify

[root@k8s-m ~]# cat  pp.py 
from os import path
import yaml
from kubernetes import client, config

def main():
    config.load_kube_config()
    k8s_core_v1 = client.CoreV1Api()
    old_resp = k8s_core_v1.read_namespaced_pod(namespace="default",name='nginx-pod')
    old_resp.spec.containers[0].image = "nginx:alpine"
    #修改镜像
    new_resp = k8s_core_v1.patch_namespaced_pod(namespace="default",name='nginx-pod',body=old_resp)
    print(new_resp.spec.containers[0].image)
if __name__ == '__main__':
    main()

[root@k8s-m ~]# python3 pp.py 
nginx:alpine

 

Guess you like

Origin www.cnblogs.com/zhangb8042/p/11444756.html