fairburg

Setting up port-forwards with kubectl can be annoying, either you need use a new terminal window or you try and use your shells background jobs.

Here is a fish function to set up a port-forwards as an auto-restarting systemd unit that runs in the background:

function pf --description "Set up a port-forward with kubectl" --wraps "kubectl port-forward"
    set -l cmd (string join ' ' $argv)
    set -l context (kubectl config current-context)
    set -l namespace (kubectl config view --minify -o jsonpath='{..namespace}')
    if test -z "$namespace"
        echo "Namespace not set in current context" >&2
        return 1
    end
    systemd-run --user --collect --unit portforward 
        --description="port-forward $cmd" 
        --property=Restart=on-failure 
        --property=RestartSec=2 
        fish -c "kubectl --context $context --namespace $namespace port-forward $cmd"
end

The —wraps option enables the usual tab completion you’d get from running kubectl directly

To make sure you don’t forget about an active port-forward, I’ve integrated this in my starship prompt:

[custom.portforward]
command = "systemctl --user show --property=Description portforward.service | sed 's/Description=//'"
when = "systemctl --user is-active --quiet portforward.service"
format = "[$output](bold green) "

And then I have two small helpers to avoid having to type systemctl —user to check the port-forward and stop it again:

function pfe --description "Stop the port-forward unit"
    systemctl --user is-active portforward >/dev/null
    if test $status -ne 0
        echo "portforward unit is not active" >&2
        return 1
    end
    systemctl --user stop portforward
end
function pfs --description "Show the status of port-forwarding"
    systemctl --user status portforward
end