kubectl
should support port-forwarding with service name but it doesn'tk9s
does though 👍🏼- So this script mimics its behavior
credits:
- maintain as a repo instead of gist
- publish as a kubectl plugin
kubectl
should support port-forwarding with service name but it doesn'tk9s
does though 👍🏼credits:
#!/usr/bin/env bash | |
set -e | |
command -v kubectl > /dev/null || (echo "kubectl not detected and exiting." && exit 1) | |
function print_usage { | |
echo "usage:" | |
echo "pfs.sh SERVICE_NAME PORTS" | |
echo "" | |
echo "examples:" | |
echo '- `pfs.sh prometheus 9090`' | |
echo '- `KUBE_NAMESPACE=my-namespace pfs.sh prometheus 9090:10090`' | |
echo '- `export KUBE_NAMESPACE=my-namespace; pfs.sh prometheus 9090 9093`' | |
echo "" | |
echo 'run `kubectl port-forward -h` to get more help' | |
} | |
svc="$1" | |
if test -z "${svc}"; then | |
print_usage | |
exit 1 | |
fi | |
shift | |
ports="$@" | |
if test -z "${ports}"; then | |
print_usage | |
exit 1 | |
fi | |
if test -n "${KUBE_NAMESPACE}"; then | |
namespace=" -n ${KUBE_NAMESPACE} " | |
else | |
namespace="" | |
fi | |
ip_addrs="$(kubectl ${namespace} get ep $svc -o=jsonpath='{.subsets[*].addresses[*].ip}' | tr ' ' '\n')" | |
random="$(echo "${ip_addrs}" | shuf | head -n1)" | |
podname="$(echo "${random}" | xargs -I % kubectl ${namespace} get pods -o=name --field-selector=status.podIP=%)" | |
echo "${podname} is selected for ${svc}" | |
kubectl ${namespace} port-forward $podname $ports |