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)
2
Answers
You need to modify your command as following(
-it
):The reason for this behavior is
nginx -v
is displaying the output overstderr
notstdout
. This means, the command you were using would work for any other commands likels
,cat
etc which display output overstdout
.Alternate approach by redirecting stderr to stdout(
2>&1
) :Example:
As @P…. Mentioned alternative approach for replacing -it is using 2>&1
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.