先上链接
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2021/12/1 17:07
# @Author : XuLiLiang
# @Email : xuliliang@epailive.com
# @File : k8s-demo.py
# @Description : 操作k8s api
import urllib3
import yaml
from kubernetes import client
from kubernetes.client import ApiException
urllib3.disable_warnings()
'''步骤
先pip install kubernetes
1、创建用户
vi CreateServiceAccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: admin-user
namespace: kube-system
kubectl create -f CreateServiceAccount.yaml
2、授权
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: admin-user
subjects:
- kind: ServiceAccount
name: admin-user
namespace: kube-system
roleRef:
kind: ClusterRole
name: cluster-admin
apiGroup: rbac.authorization.k8s.io
3、获取token
kubectl describe secret $(kubectl get secret -n kube-system | grep ^admin-user | awk '{print $1}') -n kube-system | grep -E '^token'| awk '{print $2}'
'''
apiToken = ''
host = 'https://100.100.100.5:6443'
# deployment_template = {
# "apiVersion": "apps/v1",
# "kind": "Deployment",
# "metadata": {
# "name": "myapp",
# "namespace": "",
# "labels": {
# "app": "myapp"
# }
# },
# "spec": {
# "replicas": 1,
# "selector": {
# "matchLabels": {
# "app": "myapp"
# }
# },
# "template": {
# "metadata": {
# "name": "myapp-pod",
# "labels": {
# "app": "myapp"
# }
# },
# "spec": {
# "containers": [
# {
# "name": "myapp",
# "image": "1450793561/myapp:v1",
# "ports": [
# {
# "name": "http",
# "containerPort": 80
# }
# ]
# }
# ]
# }
# }
# }
# }
# read = yaml.safe_dump(deployment_template)
# 模板----deployment
def create_deployment_object(deployment_name, namespace, container_name, container_image):
container = client.V1Container(
name=container_name,
image=container_image,
ports=[client.V1ContainerPort(container_port=80)],
resources=client.V1ResourceRequirements(requests={"cpu": "100m", "memory": "200Mi"},
limits={"cpu": "500m", "memory": "500Mi"}))
template = client.V1PodTemplateSpec(
metadata=client.V1ObjectMeta(labels={"app": container_name}),
spec=client.V1PodSpec(containers=[container]),
)
spec = client.V1DeploymentSpec(
replicas=3,
selector={"matchLabels": {"app": container_name}, "namespace": namespace},
template=template
)
deployment_temp = client.V1Deployment(
api_version="apps/v1",
kind="Deployment",
metadata=client.V1ObjectMeta(name=deployment_name),
spec=spec,
)
return deployment_temp
class K8sApi:
def __init__(self):
self.apiToken = apiToken
self.host = host
configuration = client.Configuration()
setattr(configuration, 'verify_ssl', False)
client.Configuration.set_default(configuration)
configuration.host = self.host
configuration.verify_ssl = False
configuration.debug = False
configuration.api_key = {"authorization": "Bearer " + self.apiToken}
client.Configuration.set_default(configuration)
self.core_api_v1 = client.CoreV1Api(client.ApiClient(configuration))
self.apps_v1_api = client.AppsV1Api(client.ApiClient(configuration))
def create_namespace(self, ns_name):
list_names = self.list_namespaces()
if ns_name not in list_names:
body = {'apiVersion': 'v1', 'kind': 'Namespace', 'metadata': {'name': ns_name, 'labels': {'name': ns_name}}}
try:
self.core_api_v1.create_namespace(body)
except ApiException as e:
print(e)
else:
print(f"已经存在namespace:{ns_name}")
def list_namespaces(self):
list_temp = []
try:
ret = self.core_api_v1.list_namespace(limit=50, timeout_seconds=60, watch=False)
for i in ret.items:
list_temp.append(i.metadata.name)
return list_temp
except ApiException as e:
print("Exception when calling CoreV1Api->list_namespace: %s\n" % e)
def list_services(self, ns):
lit = []
try:
ret = self.core_api_v1.list_namespaced_service(namespace=ns)
for i in ret.items:
lit.append(i.metadata.name)
return lit
except ApiException as e:
print(e)
def list_pods(self, ns):
lit = []
try:
ret = self.core_api_v1.list_namespaced_pod(namespace=ns)
for i in ret.items:
lit.append(i.metadata.name)
print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
return lit
except ApiException as e:
print(e)
# def create_namespace_deployment(self):
# with open("./test-pod.yaml") as f:
# body = yaml.safe_load(f)
# body['metadata']['name'] = "testpod"
# body['metadata']['namespace'] = "test123"
# try:
# self.apps_v1_api.create_namespaced_deployment("test123", body=body)
# except ApiException as e:
# print("失败", e)
def update_namespace_deployment(self, name, namespace, new_image):
body = self.apps_v1_api.read_namespaced_deployment(name, namespace)
body.spec.template.spec.containers[0].image = new_image
print("new images------->>>>>", body.spec.template.spec.containers[0].image)
try:
resp=self.apps_v1_api.patch_namespaced_deployment(name, namespace, body)
print("\n[INFO] deployment's container image updated.\n")
print("%s\t%s\t\t\t%s\t%s" % ("NAMESPACE", "NAME", "REVISION", "IMAGE"))
print(
"%s\t\t%s\t%s\t\t%s\n"
% (
resp.metadata.namespace,
resp.metadata.name,
resp.metadata.generation,
resp.spec.template.spec.containers[0].image,
)
)
except ApiException as e:
print(e)
def get_nodes_info(self):
response = self.core_api_v1.list_node()
print(response.items)
def create_dep(self, deployments, deployment_name, namespace):
if deployment_name not in self.list_deployments(namespace):
resp = self.apps_v1_api.create_namespaced_deployment(
body=deployments, namespace="test123123"
)
print("\n[INFO] deployment `nginx-deployment` created.\n")
print("%s\t%s\t\t\t%s\t%s" % ("NAMESPACE", "NAME", "REVISION", "IMAGE"))
print(
"%s\t\t%s\t%s\t\t%s\n"
% (
resp.metadata.namespace,
resp.metadata.name,
resp.metadata.generation,
resp.spec.template.spec.containers[0].image,
)
)
else:
print("deployment has exist")
def list_deployments(self, namespace):
list_temp = []
deployments = self.apps_v1_api.list_namespaced_deployment(namespace)
for i in deployments.items:
list_temp.append(i.metadata.name)
return list_temp
def delete_deployment(self, deployment_name, namespace):
if deployment_name in self.list_deployments(namespace):
try:
resp = self.apps_v1_api.delete_namespaced_deployment(
name=deployment_name,
namespace=namespace,
body=client.V1DeleteOptions(
propagation_policy="Foreground", grace_period_seconds=5
),
)
print(resp)
print("\n[INFO] deployment `nginx-deployment` deleted.")
except ApiException as e:
print(e)
else:
print("deployment not exist ")
if __name__ == '__main__':
# api = K8sApi()
# # api.create_namespace_deployment()
# # api.replace_namespace_deployment("testpod","test123","1450793561/myapp:v1")
# # api.create_namespace("test123123")
# deployment = create_deployment_object("myapp-deployment", "test123123", "myapp", "1450793561/myapp:v2")
# api.create_dep(deployment, "myapp-deployment", "test123123")
# api.list_deployments("test123123")
# api.delete_deployment("testpod", "test123")