Search code examples
bashkubectl

kubectl exec output not getting stored in variable


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)


Solution

  • 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