Creating a new Kubectl config context
In a previous post I discussed how to view and change the configuration context that kubectl is currently using. In this post I'll be going over how to create two new context configurations that point to a different kubernetes clusters and point to a specific namespace.
In my scenario I want to create two new contexts that make it easier to switch between two different (development and production) kubernetes clusters.
First, to familiarize ourselves with the environment(s) that kubectl is aware of we can check the contents of the kubectl config file located in .kube directory in our home folder.
$ ls -hlt ~/.kube total 40 drwxr-xr-x 120 user staff 3.8K May 31 09:27 http-cache -rw------- 1 user staff 16K May 29 15:56 config drwxr-xr-x 10 user staff 320B Oct 9 2017 schema drwxr-xr-x 3 user staff 96B Feb 13 2017 cache
The config file here contains information about any kubernetes cluster that has been used by kubectl. The config file contains a list of these 3 different types of resources that your kubectl already has configured access to.
To create a new context we will need 4 pieces of information:
- context_name - The name for the new context.
- cluster_name - The name of the cluster to connect to.
- user_name - The name of the credentials used to connect to the cluster.
- namespace_name - The namespace that all kubectl commands will apply in.
To create a development context named api-dev I will use a kubernetes cluster created in Google Cloud Platform, the development namespace, and a user that has the same name as the cluster in my ~/.kube/config file.
- context_name - api-dev
- cluster_name - gke_project-name-123_us-central1-a_my-gke-cluster-1
- user_name - gke_project-name-123_us-central1-a_my-gke-cluster-1
- namespace_name - development
kubectl config set-context api-dev \ --cluster=gke_project-name-123_us-central1-a_my-gke-cluster-1 \ --namespace=development \ --user=gke_project-name-123_us-central1-a_my-gke-cluster-1
To create a production context I will use a KOPS kubernetes cluster I created, the api-production namespace, and a user configured with basic authentication:
- context_name - api-prod
- cluster_name - kops.mydomain.com
- user_name - kops.mydomain.com-basic-auth
- namespace_name - api-production
kubectl config set-context api-prod \ --cluster=kops.mydomain.com \ --namespace=api-production \ --user=kops.mydomain.com-basic-auth
Now you can toggle between these different context configurations by running one of the following.
kubectl config set-context api-dev or kubectl config set-context api-prod