Home > Software engineering >  kubectl exec output not getting stored in variable
kubectl exec output not getting stored in variable

Time:10-02

I am trying to do a kubectl exec and store value into a variable. But the variable displays null. If i use -it in the exec, it works. Since while running with terraform says can't allocate terminal, I need to run it without -it.

Command I run: abc=$(kubectl exec nginx-6799fc88d8-xpzs9 -- nginx -v)

CodePudding user response:

You need to modify your command as following(-it):

abc=$(kubectl exec -it nginx-6799fc88d8-xpzs9 -- nginx -v)

The reason for this behavior is nginx -v is displaying the output over stderr not stdout. This means, the command you were using would work for any other commands like ls , cat etc which display output over stdout.

Alternate approach by redirecting stderr to stdout(2>&1) :

abc=$(kubectl exec nginx-6799fc88d8-xpzs9 -- nginx -v 2>&1)

Example:

x=$(k exec nginx  -- nginx -v 2>&1)
echo "$x"
nginx version: nginx/1.21.3

CodePudding user response:

As @P.... Mentioned alternative approach for replacing -it is using 2>&1

  • File descriptor 1 is the standard output (stdout).
  • File descriptor 2 is the standard error (stderr).
  • -i Pass stdin to the container(stdin)
  • -t Stdin is a TTY(tty)

Here is one way to remember this construct: at first, 2>1 may look like a good way to redirect stderr to stdout. However, it will actually be interpreted as "redirect stderr to a file named 1". & indicates that what follows and precedes is a file descriptor and not a filename. So the construct becomes: 2>&1.

Consider >& as a redirect merger operator.

For more details, refer this document on kubectl exec command.

  • Related