How to use the kubernetes.client.Configuration 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 PaddlePaddle / cloud / python / paddlecloud / notebook / utils.py View on Github external
def get_user_api_client(username):
    """
        Update kubernetes client to use current logined user's crednetials
    """

    conf_obj = kubernetes.client.Configuration()
    conf_obj.host = settings.K8S_HOST
    conf_obj.ssl_ca_cert = os.path.join(settings.CA_PATH)
    conf_obj.cert_file = os.path.join(settings.USER_CERTS_PATH, username, "%s.pem"%username)
    conf_obj.key_file = os.path.join(settings.USER_CERTS_PATH, username, "%s-key.pem"%username)
    api_client = kubernetes.client.ApiClient(config=conf_obj)
    return api_client
github openstack / rally / rally / plugins / openstack / scenarios / magnum / utils.py View on Github external
key_file = None
        cert_file = None
        ca_certs = None
        if not cluster_template.tls_disabled:
            dir = self.context["ca_certs_directory"]
            key_file = cluster_uuid + ".key"
            key_file = os.path.join(dir, key_file)
            cert_file = cluster_uuid + ".crt"
            cert_file = os.path.join(dir, cert_file)
            ca_certs = cluster_uuid + "_ca.crt"
            ca_certs = os.path.join(dir, ca_certs)
        if hasattr(k8s_config, "ConfigurationObject"):
            # k8sclient < 4.0.0
            config = k8s_config.ConfigurationObject()
        else:
            config = k8s_config.Configuration()
        config.host = cluster.api_address
        config.ssl_ca_cert = ca_certs
        config.cert_file = cert_file
        config.key_file = key_file
        client = api_client.ApiClient(config=config)
        return core_v1_api.CoreV1Api(client)
github redhat-cop / anarchy / build / anarchy.py View on Github external
def init_kube_api():
    """Set kube_api global to communicate with the local kubernetes cluster."""
    global kube_api, kube_custom_objects, anarchy_crd_domain
    kube_config = kubernetes.client.Configuration()
    kube_config.api_key['authorization'] = service_account_token
    kube_config.api_key_prefix['authorization'] = 'Bearer'
    kube_config.host = os.environ['KUBERNETES_PORT'].replace('tcp://', 'https://', 1)
    kube_config.ssl_ca_cert = '/run/secrets/kubernetes.io/serviceaccount/ca.crt'
    kube_api = kubernetes.client.CoreV1Api(
        kubernetes.client.ApiClient(kube_config)
    )
    kube_custom_objects = kubernetes.client.CustomObjectsApi(
        kubernetes.client.ApiClient(kube_config)
    )
    anarchy_crd_domain = os.environ.get('ANARCHY_CRD_DOMAIN','gpte.redhat.com')
