目录
阅读时间: 3 分钟
读者朋友们,大家好在这篇博客中,我们将看到如何用 Kubernetes客户端Python创建Cronjob。
我们都知道,一般来说,我们使用kubectl命令来创建、列出、更新和
删除Kubernetes资源。但在这篇博客中,我们将看到如何使用python来进行
做这些事情的。
安装。
从源码安装。
git clone --recursive https://github.com/kubernetes-client/python.git
cd python
python setup.py install
直接从PyPI安装。
pip install kubernetes
现在,我们已经安装了python-Kubernetes包。
创建Cronjob。
我的create.py文件包含以下代码,用于创建cronjob,使用
Kubernetes Python客户端。现在我们已经安装了python-Kubernetes包。
我们可以把它导入。
from kubernetes import client, config
在Python中,我们从客户端模块实例化了BatchV1beta1Api类。
client_api = client.BatchV1beta1Api()
对Kubernetes API服务器进行认证。
但如果你想列出一个GKE集群的所有自动化cronjob,你只需要
认证配置
我使用了Bearer Token,它使请求能够使用访问密钥进行认证。
configuration.api_key = {"authorization": "Bearer" + bearer_token}
from time import sleep
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes import client, config
JOB_NAME = "pi"
def __get_kubernetes_client(bearer_token,api_server_endpoint):
try:
configuration = kubernetes.client.Configuration()
configuration.host = api_server_endpoint
configuration.verify_ssl = False
configuration.api_key = {"authorization": "Bearer " + bearer_token}
client.Configuration.set_default(configuration)
with kubernetes.client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance1 = kubernetes.client.BatchV1beta1Api(api_client)
return api_instance1
except Exception as e:
print("Error getting kubernetes client \n{}".format(e))
return None
def create_cron_job(api_instance,cluster_details,namespace):
container = client.V1Container(
name="pi",
image="perl",
command=["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"])
# Create and configure a spec section
template = client.V1PodTemplateSpec(
metadata=client.V1ObjectMeta(labels={"app": "pi"}),
spec=client.V1PodSpec(restart_policy="Never", containers=[container]))
# Create the specification of deployment
spec = client.V1JobSpec(
template=template,
backoff_limit=4) #specify the number of retries before considering a Job as failed
# Instantiate the job object
job = client.V1Job(
api_version="batch/v1",
kind="Job",
metadata=client.V1ObjectMeta(name=JOB_NAME),
spec=spec)
client_api= __get_kubernetes_client(
bearer_token=cluster_details["bearer_token"],
api_server_endpoint=cluster_details["api_server_endpoint"],
)
api_response = client_api.create_namespaced_cron_job(
body=client.V1beta1CronJob(
api_version='batch/v1beta1',
kind='CronJob',
metadata=client.V1ObjectMeta(name='cronjob8'),
spec = client.V1CronJobSpec(
schedule="25 17 8 6 2", # 25(minute) 5(pm) 8(date) june(month) tuesday(day of the week)
job_template=job
)
),
namespace=namespace)
print("cronJob created. status='%s'" % str(api_response.status))
if __name__ == '__main__':
batch_v1 = client.BatchV1Api()
cluster_details={
"bearer_token":"GKE-Bearer-Token",
"api_server_endpoint":"Ip-k8s-crontrol-plane"
}
create_cron_job(batch_v1,cluster_details,"default")
保存代码文件名,如create-cronjobs.py,然后运行下面的命令。
之前,你必须提供GKE Cluster Bearer令牌和Kubernetes控制平面的IP。
python3 create-cronjobs.py
如你所见,我的cronjob已经成功创建。
获取cronjob。
要获得已创建的和现有的cronjob列表,请使用下面的方法并调用函数getcronjob,就像我在上面的例子中调用create_cron_job()一样。
def __get_kubernetes_client(bearer_token,api_server_endpoint):
try:
configuration = client.Configuration()
configuration.host = api_server_endpoint
configuration.verify_ssl = False
configuration.api_key = {"authorization": "Bearer " + bearer_token} # for authentication to the GKE Cluster
client.Configuration.set_default(configuration)
client_api = client.BatchV1beta1Api() #BatchV1beta1Api for interacting with cronjobs
return client_api
except Exception as e:
print("Error getting kubernetes client \n{}".format(e))
return None
def getcronjobs(cluster_details,namespace="default",all_namespaces=True):
client_api= __get_kubernetes_client(
bearer_token=cluster_details["bearer_token"],
api_server_endpoint=cluster_details["api_server_endpoint"],
)
if all_namespaces is True: #list all the cronjobs in all namespaces
ret =client_api.list_cron_job_for_all_namespaces(watch=False)
temp_dict_obj={}
temp_list_obj=[]
for i in ret.items:
temp_dict_obj={
"name": i.metadata.name,
"namespace": i.metadata.namespace
}
temp_list_obj.append(temp_dict_obj)
print("cronjob under all namespaces: {}".format(temp_list_obj))
return temp_list_obj
else:
cronjob_list = client_api.list_namespaced_cron_job("{}".format(namespace)) #list the cronjobs of default namespace
print("cronjob under default namespaces:{}".format(cronjob_list))
return cronjob_list
之后,我将运行以下命令。
python3 get-cronjobs.py
正如你在这里看到的,我的cronjob在所有命名空间下都被列出,同样,你也可以在默认和任何其他的
同样地,你也可以通过执行if all_namespaces为False来列出默认和其他任何命名空间。
所以,现在你对GKE集群的Python Kubernetes客户端有了一个概念,更多信息请查看示例。
总结。
因此,在这篇博客中,我们看到了如何轻松地使用Kubernetes Python客户端创建和获取cronjob的列表。如果你喜欢这篇博客,请通过竖起大拇指并与你的朋友分享来表示你的赞赏。