本文整理匯總了Python中kubernetes.config.load_kube_config方法的典型用法代碼示例。如果您正苦於以下問題:Python config.load_kube_config方法的具體用法?Python config.load_kube_config怎麽用?Python config.load_kube_config使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類kubernetes.config
的用法示例。
在下文中一共展示了config.load_kube_config方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: main
# 需要導入模塊: from kubernetes import config [as 別名]
# 或者: from kubernetes.config import load_kube_config [as 別名]
def main():
contexts, active_context = config.list_kube_config_contexts()
if not contexts:
print("Cannot find any context in kube-config file.")
return
contexts = [context['name'] for context in contexts]
active_index = contexts.index(active_context['name'])
option, _ = pick(contexts, title="Pick the context to load",
default_index=active_index)
# Configs can be set in Configuration class directly or using helper
# utility
config.load_kube_config(context=option)
print("Active host is %s" % configuration.Configuration().host)
v1 = client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for item in ret.items:
print(
"%s\t%s\t%s" %
(item.status.pod_ip,
item.metadata.namespace,
item.metadata.name))
示例2: get_conn
# 需要導入模塊: from kubernetes import config [as 別名]
# 或者: from kubernetes.config import load_kube_config [as 別名]
def get_conn(self):
"""
Returns kubernetes api session for use with requests
"""
connection = self.get_connection(self.conn_id)
extras = connection.extra_dejson
if extras.get("extra__kubernetes__in_cluster"):
self.log.debug("loading kube_config from: in_cluster configuration")
config.load_incluster_config()
elif extras.get("extra__kubernetes__kube_config") is None:
self.log.debug("loading kube_config from: default file")
config.load_kube_config()
else:
with tempfile.NamedTemporaryFile() as temp_config:
self.log.debug("loading kube_config from: connection kube_config")
temp_config.write(extras.get("extra__kubernetes__kube_config").encode())
temp_config.flush()
config.load_kube_config(temp_config.name)
return client.ApiClient()
示例3: get_k8s_nodes
# 需要導入模塊: from kubernetes import config [as 別名]
# 或者: from kubernetes.config import load_kube_config [as 別名]
def get_k8s_nodes(exclude_node_label_key=app_config["EXCLUDE_NODE_LABEL_KEY"]):
"""
Returns a list of kubernetes nodes
"""
try:
config.load_incluster_config()
except config.ConfigException:
try:
config.load_kube_config()
except config.ConfigException:
raise Exception("Could not configure kubernetes python client")
k8s_api = client.CoreV1Api()
logger.info("Getting k8s nodes...")
response = k8s_api.list_node()
if exclude_node_label_key is not None:
nodes = []
for node in response.items:
if exclude_node_label_key not in node.metadata.labels:
nodes.append(node)
response.items = nodes
logger.info("Current k8s node count is {}".format(len(response.items)))
return response.items
示例4: delete_node
# 需要導入模塊: from kubernetes import config [as 別名]
# 或者: from kubernetes.config import load_kube_config [as 別名]
def delete_node(node_name):
"""
Deletes a kubernetes node from the cluster
"""
try:
config.load_incluster_config()
except config.ConfigException:
try:
config.load_kube_config()
except config.ConfigException:
raise Exception("Could not configure kubernetes python client")
configuration = client.Configuration()
# create an instance of the API class
k8s_api = client.CoreV1Api(client.ApiClient(configuration))
logger.info("Deleting k8s node {}...".format(node_name))
try:
if not app_config['DRY_RUN']:
k8s_api.delete_node(node_name)
else:
k8s_api.delete_node(node_name, dry_run="true")
logger.info("Node deleted")
except ApiException as e:
logger.info("Exception when calling CoreV1Api->delete_node: {}".format(e))
示例5: __init__
# 需要導入模塊: from kubernetes import config [as 別名]
# 或者: from kubernetes.config import load_kube_config [as 別名]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Load kubernetes config here, since this is a Singleton and
# so this __init__ will be run way before anything else gets run.
try:
config.load_incluster_config()
except config.ConfigException:
config.load_kube_config()
self.api = shared_client(self.api_group_name)
# FIXME: Protect against malicious labels?
self.label_selector = ','.join(['{}={}'.format(k, v) for k, v in self.labels.items()])
self.field_selector = ','.join(['{}={}'.format(k, v) for k, v in self.fields.items()])
self.first_load_future = Future()
self._stop_event = threading.Event()
self.start()
示例6: main
# 需要導入模塊: from kubernetes import config [as 別名]
# 或者: from kubernetes.config import load_kube_config [as 別名]
def main():
config.load_kube_config()
api_instance = client.CoreV1Api()
body = {
"metadata": {
"labels": {
"foo": "bar",
"baz": None}
}
}
api_response = api_instance.patch_node("minikube", body)
pprint(api_response)
示例7: main
# 需要導入模塊: from kubernetes import config [as 別名]
# 或者: from kubernetes.config import load_kube_config [as 別名]
def main():
# Configs can be set in Configuration class directly or using helper
# utility. If no argument provided, the config will be loaded from
# default location.
config.load_kube_config()
print("Supported APIs (* is preferred version):")
print("%-40s %s" %
("core", ",".join(client.CoreApi().get_api_versions().versions)))
for api in client.ApisApi().get_api_versions().groups:
versions = []
for v in api.versions:
name = ""
if v.version == api.preferred_version.version and len(
api.versions) > 1:
name += "*"
name += v.version
versions.append(name)
print("%-40s %s" % (api.name, ",".join(versions)))
示例8: __init__
# 需要導入模塊: from kubernetes import config [as 別名]
# 或者: from kubernetes.config import load_kube_config [as 別名]
def __init__(self) -> None:
kube_config.load_kube_config(
config_file=os.environ.get("KUBECONFIG", KUBE_CONFIG_PATH),
context=os.environ.get("KUBECONTEXT"),
)
models.V1beta1PodDisruptionBudgetStatus.disrupted_pods = property(
fget=lambda *args, **kwargs: models.V1beta1PodDisruptionBudgetStatus.disrupted_pods(
*args, **kwargs
),
fset=_set_disrupted_pods,
)
self.deployments = kube_client.AppsV1Api()
self.core = kube_client.CoreV1Api()
self.policy = kube_client.PolicyV1beta1Api()
self.apiextensions = kube_client.ApiextensionsV1beta1Api()
self.custom = kube_client.CustomObjectsApi()
self.autoscaling = kube_client.AutoscalingV2beta1Api()
self.request = kube_client.ApiClient().request
示例9: copy_job_config
# 需要導入模塊: from kubernetes import config [as 別名]
# 或者: from kubernetes.config import load_kube_config [as 別名]
def copy_job_config(src_dir, namespace):
config.load_kube_config()
v1 = k8s_client.CoreV1Api()
nfs_server_pod = None
ret = v1.list_namespaced_pod(namespace, watch=False)
for i in ret.items:
if(i.metadata.labels.get("role") != None) & (i.metadata.labels.get("role") == "nfs-server"):
nfs_server_pod = i.metadata.name
if nfs_server_pod is None:
logging.info("nfs server pod NOT found")
return 0
cmd = "kubectl -n " + namespace + " exec " + nfs_server_pod + " -- mkdir -p /exports/config"
util.run(cmd.split(), cwd=src_dir)
cmd = "kubectl cp examples/tf_cnn_benchmarks/job_config.yaml " + namespace + \
"/" + nfs_server_pod + ":/exports/config/job-config.yaml"
util.run(cmd.split(), cwd=src_dir)
return 1
示例10: get_registry_service_ip
# 需要導入模塊: from kubernetes import config [as 別名]
# 或者: from kubernetes.config import load_kube_config [as 別名]
def get_registry_service_ip(namespace, svc_name):
ip = None
try:
openshift_config.load_kube_config()
api = kubernetes_client.CoreV1Api()
service = api.read_namespaced_service(namespace=namespace, name=svc_name)
if service is None:
print("Couldn't find docker-registry service in namespace default. Erroring.")
return None
if service.spec.ports == []:
print("Service spec appears invalid. Erroring.")
return None
ip = service.spec.cluster_ip + ":" + str(service.spec.ports[0].port)
print("Found registry IP at: " + ip)
except ApiException as e:
print("Exception occurred trying to find %s service in namespace %s: %s" % (svc_name, namespace, e))
return None
return ip
示例11: create_project
# 需要導入模塊: from kubernetes import config [as 別名]
# 或者: from kubernetes.config import load_kube_config [as 別名]
def create_project(project):
print("Creating project {}".format(project))
try:
openshift_config.load_kube_config()
api = openshift_client.OapiApi()
api.create_project_request({
'apiVersion': 'v1',
'kind': 'ProjectRequest',
'metadata': {
'name': project
}
})
print("Created project")
# TODO: Evaluate the project request to get the actual project name
return project
except ApiException as e:
if e.status == 409:
print("Project {} already exists".format(project))
return project
else:
raise e
示例12: create_service_account
# 需要導入模塊: from kubernetes import config [as 別名]
# 或者: from kubernetes.config import load_kube_config [as 別名]
def create_service_account(name, namespace):
print("Creating service account in {}".format(namespace))
try:
kubernetes_config.load_kube_config()
api = kubernetes_client.CoreV1Api()
api.create_namespaced_service_account(
namespace,
{
'apiVersion': 'v1',
'kind': 'ServiceAccount',
'metadata': {
'name': name,
'namespace': namespace,
},
}
)
print("Created service account")
return name
except ApiException as e:
if e.status == 409:
print("Service account {} already exists".format(name))
return name
raise e
示例13: watch_pod
# 需要導入模塊: from kubernetes import config [as 別名]
# 或者: from kubernetes.config import load_kube_config [as 別名]
def watch_pod(name, namespace):
kubernetes_config.load_kube_config()
api = kubernetes_client.CoreV1Api()
while True:
sleep(WATCH_POD_SLEEP)
pod_status = api.read_namespaced_pod(name, namespace).status
pod_phase = pod_status.phase
print("Pod in phase: {}".format(pod_phase))
if pod_phase == 'Succeeded' or pod_phase == 'Failed':
print(api.read_namespaced_pod_log(name, namespace))
return pod_phase
if pod_phase == 'Pending':
try:
reason = pod_status.container_statuses[0].state.waiting.reason
except ApiException:
pass
if reason == 'ImagePullBackOff':
raise ApiException("APB failed {} - check name".format(reason))
示例14: _configure_k8s
# 需要導入模塊: from kubernetes import config [as 別名]
# 或者: from kubernetes.config import load_kube_config [as 別名]
def _configure_k8s(self):
k8s_config_file = os.environ.get('KUBECONFIG')
if k8s_config_file:
try:
logging.info('Loading kubernetes config from the file %s', k8s_config_file)
config.load_kube_config(config_file=k8s_config_file)
except Exception as e:
raise RuntimeError('Can not load kube config from the file %s, error: %s', k8s_config_file, e)
else:
try:
config.load_incluster_config()
logging.info('Initialized with in-cluster config.')
except:
logging.info('Cannot find in-cluster config, trying the local kubernetes config. ')
try:
config.load_kube_config()
logging.info('Found local kubernetes config. Initialized with kube_config.')
except:
raise RuntimeError('Forgot to run the gcloud command? Check out the link: \
https://cloud.google.com/kubernetes-engine/docs/how-to/cluster-access-for-kubectl for more information')
self._api_client = k8s_client.ApiClient()
self._corev1 = k8s_client.CoreV1Api(self._api_client)
return True
示例15: _k8s_client
# 需要導入模塊: from kubernetes import config [as 別名]
# 或者: from kubernetes.config import load_kube_config [as 別名]
def _k8s_client():
try:
if not CONF.kubernetes.config_file:
LOG.warning('kubernetes config file is not defined')
return
kubeconf = CONF.kubernetes.config_file
config.load_kube_config(config_file=kubeconf)
k8s_client = client.CoreV1Api()
if k8s_client is None:
LOG.warning('k8s client returns None')
return
return k8s_client
except Exception:
LOG.exception('Create k8s client - Got Exception')