Thursday, October 5, 2017

kubernetes: How to Use Kubectl Context to Switch User and Cluster

context

Kubernetes Context Setting

One can connect to different remote Cluster and with different namespace via a single client. And the single client must to install kubectl to access multiple clusters.

Assume 172.16.155.158:8080 is an k8s api-server, you can use the following command to setup different context and connect with switch context to different cluster (an k8s cluter).

So it's very easy, that you can control different kubernetes cluster via single client with execution file kubectl and context setting.

Create Cluster and Context

kubectl config set-cluster firstcluster --server=http://172.16.155.158:8080 --insecure-skip-tls-verify=true
kubectl config set-context firstctx --cluster=firstcluster --namespace=inq
kubectl config use-context firstctx

where --server is connect to the api-server.

root@kuberm:~# kubectl config view
apiVersion: v1
clusters:
- cluster:
    insecure-skip-tls-verify: true
    server: http://172.16.155.158:8080
  name: firstcluster
contexts:
- context:
    cluster: firstcluster
    namespace: inq
    user: ""
  name: ctx-first
- context:
    cluster: firstcluster
    namespace: inq
    user: ""
  name: firstctx
current-context: firstctx
kind: Config
preferences: {}
users: []

Multiple Context

of course you might need another cluster that have another api-server, you then can directly connect to different cluster via the context switch.

The following is the two cluster with two context shown in .kube/config

root@kuberm:~# cat .kube/config
apiVersion: v1
clusters:
- cluster:
    insecure-skip-tls-verify: true
    server: http://172.16.155.158:8080
  name: firstcluster
- cluster:
    insecure-skip-tls-verify: true
    server: http://172.16.155.158:8080
  name: secondcluster
contexts:
- context:
    cluster: firstcluster
    namespace: inq
    user: ""
  name: firstctx
- context:
    cluster: secondcluster
    namespace: inq
    user: ""
  name: secondctx
current-context: firstctx
kind: Config
preferences: {}
users: []

Connect to Pod to Program

In the context environment, you can access the pods limited in namespace you used.

root@kubecontext:~# kubectl config current-context
ctx-default
root@kubecontext:~# kubectl get po
NAME               READY     STATUS    RESTARTS   AGE
webserver1-llgxz   1/1       Running   0          2h
webserver1-qt3nd   0/1       Unknown   0          70d
webserver2-94vjs   1/1       Running   1          70d
root@kubecontext:~# kubectl exec -it webserver2-94vjs -- bash
root@webserver2-94vjs:/#

Now you can connect to container in the context environment.

Release Context

If you want to release or reset the context

rm .kube/config

No comments:

Post a Comment