I am trying to execute the kubectl
command using python script but keep getting error. I have requirement to execute the kubectl
command to create pod and check the pod
log for any failure.
What am I doing wrong here?
import subprocess
command = 'kubectl apply -f deployment.yaml'
check_output= subprocess.check_output(command)
print(check_output)
error
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'
You can execute kubectl
commands with Python, but you can also use the Python client for the Kubernetes API.
Below I will give examples for both options.
You can use the subprocess module:
$ 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
You can also use the os module:
$ 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
As previously mentioned, you can also use a Python client to create a Deployment.
Based on the deployment_create.py example, I've created a script to deploy deployment.yaml
in the default
Namespace:
$ 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With