3

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
  • 8,411
  • 8
  • 43
  • 79
  • 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

7

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
  • 1,707
  • 2
  • 12
  • 25
  • 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
  • 4
    @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
2

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
  • 204
  • 1
  • 1