kubectl Usage Patterns#

Use one KUBECONFIG file per environment#

We usually create one KUBECONFIG file per environment and put them into ~/.kube with a shared prefix, e.g.

~/.kube/
├── foo_dev.yml
├── foo_prod.yml
└── foo_test.yml

To use them we set KUBECONFIG accordingly, e.g.

export KUBECONFIG=~/.kube/foo_dev.yml
kubectl version

One benefit of this approach is that we can version those files locally, for example:

cd ~/.kube
git init .
git add .
git commit -m initial

Use kubectl contexts#

When working on a specific namespace of a cluster, use kubectl context to set it once.

# remember cluster and user of current context (--minify)
cluster=$(kubectl config view --minify -o jsonpath='{.contexts[0].context.cluster}')
user=$(kubectl config view --minify -o jsonpath='{.contexts[0].context.user}')

# create new context "prometheus" for namespace "prometheus"
kubectl config set-context prometheus --namespace=prometheus --cluster=$cluster --user=$user

# use the context "prometheus"
kubectl config use-context prometheus