I created a connection to remote K8s server with username and password. How can I get current-context like using command: "kubectl config current-context"
@hoangphuocbk you can use config.list_kube_config_contexts()[1] to get the current context.
Thank @nurus ^^
This seems to just return the context at position [1] from all your available contexts.
Is there a way to get the currently active one?
@richstokes No, it returns a tuple (all_context, current) so list_kube_config_contexts()[1] gives you the current context.
How to select specific context?
To select specific context:
kubernetes.config.load_kube_config(
config_file=os.environ['KUBECONFIG'],
context="my-context")
This will set configuration for kubernetes.client. It won't change your kubectl context, just internally for that specific object of kubernetes.client.
How does this work for load_incluster_config()? From what I can tell, it doesn't. If that's so, I'd appreciate a generic solution that works within and without.
I was also looking for a way to change context when using load_incluster_config() until I realized that doesn't make sense. Why? Context is the combination of cluster, namespace and user. So @adubkov has the right answer - always use load_kube_config() if you want to the ability to specify the context to use.
Most helpful comment
@richstokes No, it returns a tuple (all_context, current) so
list_kube_config_contexts()[1]gives you the current context.