Switching Between Contexts
Once you have multiple contexts defined in your kubeconfig
file, you can easily switch between them using the kubectl config use-context
command.
Here's an example of how to switch between contexts:
## List the available contexts
kubectl config get-contexts
## Switch to a different context
kubectl config use-context another-context
## Verify the current context
kubectl config current-context
In this example, we first list the available contexts using the kubectl config get-contexts
command. This will show all the contexts defined in the kubeconfig
file.
Next, we switch to the another-context
context using the kubectl config use-context
command. This will update the current context in the kubeconfig
file, and all subsequent kubectl
commands will use the new context.
Finally, we verify the current context using the kubectl config current-context
command, which should now display another-context
.
You can also set the current context programmatically by modifying the kubeconfig
file directly. Here's an example:
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: <base64-encoded-ca-cert>
server: https://kubernetes.example.com
name: my-cluster
contexts:
- context:
cluster: my-cluster
user: my-user
namespace: my-namespace
name: my-context
- context:
cluster: another-cluster
user: another-user
namespace: another-namespace
name: another-context
current-context: another-context
kind: Config
preferences: {}
users:
- name: my-user
user:
client-certificate-data: <base64-encoded-client-cert>
client-key-data: <base64-encoded-client-key>
- name: another-user
user:
client-certificate-data: <base64-encoded-client-cert>
client-key-data: <base64-encoded-client-key>
In this example, we've set the current-context
field to another-context
, which means that the Kubernetes client will use the another-context
context by default.
By switching between contexts, you can easily manage and interact with different Kubernetes clusters and environments without having to reconfigure the connection details each time.