Following code snipet uses kubeconfig python module and it takes the default kubeconfig file, and switch to a new context.
kubectl commands:
kubectl config get-contexts
kubectl config current-context
kubectl config use-context <context_name>
Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# prerequisite: pip3 install kubeconfig | |
# this code snipet can be used to switch to a different context | |
from kubeconfig import KubeConfig | |
import argparse | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument( | |
"-c", "--cluster", required=True, help="K8s cluster context name" | |
) | |
args = parser.parse_args() | |
new_context = args.cluster | |
conf = KubeConfig() | |
print("Kubeconfig file: ", conf.view()) | |
print("Current context: ", conf.current_context()) | |
conf.use_context(new_context) | |
print("Switched to context: ", conf.current_context()) | |
if __name__ == "__main__": | |
main() |
Note: If you want to use a specific kubeconfig file, instead of conf = KubeConfig()
you can use conf = KubeConfig('path-to-your-kubeconfig')
Reference:
https://kubeconfig-python.readthedocs.io/en/latest/
No comments:
Post a Comment