使用Python脚本执行kubectl命令



我试图使用python脚本执行kubectl命令,但不断得到错误。我需要执行kubectl命令来创建pod,并检查pod日志是否有任何失败。

我在这里做错了什么?

import subprocess
command = 'kubectl apply -f deployment.yaml'

check_output= subprocess.check_output(command)
print(check_output)

误差

Traceback (most recent call last):
File "/usr/bin/cma-scripts/kubectl.py", line 6, in <module>
check_output= subprocess.check_output(command)
File "/usr/local/lib/python3.9/subprocess.py", line 424, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "/usr/local/lib/python3.9/subprocess.py", line 505, in run
with Popen(*popenargs, **kwargs) as process:
File "/usr/local/lib/python3.9/subprocess.py", line 951, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/local/lib/python3.9/subprocess.py", line 1821, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'kubectl apply -f deployment.yaml'

您可以使用Python执行kubectl命令,但您也可以使用Kubernetes API的Python客户端。

下面我将给出两个选项的示例。

使用Python执行kubectl命令

您可以使用子流程模块:

$ cat script-1.py
#!/usr/bin/python3.7
import subprocess
subprocess.run(["kubectl", "apply", "-f", "deployment.yaml"])

$ ./script-1.py
deployment.apps/web-app created

您也可以使用os模块:

$ cat script-1.py
#!/usr/bin/python3.7
import os
os.system("kubectl  apply -f deployment.yaml")
$ ./script-1.py
deployment.apps/web-app created

为kubernetes API使用Python客户端

如前所述,您还可以使用Python客户端来创建部署。

基于deployment_create.py示例,我创建了一个脚本,用于在default命名空间中部署deployment.yaml:

$ cat script-2.py
#!/usr/bin/python3.7
from os import path
import yaml
from kubernetes import client, config

def main():
config.load_kube_config()
with open(path.join(path.dirname(__file__), "deployment-1.yaml")) as f:
dep = yaml.safe_load(f)
k8s_apps_v1 = client.AppsV1Api()
resp = k8s_apps_v1.create_namespaced_deployment(
body=dep, namespace="default")
print("Deployment created. status='%s'" % resp.metadata.name)

if __name__ == '__main__':
main()
$ ./script-2.py
Deployment created. status='web-app'
$ kubectl get deployment
NAME      READY   UP-TO-DATE   AVAILABLE   
web-app   1/1     1            1   

相关内容

  • 没有找到相关文章

最新更新