Home > Back-end >  Enable tab auto completion for kubectl in bash function
Enable tab auto completion for kubectl in bash function

Time:06-30

Given a bash function in .bashrc such as

kgp () {
  kubectl get po -n $1 $2
}

Is it possible to have kubectl auto complete work for k8s resources such as namespaces/pods? As an example if I use

kubectl get po -n nsprefix podprefix

I can tab auto complete the prefix. Whereas with the positional parameters when I call

kgp nsprefix podprefix

I have to type out the entire resource name.

CodePudding user response:

Yes, that's because bash-completion only understands known commands, not aliases or new functions that you have made up. You will experience the same thing with a trivial example of alias whee=/bin/ls and then whee <TAB> will do nothing because it doesn't "recurse" into that alias, and for sure does not attempt to call your function in order to find out what arguments it could possibly accept. That could potentially be catastrophic

You're welcome to create a new complete handler for your custom kgp, but that's the only way you'll get the desired behavior

_kgp_completer() {
    local cur prev words cword

    COMPREPLY=()
    _get_comp_words_by_ref -n : cur prev words cword
    if [[ $cword == 1 ]] && [[ -z "$cur" ]]; then
        COMPREPLY=( $(echo ns1 ns2 ns3) )
    elif [[ $cword == 2 ]] && [[ -z "$cur" ]]; then
        COMPREPLY=( $(echo pod1 pod2 pod3) )
    fi
    echo "DEBUG: cur=$cur prev=$prev words=$words cword=$cword COMPREPLY=${COMPREPLY[@]}" >&2
}
complete -F _kgp_completer kgp
  • Related