k8s二次开发 使用python (Kubernetes Python Client)
一.在k8s master获取API cluster URL与token1.抓取Cluster URL地址# APISERVER=$(kubectl config view --minify | grep server | cut -f 2- -d ":" | tr -d " ")# echo $APISERVER下面python脚本要使用,我获取的是:https://192.16...
一.在k8s master获取API cluster URL与token
1.抓取Cluster URL地址
# APISERVER=$(kubectl config view --minify | grep server | cut -f 2- -d ":" | tr -d " ")
# echo $APISERVER
下面python脚本要使用,我获取的是:https://192.168.1.202:6443
2.创建k8s admin-token
# 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
# kubectl create -f admin-token.yaml
3.获取token值
# kubectl describe secret/$(kubectl get secret -nkube-system |grep admin|awk '{print $1}') -nkube-system
最后将token与APISERVER地址返回内容复制到python client主机上, 供脚本使用.
二、 在python client主机上编写脚本
1. 创建目录结构
# mkdir -p /kube/auth
# cd /kube/auth
# vim token.txt
将刚才获取的Token字符串复制到该文件
这里我们获取的token会引入到我们的脚本下, 作为bearer authorization的api key与远程k8s API建立认证连接.
2. 编写python client脚本,获取的pod信息
# vi k8s.py
from kubernetes.client import api_client
from kubernetes.client.apis import core_v1_api
def test_service_apis():
from kubernetes import client
k8s_url = 'https://192.168.1.124:6443'
with open('/kube/auth/token.txt', 'r') as file:
Token = file.read().strip('\n')
configuration = client.Configuration()
configuration.host = k8s_url
configuration.verify_ssl = False
configuration.api_key = {"authorization": "Bearer " + Token}
client1 = api_client.ApiClient(configuration=configuration)
api = core_v1_api.CoreV1Api(client1)
ret = api.list_pod_for_all_namespaces(watch=False)
print(ret)
test_service_apis()
更多推荐
所有评论(0)