KubernetesPythonクライアント

I.概要#

Pythonクライアントクライアント-Kubernetesによって公式に保守されているpython、アドレス:[https://github.com/kubernetes-client/python](https://github.com/kubernetes-client/python)

モジュールのインストール##

pip3 install kubernetes

環境の説明##

オペレーティングシステム:centos 7.6

k8sバージョン:1.18.1

ipアドレス:192.168.31.74

ホスト名:k8s-master

オペレーティングシステム:centos 7.6

k8sバージョン:1.18.1

ipアドレス:192.168.31.71

ホスト名:k8s-node01

2. APIクラスターのURLとトークン#を取得します

クラスターのURLアドレスを取得します##

k8s-masterノードにログインし、以下を実行します。

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

次のpythonスクリプトを使用したいのですが、取得したのはhttps://192.168.31.74:6443です。

k8s管理トークンを作成します##

新しいファイルを編集する

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

内容は以下の通りです。

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

yamlファイルを実行する

kubectl create -f admin-token.yaml

トークン値を取得します##

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

出力:

token:      eyJhbGciOiJSUzI1NiIsImtxxxx

トークンが長すぎるため、代わりにxxxを使用してください

最後に、返されたトークンの内容とAPISERVERアドレスを、スクリプトで使用できるようにpythonクライアントホストにコピーします。

3つ目は、pythonクライアントhost#でスクリプトを作成することです。

この記事で使用されているpythonバージョンは3.7.3で、centos7.6サーバーで実行されています。

ディレクトリ構造を作成する##

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

取得したトークン文字列をこのファイルにコピーします。例:eyJhbGciOiJSUzI1NiIsImtxxxx

ここで取得したトークンは、リモートk8sAPIとの認証接続を確立するためのベアラ認証のapiキーとしてスクリプトに導入されます。

pythonクライアントスクリプトの作成##

名前を取得しました###

# !/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):"""
  トークンを取得
  : return:"""
  withopen('token.txt','r')as file:
   Token = file.read().strip('\n')return Token

 def get_api(self):"""
  APIのCoreV1Apiバージョンオブジェクトを取得します
  : 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):"""
  名前のリストを取得する
  : 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)

実行出力:

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

注:出力時に警告メッセージが表示されます

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,

これはリクエストライブラリからの警告です。ip経由でアクセスしているため、SSL検証は失敗します。しかし、これは影響しません。

すべてのサービスを取得する##

上記のコードに基づいて、別のメソッドを追加します

def get_services(self):"""
  すべてのサービスを利用する
  : 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))

このメソッドを単独で実行すると、多くの情報が出力されます。過剰な出力のため、私が実行した1つのflaskappのみがここにリストされています

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

node_portによって公開されているサービス名、svcアドレス、ポートなど、多くの情報を確認できます。

ポッド情報を取得する##

最初にk8s-masterにログインして、現在実行中のポッドを表示します

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

上記のコードに基づいて、別のメソッドを追加します

def get_pod_info(self,namespaces,pod_name):"""
  ポッド情報を表示する
  : param namespaces:次のようなコマンドスペース:デフォルト:param pod_name:ポッドのフルネーム(flaskappなど)-1-5d96dbf59b-lhmp8
  : return:"""
  api = self.get_api()
  # パラメータの例
  namespaces ="default"
  pod_name ="flaskapp-1-5d96dbf59b-lhmp8"
  resp = api.read_namespaced_pod(namespace=namespaces,name=pod_name)
  # 詳細
  print(resp)

このメソッドを実行し、次の情報を出力します。出力が多すぎるため、使用...省略

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

このポッドに関する詳細情報を含む非常に長いjsonが出力されます

ポッドログを取得する##

上記のコードに基づいて、別のメソッドを追加します

def get_pod_logs(self,namespaces,pod_name):"""
  ポッドログを表示
  : param namespaces:次のようなコマンドスペース:デフォルト:param pod_name:ポッドのフルネーム(flaskappなど)-1-5d96dbf59b-lhmp8
  : return:"""
  api = self.get_api()
  # パラメータの例
  namespaces ="default"
  pod_name ="flaskapp-1-5d96dbf59b-lhmp8""""
  出力をかなり美しくする
  tail_lines=200は最新の200行を出力します
        """
  log_content = api.read_namespaced_pod_log(pod_name, namespaces, pretty=True, tail_lines=200)print(log_content)

このメソッドを実行し、次の情報を出力します。

* 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

これは、フラスコの実行後に出力されるログ情報です。

その他の参考資料については、次のリンクを参照してください。

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

**注:トークンを直接txtに書き込むことは安全ではありません。トークンをredisに書き込んでから、pythonで呼び出すことを検討できます。 ****

この記事の参照リンク:

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

Recommended Posts

KubernetesPythonクライアント
Pythonマルチスレッド
Python CookBook
Python FAQ
Python3辞書
python(you-get)
Python文字列
Pythonの基本
Python記述子
Pythonの基本2
Python exec
Pythonノート
Python3タプル
CentOS + Python3.6 +
Python Advanced(1)
Python IO
Pythonマルチスレッド
Pythonツールチェーン
Python3リスト
Pythonマルチタスク-日常
Pythonの概要
Pythonアナリティック
Pythonの基本
07.Python3関数
Pythonの基本3
Pythonマルチタスクスレッド
Python関数
python sys.stdout
python演算子
Pythonエントリ-3
Centos 7.5 python3.6
Python文字列
pythonキューキュー
Pythonの基本4
Pythonの基本5