github PrefectHQ / prefect / src / prefect / tasks / kubernetes / service.py View on Github external
Raises:
            - ValueError: if `body` is `None`
            - ValueError: if `service_name` is `None`
        """
        if not body:
            raise ValueError(
                "A dictionary representing a V1Service patch must be provided."
            )

        if not service_name:
            raise ValueError("The name of a Kubernetes service must be provided.")

        kubernetes_api_key = Secret(kubernetes_api_key_secret).get()

        if kubernetes_api_key:
            configuration = client.Configuration()
            configuration.api_key["authorization"] = kubernetes_api_key
            api_client = client.CoreV1Api(client.ApiClient(configuration))
        else:
            try:
                config.load_incluster_config()
            except config.config_exception.ConfigException:
                config.load_kube_config()

            api_client = client.CoreV1Api()

        body = {**self.body, **(body or {})}
        kube_kwargs = {**self.kube_kwargs, **(kube_kwargs or {})}

        api_client.patch_namespaced_service(
            name=service_name, namespace=namespace, body=body, **kube_kwargs
        )
github redhat-cop / anarchy / operator / anarchyruntime.py View on Github external
def __init_kube_apis(self):
        if os.path.exists('/run/secrets/kubernetes.io/serviceaccount/token'):
            f = open('/run/secrets/kubernetes.io/serviceaccount/token')
            kube_auth_token = f.read()
            kube_config = kubernetes.client.Configuration()
            kube_config.api_key['authorization'] = 'Bearer ' + kube_auth_token
            kube_config.host = os.environ['KUBERNETES_PORT'].replace('tcp://', 'https://', 1)
            kube_config.ssl_ca_cert = '/run/secrets/kubernetes.io/serviceaccount/ca.crt'
        else:
            kubernetes.config.load_kube_config()
            kube_config = None

        self.api_client = kubernetes.client.ApiClient(kube_config)
        self.core_v1_api = kubernetes.client.CoreV1Api(self.api_client)
        self.custom_objects_api = kubernetes.client.CustomObjectsApi(self.api_client)
github mlbench / mlbench-core / mlbench_core / api.py View on Github external
def __get_in_cluster_url(self, label_selector, k8s_namespace, load_config):
        """Get the API url for the dashboard when running in a cluster """
        if load_config:
            config.load_incluster_config()

        configuration = client.Configuration()
        k8s_client = client.CoreV1Api(_CustomApiClient(configuration))
        namespaced_pods = k8s_client.list_namespaced_pod(
            k8s_namespace, label_selector=label_selector
        )

        assert len(namespaced_pods.items) == 1

        master_pod = namespaced_pods.items[0]

        return master_pod.status.pod_ip + ":80"
github IBM / multicloud-incident-response-navigator / backend / metrics.py View on Github external
def get_pod_container_usage(cluster_name, namespace, pod_name):
        """
        Helper method for getting current usage for containers in a pod
        :return: Dict(container_name : (cpu, mem)), or None if http request failed
        """
        # load configuration for the desired context to get host and api key
        myconfig = client.Configuration()
        desired_context = k8s_config.context_for_cluster(cluster_name)
        config.load_kube_config(context=desired_context, client_configuration=myconfig)

        # request to get pod
        server = myconfig.host
        headers = myconfig.api_key
        url = server + "/apis/metrics.k8s.io/v1beta1/namespaces/{}/pods/{}".format(namespace, pod_name)
        response = requests.get(url, headers=headers, verify=False)

        if response.status_code == 200:
            pod_metrics = response.json()
            usage_by_container = {}
            if pod_metrics.get('containers'):
                for ct in pod_metrics['containers']:
                    usage_by_container[ct['name']] = (ct['usage']['cpu'], ct['usage']['memory'])
            return usage_by_container
github karmab / samplecontroller / kopf / handlers.py View on Github external
def review_guitar(name, namespace):
    configuration = client.Configuration()
    configuration.assert_hostname = False
    api_client = client.api_client.ApiClient(configuration=configuration)
    crds = client.CustomObjectsApi(api_client)
    guitar = crds.get_namespaced_custom_object(DOMAIN, 'v1', namespace, 'guitars', name)
    metadata = guitar.get("metadata")
    if not metadata:
        print("No metadata in object, skipping: %s" % json.dumps(guitar, indent=1))
        return
    name = metadata.get("name")
    namespace = metadata.get("namespace")
    guitar["spec"]["review"] = True
    brand = guitar["spec"]["brand"]
    if brand in goodbrands:
        guitar["spec"]["comment"] = "this is a great instrument"
    elif brand in badbrands:
        guitar["spec"]["comment"] = "this is shit"
github labdave / CloudConductor / System / Platform / Kubernetes / KubernetesCluster.py View on Github external
def authenticate_platform(self):
        cert_path, host, api_token, api_prefix = self.__parse_identity_json(self.identity)
        self.configuration = client.Configuration()
        self.configuration.api_key["authorization"] = api_token
        self.configuration.api_key_prefix['authorization'] = api_prefix
        self.configuration.host = host
        self.configuration.ssl_ca_cert = cert_path
        self.batch_api = client.BatchV1Api(client.ApiClient(self.configuration))
        self.core_api = client.CoreV1Api(client.ApiClient(self.configuration))