How to use the kubernetes.config function in kubernetes

To help you get started, we’ve selected a few kubernetes examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github karmab / samplecontroller / ui / ui.py View on Github external
def run():
    if 'KUBERNETES_PORT' in os.environ:
        # os.environ['KUBERNETES_SERVICE_HOST'] = 'kubernetes'
        config.load_incluster_config()
    else:
        config.load_kube_config()
    app.run(host="0.0.0.0", port=9000)
    run()
github karmab / samplecontroller / initializer / initializer_dc.py View on Github external
oapi.replace_namespaced_deployment_config(name, namespace, obj)
            break


if __name__ == "__main__":
    global oapi
    inject = os.environ['INJECT_POD'] if 'INJECT_POD' in os.environ else 'karmab/kdummy'
    annotation = os.environ['ANNOTATION'] if 'ANNOTATION' in os.environ else None
    if annotation is not None:
        print "Injecting %s to new deployment configs with annotation %s set to true" % (inject, annotation)
    else:
        print "Injecting %s to all new deployment configs" % inject
    if 'KUBERNETES_PORT' in os.environ:
        config.load_incluster_config()
    else:
        config.load_kube_config()
    oapi = client.OapiApi()
    resource_version = ''
    while True:
        stream = watch.Watch().stream(oapi.list_deployment_config_for_all_namespaces, include_uninitialized=True, resource_version=resource_version)
        for event in stream:
                obj = event["object"]
                operation = event['type']
                spec = obj.spec
                if not spec:
                    continue
                metadata = obj.metadata
                resource_version = metadata._resource_version
                name = metadata.name
                print("Handling %s on %s" % (operation, name))
                process_deployment(obj)
github datawire / ambassador / python / kubewatch.py View on Github external
def kube_v1():
    # Assume we got nothin'.
    k8s_api = None

    # XXX: is there a better way to check if we are inside a cluster or not?
    if "KUBERNETES_SERVICE_HOST" in os.environ:
        # If this goes horribly wrong and raises an exception (it shouldn't),
        # we'll crash, and Kubernetes will kill the pod. That's probably not an
        # unreasonable response.
        config.load_incluster_config()
        if "AMBASSADOR_VERIFY_SSL_FALSE" in os.environ:
            configuration = client.Configuration()
            configuration.verify_ssl = False
            client.Configuration.set_default(configuration)
        k8s_api = client.CoreV1Api()
    else:
        # Here, we might be running in docker, in which case we'll likely not
        # have any Kube secrets, and that's OK.
        try:
            config.load_kube_config()
            k8s_api = client.CoreV1Api()
        except FileNotFoundError:
            # Meh, just ride through.
            logger.info("No K8s")
            pass
github hellofresh / eks-rolling-update / eksrollup / lib / k8s.py View on Github external
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)))
github FNNDSC / pman / openshift / pman-reaper / reaper.py View on Github external
def init_kube_client(self):
        """
        Method to get a kube client connected to remote or local kube api
        """
        kubecfg_path = os.environ.get('KUBECFG_PATH')
        if kubecfg_path is None:
            config.load_kube_config()
        else:
            config.load_kube_config(config_file='/tmp/.kube/config') 
        self.kube_client = k_client.CoreV1Api()
        self.kube_v1_batch_client = k_client.BatchV1Api()
        self.kube_v1_delete = k_client.V1DeleteOptions()
github IntelAI / nauta / applications / tfjob-multinode-sidecar / main.py View on Github external
def init_kubernetes_config():
    config.load_incluster_config()
github airshipit / promenade / promenade / kubeclient.py View on Github external
def __init__(self):
        """ Set Kubernetes APIs connection """
        try:
            LOG.info('Loading in-cluster Kubernetes configuration.')
            kubernetes.config.load_incluster_config()
        except kubernetes.config.config_exception.ConfigException:
            LOG.debug('Failed to load in-cluster configuration')
            try:
                LOG.info('Loading out-of-cluster Kubernetes configuration.')
                kubernetes.config.load_kube_config()
            except FileNotFoundError:
                LOG.exception(
                    'FileNotFoundError: Failed to load Kubernetes config file.'
                )
                raise KubernetesConfigException
        self.client = kubernetes.client.CoreV1Api()
github jupyter / enterprise_gateway / etc / kernelspecs / python_kubernetes / scripts / launch_k8s.py View on Github external
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(os.environ.get('EG_KUBERNETES_CONFIG'))

    kwds = dict()
    kwds['kernel_id'] = os.environ.get('KERNEL_ID')
    kwds['language'] = os.environ.get('KERNEL_LANGUAGE')
    kwds['namespace'] = os.environ.get('EG_KUBERNETES_NAMESPACE')
    kwds['response_address'] = response_addr
    kwds['docker_image'] = DOCKER_IMAGE
    kwds['comm_port'] = COMM_PORT
    kwds['stdin_port'] = STDIN_PORT
    kwds['control_port'] = CONTROL_PORT
    kwds['hb_port'] = HB_PORT
    kwds['shell_port'] = SHELL_PORT
    kwds['iopub_port'] = IOPUB_PORT

    with open(os.path.join(os.path.dirname(__file__), "kernel-service.yaml")) as f:
        yaml_template = f.read()
github kubeflow / kubeflow / components / jupyter-web-app / backend / kubeflow_jupyter / common / api.py View on Github external
import json
from kubernetes import client, config
from kubernetes.config import ConfigException
from kubernetes.client.rest import ApiException
from . import auth
from . import utils

logger = utils.create_logger(__name__)

try:
    # Load configuration inside the Pod
    config.load_incluster_config()
except ConfigException:
    # Load configuration for testing
    config.load_kube_config()

# Create the Apis
v1_core = client.CoreV1Api()
custom_api = client.CustomObjectsApi()
storage_api = client.StorageV1Api()


def parse_error(e):
    try:
        err = json.loads(e.body)["message"]
    except (json.JSONDecodeError, KeyError, AttributeError):
        err = str(e)

    return err
github intel / CPU-Manager-for-Kubernetes / intel / nodereport.py View on Github external
def nodereport(conf_dir, seconds, publish):
    if seconds is None:
        seconds = 0
    else:
        seconds = int(seconds)
    should_exit = (seconds <= 0)

    while True:
        report = generate_report(conf_dir)

        print(report.json())

        if publish and report is not None:
            logging.debug("Publishing node report to Kubernetes API server")
            k8sconfig.load_incluster_config()
            v1beta = k8sclient.ExtensionsV1beta1Api()

            version = util.parse_version(k8s.get_kube_version(None))

            if version >= util.parse_version("v1.7.0"):
                node_report_type = \
                    custom_resource.CustomResourceDefinitionType(
                        v1beta,
                        "intel.com",
                        "cmk-nodereport",
                        ["cmk-nr"]
                    )
                # custom_resource throws an exception if the environment
                # variable is not set.
                node_name = os.getenv("NODE_NAME")
                node_report = node_report_type.create(node_name)