Search code examples
powershellkubectl

powershell pipe escaping in kubectl exec


How can I send a simple pipe via kubectl exec on powershell? single commands and parameters work fine.

Works fine in linux and kubectl shell inside rancher:

$> kubectl exec test12-7b7fd6b4f4-wzp59 --namespace=test12 -- dmesg | tail -1
[562119.054019] oom_reaper: reaped process 2410 (supervisorctl), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB

kubectl exec needs the -- dmesg | tail -1 to be unquoted, but then powershell catches it:

PS> kubectl exec test12-7b7fd6b4f4-wzp59 --namespace=test12 -- dmesg | tail -1
tail : The term 'tail' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:168
+ ... namespace=test12 -- dmesg | tail -1
+                                                                  ~~~~
    + CategoryInfo          : ObjectNotFound: (tail:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

if I quote it kubectl complains:

PS> kubectl exec test12-7b7fd6b4f4-wzp59 --namespace=test12 -- "dmesg | tail -1"
OCI runtime exec failed: exec failed: unable to start container process: exec: "dmesg | tail -1": executable file not found in $PATH: unknown
command terminated with exit code 126

Commands and parameters work:

PS> kubectl exec test12-7b7fd6b4f4-wzp59 --namespace=test12 -- ls -l /var/log/lastlog 
-rw-rw-r-- 1 root utmp 2920292 Jan 27 09:56 /var/log/lastlog

I found this link and have tried all of them even the stop parse --% but none worked: https://www.octopus.com/blog/powershell-pipe-escaping

A naive workaround is to create aliases in the container when building it: alias ll='dmesg|tail -1'

and append it to ~./bashrc


Solution

  • pipe works if you wrap it into a sh command:

    ps> kubectl exec id-pro-trk-trk-user-portal-web-production-747b88964c-rqt75 \
     --namespace=id-pro-trk-trk-user-portal-web-production \
     -- sh -c 'wget -O- http://localhost:8082/user-portal/bp-internal/info | grep version'
    

    output:

    Connecting to localhost:8082 (127.0.0.1:8082)
    writing to stdout
    -                    100% |********************************|   818  0:00:00 ETA
    written to stdout
      "version" : "1.10.247",