8000 - Add context switch to kube config loader · kubernetes-client/python@c7d3c7c · GitHub
[go: up one dir, main page]

Skip to content

Commit c7d3c7c

Browse files
committed
- Add context switch to kube config loader
- Refactor kube config loader to be able to test it - Add test for kube config loader
1 parent c177b5f commit c7d3c7c

File tree

4 files changed

+689
-112
lines changed

4 files changed

+689
-112
lines changed

examples/example4.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# Copyright 2016 The Kubernetes Authors.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import os
16+
17+
from kubernetes import client, config
18+
from kubernetes.client import configuration
19+
20+
21+
def main():
22+
config_file = os.environ["HOME"] + '/.kube/config'
23+
contexts, active_context = config.list_kube_config_context(config_file)
24+
if not contexts:
25+
print("Cannot find any context in kube-config file.")
26+
return
27+
for i in range(len(contexts)):
28+
format_str = "%d. %s"
29+
if contexts[i]['name'] == active_context['name']:
30+
format_str = "* " + format_str
31+
print(format_str % (i, contexts[i]['name']))
32+
context = input("Enter context number: ")
33+
context = int(context)
34+
if context not in range(len(contexts)):
35+
print(
36+
"Number out of range. Using default context %s." %
37+
active_context)
38+
return
39+
else:
40+
context_name = contexts[context]['name']
41+
42+
# Configs can be set in Configuration class directly or using helper
43+
# utility
44+
config.load_kube_config(os.environ["HOME"] + '/.kube/config', context_name)
45+
46+
print("Active host is %s" % configuration.host)
47+
48+
v1 = client.CoreV1Api()
49+
print("Listing pods with their IPs:")
50+
ret = v1.list_pod_for_all_namespaces(watch=False)
51+
for i in ret.items:
52+
print("%s\t%s\t%s" %
53+
(i.status.pod_ip, i.metadata.namespace, i.metadata.name))
54+
55+
56+
if __name__ == '__main__':
57+
main()

kubernetes/config/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,5 @@
1414

1515
from .config_exception import ConfigException
1616
from .incluster_config import load_incluster_config
17+
from .kube_config import list_kube_config_context
1718
from .kube_config import load_kube_config

0 commit comments

Comments
 (0)
100
0