Last active
May 12, 2024 12:18
-
-
Save caruccio/245ecf15d35b4496d86d5c86bebe66f0 to your computer and use it in GitHub Desktop.
Kubectl port-forward with fzf service selector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
## | |
## kubectl port-forward on selected services, combined by all service ports. | |
## | |
function kpfz() | |
{ | |
local svc_ports_command="jq -r '.items[] | | |
{ | |
name: .metadata.name, | |
port: .spec.ports[].port | tonumber, | |
lport: (\"\\(.metadata.name)\") | explode | add | |
} | | |
\"\\(.name):\\(.port):\\(.lport + .port)\" | |
'" | |
local svcs=$( | |
FZF_DEFAULT_COMMAND="command kubectl get svc -o json $_NS | $svc_ports_command" \ | |
fzf -m --ansi --no-preview -1 --exact --select-1 --query="$@" | |
) | |
if [ -z "$svcs" ]; then | |
return | |
fi | |
pids=() | |
for svc in $svcs; do | |
local name=$(cut -d: -f1 <<<$svc) | |
local port=$(cut -d: -f2 <<<$svc) | |
local lport=$(cut -d: -f3 <<<$svc) | |
local cmd="kubectl port-forward $_NS svc/$name $lport:$port" | |
echo "+ $cmd" | |
command $cmd & pids+=($!) | |
done | |
trap "echo -e '\nKilling pids: ${pids[*]}'; kill -INT ${pids[*]}" SIGINT SIGTERM SIGHUP EXIT | |
wait | |
trap - SIGINT SIGTERM SIGHUP EXIT | |
sleep 1 # give a chance to prompt appear | |
} | |
## | |
## Same as kpfz, but for a specifc namespace | |
## | |
function kpfzn() | |
{ | |
local ns="$1" | |
shift | |
_NS="-n $ns" kpfz "$@" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment