samisaviv
samisaviv

Reputation: 323

Add timeout to Kubctl exec command

I have python 2.7 code that for each 1 min run command on running pods with the following:

file_exist = subprocess. \
    check_output("kubectl exec -it  " + pod_name + " -- ls " +
                 path + " >> /dev/null 2>&1 && echo yes || echo no", shell=True).rstrip()
return file_exist == "yes"

The problem I face with is kubectl exec command sometimes hang, How can I add timeout to kubectl command to prevent my code to hang on kubectl exec command?

Upvotes: 1

Views: 1589

Answers (2)

Shashank V
Shashank V

Reputation: 11193

If you are running kubectl out of cluster(i.e., not inside a pod), then you can use --request-timeout option of kubectl .

From docs

--request-timeout string     Default: "0"
The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests. 

If you are running kubectl in-cluster(inside a pod using in-cluster config), then --request-timeout currently does not work. You can use the timeout parameter of subprocess.check_output. subprocess.TimeoutExpired exception is raised if the command times out.

https://docs.python.org/3/library/subprocess.html#subprocess.check_output

Upvotes: 0

Vikas Mulaje
Vikas Mulaje

Reputation: 765

Use timeout parameter In check_output()

file_exist = subprocess. \
    check_output("kubectl exec -it  " + pod_name + " -- ls " +
                 path + " >> /dev/null 2>&1 && echo yes || echo no", shell=True,timeout=300).rstrip()
return file_exist == "yes"

https://docs.python.org/3/library/subprocess.html#subprocess.check_output

for kubectl exec timeout you can use --request-timeout=30s

Upvotes: 2

Related Questions