9

I want to run a local script within Kubernetes pod and then set the output result to a linux variable

Here is what I tried:

# if I directly run -c "netstat -pnt |grep ssh", I get output assigned to $result:

cat check_tcp_conn.sh 
#!/bin/bash
result=$(kubectl exec -ti <pod_name> -- /bin/bash -c "netstat -pnt |grep ssh")
echo "result is $result"

What I want is something like this:

#script to be called:
cat netstat_tcp_conn.sh
#!/bin/bash
netstat -pnt |grep ssh

#script to call netstat_tcp_conn.sh:
cat check_tcp_conn.sh 
#!/bin/bash
result=$(kubectl exec -ti <pod_name> -- 
/bin/bash -c "./netstat_tcp_conn.sh)
echo "result is $result

the result showed result is /bin/bash: ./netstat_tcp_conn.sh: No such file or directory.

How can I let Kubernetes pod execute netstat_tcp_conn.sh which is at my local machine?

user389955
  • 9,605
  • 14
  • 56
  • 98
  • you need to somehow mount the script within the running pod, check for different ways of mounting the script within a pod. – Krishna Chaurasia Feb 03 '21 at 06:19
  • Krishna: I know we can use -v in docker to mount, or configure mount in k8s configuration file. But how to mount a local file from Kubernetes exec command directly? – user389955 Feb 03 '21 at 06:56
  • I don't think we can do that from the exec command. I believe we need to mount the file first and then run exec as it is or may be use mix of `cat` and `xargs` to pass the output of the file directly to the `exec` command. – Krishna Chaurasia Feb 03 '21 at 06:57

2 Answers2

14

You can use following command to execute your script in your pod:

kubectl exec POD -- /bin/sh -c "`cat netstat_tcp_conn.sh`"
Ali Tou
  • 2,009
  • 2
  • 18
  • 33
  • 1
    @Ali Tou how this command will execute if `netstat_tcp_conn.sh` dosen't exists inside pod or it exists inside pod? – heheh Feb 05 '21 at 04:46
  • 5
    @heheh it doesn't depend on the contents of the pod at all. That `cat netstat_tcp_conn.sh` will be evaluated by your shell on client-side, before running `kubectl exec`. – Ali Tou Feb 05 '21 at 07:19
  • You 're the best, thanx – DimiDak Jan 13 '22 at 12:20
  • @AliTou Is there a way to pass an argument to the script while executing it in the mentioned manner? – Elvin Varghese Nov 03 '22 at 15:11
  • @ElvinVarghese I don't think so. The only thing comes to my mind is that you can set environment variables before running that command so that some variables substitutions can be done. I don't have anything else of passing a variable to that script. – Ali Tou Nov 03 '22 at 18:11
  • @AliTou Thanks for reply. I tried with "foo=bar && `cat script.sh`", and value seems to be getting passed on to the script. – Elvin Varghese Nov 04 '22 at 10:09
3

You can copy local files into pod using kubectl command like kubectl cp /tmp/foo :/tmp/
Then you can change its permission and make it executable and run it using kubectl exec.

Rushikesh
  • 222
  • 1
  • 1