kubectl bash completion doesn't work in ubuntu docker container

5/18/2018

I'm using kubectl from within a docker container running on a Mac. I've already successfully configured the bash completion for kubectl to work on the Mac, however, it doesn't work within the docker container. I always get bash: _get_comp_words_by_ref: command not found.

The docker image is based on ubuntu:16.04 and kubectl is installed via the line (snippet from the dockerfile)

curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl && \
mv kubectl /usr/local/bin

echo $BASH_VERSION gives me 4.3.48(1)-release, and according to apt, the bash-completionpackage is installed.

I'm using iTerm2 as terminal.

Any idea why it doesn't work or how to get it to work?

-- DonGiovanni
autocomplete
bash
docker
kubectl
kubernetes

2 Answers

5/18/2018

A Linux container executed on macOS creates a separate environment and yes, it looks like a thread from macOS shell, but it is not. Shell history, properties, functions are a different story. Moreover, if the container has no persistent volume mounted all of those parameters will be transisten and won’t survive container’s restart.

The approach to have bash completion of both of them - macOS and Ubuntu Linux are similar, but require different steps to take:

macOS side - permanent support for kubectl bash completion:

use homebrew to install support:

brew install bash-completion
kubectl completion bash > $(brew --prefix)/etc/bash_completion.d/kubectl

Ubuntu container’s approach to have kubectl and bash completion support build in:

You can adapt this set of commands and use it in Dockerfile during the image preparation:

apt-get update && apt-get install -y apt-transport-https
curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -
cat <<EOF >/etc/apt/sources.list.d/kubernetes.list
deb http://apt.kubernetes.io/ kubernetes-xenial main
EOF
apt-get update
apt-get install -y kubectl
echo 'source <(kubectl completion bash)' >> ~/.bashrc

If afterwards you or user executes /bin/bash in running container then you should get completion working.

docker exec -it docker_image_id /bin/bash

this will start bash shell with the bash completion.

-- d0bry
Source: StackOverflow

5/30/2018

Ok, I found it - I simply needed to do a source /etc/bash_completion before or after the source <(kubectl completion bash).

-- DonGiovanni
Source: StackOverflow