简体   繁体   中英

How to kill kubectl port-forward on error?

I frequently encounter issues will kubectl port forwarding and want to write a bash script to auto-reconnect. How do you grep for something on a stream and "fail" when it's found? I've found questions like this for "tailing a file" but I don't want to write the output of kubectl to a log file and use a separate process to tail - that feels too complicated. Also I'm aware that grep -q doesn't work on steams eg see here .

So far I have tried this:

kubectl port-forward deployment/haproxy 8080:8080 | grep -q --line-buffered error

Which correctly prints

E0528 21:30:14.643696   95553 portforward.go:400] an error occurred forwarding 8080 -> 8080: error forwarding port 8080 to pod 7aa1822dab53ddd732bc8fdc9575e1820ab476be2be097a472eb838f5eec22b2, uid : exit status 1: 2021/05/29 01:30:14 socat[13287] E connect(5, AF=2 127.0.0.1:1883, 16): Connection refused

But how do I return after error so I can do something like this:

while :
do
  kubectl port-forward deployment/haproxy 8080:8080 | grep -q --line-buffered error | return on error
  echo "port forwarding failed trying again!"
done

How about.

#!/usr/bin/env bash

if kubectl port-forward deployment/haproxy 8080:8080 2>&1 |
  grep -Fq --line-buffered error; then
  printf >&2 "port forwarding failed trying again!\n" &&
  exit 
fi 

If it is inside a loop, replace exit with break .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM