Kubernetes Python Client

I. Overview#

The Python client client-python officially maintained by Kubernetes, address: https://github.com/kubernetes-client/python

Install module##

pip3 install kubernetes

Environmental description##

Operating system: centos 7.6

k8s version: 1.18.1

ip address: 192.168.31.74

Host name: k8s-master

Operating system: centos 7.6

k8s version: 1.18.1

ip address: 192.168.31.71

Host name: k8s-node01

2. Get API cluster URL and token

Get the Cluster URL address##

Log in to the k8s-master node and execute:

# APISERVER=$(kubectl config view --minify | grep server | cut -f 2--d ":"| tr -d " ")
# echo $APISERVER
https://192.168.31.74:6443

I want to use the following python script, what I got is: https://192.168.31.74:6443

Create k8s admin-token

Edit new file

# mkdir -p /kube/role
# cd /kube/role
# vi admin-token.yaml

The content is as follows:

kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
 name: admin
 annotations:
 rbac.authorization.kubernetes.io/autoupdate:"true"
roleRef:
 kind: ClusterRole
 name: cluster-admin
 apiGroup: rbac.authorization.k8s.io
subjects:- kind: ServiceAccount
 name: admin
 namespace: kube-system
---
apiVersion: v1
kind: ServiceAccount
metadata:
 name: admin
 namespace: kube-system
 labels:
 kubernetes.io/cluster-service:"true"
 addonmanager.kubernetes.io/mode: Reconcile

Execute yaml file

kubectl create -f admin-token.yaml

Get the token value##

# kubectl describe secret/$(kubectl get secret -nkube-system |grep admin|awk '{print $1}')-nkube-system|grep token:

Output:

token:      eyJhbGciOiJSUzI1NiIsImtxxxx

Because the token is too long, use xxx instead

Finally, copy the returned content of the token and APISERVER address to the python client host for use by the script.

Three, write scripts on the python client host#

The python version used in this article is 3.7.3, running on a centos 7.6 server.

Create directory structure##

# mkdir -p /kube/auth
# cd /kube/auth
# vim token.txt

Copy the Token string just obtained to this file, for example: eyJhbGciOiJSUzI1NiIsImtxxxx

The token we obtained here will be introduced into our script as the api key of bearer authorization to establish an authentication connection with the remote k8s API.

Writing python client script##

Obtained namespace###

# !/usr/bin/python3
# - *- coding: utf-8-*-from kubernetes.client import api_client
from kubernetes.client.apis import core_v1_api
from kubernetes import client,config

classKubernetesTools(object):
 def __init__(self):
  self.k8s_url ='https://192.168.31.74:6443'

 def get_token(self):"""
  Get token
  : return:"""
  withopen('token.txt','r')as file:
   Token = file.read().strip('\n')return Token

 def get_api(self):"""
  Get the CoreV1Api version object of the API
  : return:"""
  configuration = client.Configuration()
  configuration.host = self.k8s_url
  configuration.verify_ssl = False
  configuration.api_key ={"authorization":"Bearer "+ self.get_token()}
  client1 = api_client.ApiClient(configuration=configuration)
  api = core_v1_api.CoreV1Api(client1)return api

 def get_namespace_list(self):"""
  Get a list of namespaces
  : return:"""
  api = self.get_api()
  namespace_list =[]for ns in api.list_namespace().items:
   # print(ns.metadata.name)
   namespace_list.append(ns.metadata.name)return namespace_list

if __name__ =='__main__':
 namespace_list =KubernetesTools().get_namespace_list()print(namespace_list)

Execution output:

[' default','istio-system','kube-node-lease','kube-public','kube-system']

Note: When outputting, there will be a warning message

InsecureRequestWarning: Unverified HTTPS request is being made to host '192.168.31.74'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
 InsecureRequestWarning,

This is a warning from the requests library. Because I am accessing it via ip, SSL verification will fail. But this does not affect.

Get all services

On the basis of the above code, add another method

def get_services(self):"""
  Get all services
  : return:"""
  api = self.get_api()
  ret = api.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))

Executing this method alone will output a lot of information. Due to excessive output, only one flaskapp I run is listed here

None     default     flaskapp-110.1.168.165[{'name':'flaskapp-port','node_port':30005,'port':5000,'protocol':'TCP','target_port':5000}]

You can see a lot of information, including service name, svc address, and port exposed by node_port

Get pod information##

Log in to k8s-master first to view the pod currently running

# kubectl get pods
NAME                          READY   STATUS    RESTARTS   AGE
flaskapp-1-5d96dbf59b-lhmp8   1/1     Running   4          23d

On the basis of the above code, add another method

def get_pod_info(self,namespaces,pod_name):"""
  View pod information
  : param namespaces:Command space, such as: default:param pod_name:The full name of the pod, such as flaskapp-1-5d96dbf59b-lhmp8
  : return:"""
  api = self.get_api()
  # Example parameters
  namespaces ="default"
  pod_name ="flaskapp-1-5d96dbf59b-lhmp8"
  resp = api.read_namespaced_pod(namespace=namespaces,name=pod_name)
  # details
  print(resp)

Execute this method, output the following information, due to too much output, use... omitted

{' api_version':'v1','kind':'Pod',...

It will output a very long json, which contains detailed information about this pod

Get pod log##

On the basis of the above code, add another method

def get_pod_logs(self,namespaces,pod_name):"""
  View pod log
  : param namespaces:Command space, such as: default:param pod_name:The full name of the pod, such as flaskapp-1-5d96dbf59b-lhmp8
  : return:"""
  api = self.get_api()
  # Example parameters
  namespaces ="default"
  pod_name ="flaskapp-1-5d96dbf59b-lhmp8""""
  pretty beautify output
  tail_lines=200 output the most recent 200 lines
        """
  log_content = api.read_namespaced_pod_log(pod_name, namespaces, pretty=True, tail_lines=200)print(log_content)

Execute this method and output the following information:

* Serving Flask app "app"(lazy loading)* Environment: production
 WARNING: Do not use the development server in a production environment.
 Use a production WSGI server instead.* Debug mode: on
 * Running on http://0.0.0.0:5000/(Press CTRL+C to quit)* Restarting with stat
 * Debugger is active!* Debugger PIN:182-124-947

This is the log information output after flask runs.

For more references, please refer to the link:

https://blog.csdn.net/sinat_33431419/article/details/105223726

**Note: It is not safe to write token directly to txt. You can consider writing token to redis and then call it with python. **

Reference link for this article:

https://blog.csdn.net/hypon2016/article/details/99439309

Recommended Posts

Kubernetes Python Client
Python multithreading
Python CookBook
Python FAQ
Python3 dictionary
python (you-get)
Python string
Python basics
Python descriptor
Python basics 2
Python exec
Python notes
Python3 tuple
CentOS + Python3.6+
Python advanced (1)
Python IO
Python multithreading
Python toolchain
Python3 list
Python multitasking-coroutine
Python overview
Python analytic
Python basics
07. Python3 functions
Python basics 3
Python multitasking-threads
Python functions
python sys.stdout
python operator
Python entry-3
Centos 7.5 python3.6
Python string
python queue Queue
Python basics 4
Python basics 5