Skip to content

Instantly share code, notes, and snippets.

@ryuheechul
Last active August 5, 2021 16:53
Show Gist options
  • Save ryuheechul/7c5b135d166234202f9fbeb42feb32f8 to your computer and use it in GitHub Desktop.
Save ryuheechul/7c5b135d166234202f9fbeb42feb32f8 to your computer and use it in GitHub Desktop.
kubectl port-forward service made easy

A script to port-forward via Service name

  • kubectl should support port-forwarding with service name but it doesn't
  • k9s does though 👍🏼
  • So this script mimics its behavior

credits:

Roadmap (maybe)

  • maintain as a repo instead of gist
  • publish as a kubectl plugin
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment