Ejemplo n.º 1
0
    def run(
        self,
        deployment_name: str = None,
        namespace: str = "default",
        kube_kwargs: dict = None,
        kubernetes_api_key_secret: str = "KUBERNETES_API_KEY",
    ) -> None:
        """
        Task run method.

        Args:
            - deployment_name (str, optional): The name of a deployment to read
            - namespace (str, optional): The Kubernetes namespace to read this deployment in,
                defaults to the `default` namespace
            - kube_kwargs (dict, optional): Optional extra keyword arguments to pass to the
                Kubernetes API (e.g. `{"pretty": "...", "exact": "..."}`)
            - kubernetes_api_key_secret (str, optional): the name of the Prefect Secret
                which stored your Kubernetes API Key; this Secret must be a string and in
                BearerToken format

        Returns:
            - ExtensionsV1beta1Deployment: a Kubernetes ExtensionsV1beta1Deployment
                matching the deployment that was found

        Raises:
            - ValueError: if `deployment_name` is `None`
        """
        if not deployment_name:
            raise ValueError(
                "The name of a Kubernetes deployment must be provided.")

        kubernetes_api_key = None
        if kubernetes_api_key_secret:
            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.ExtensionsV1beta1Api(
                client.ApiClient(configuration))
        else:
            try:
                config.load_incluster_config()
            except ConfigException:
                config.load_kube_config()

            api_client = client.ExtensionsV1beta1Api()

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

        return api_client.read_namespaced_deployment(name=deployment_name,
                                                     namespace=namespace,
                                                     **kube_kwargs)
Ejemplo n.º 2
0
def get_api_client(cluster_name, cluster_endpoint, challenge, evalai):
    # TODO: Add SSL verification
    configuration = client.Configuration()
    aws_eks_api = evalai.get_aws_eks_bearer_token(challenge.get("id"))
    configuration.host = cluster_endpoint
    configuration.verify_ssl = True
    configuration.ssl_ca_cert = '.certificate.txt'
    configuration.api_key["authorization"] = aws_eks_api[
        "aws_eks_bearer_token"]
    configuration.api_key_prefix["authorization"] = "Bearer"
    api_instance = client.ApiClient(configuration)
    return api_instance
Ejemplo n.º 3
0
 def Read_Custom_Resource_Definition_Status(self, name):
     configuration = client.Configuration()
     api_instance = client.ApiextensionsV1beta1Api(
         client.ApiClient(configuration))
     try:
         api_response = api_instance.read_custom_resource_definition_status(
             name, pretty='true')
         pprint(api_response)
     except ApiException as e:
         print(
             "Exception when calling ApiextensionsV1beta1Api->read_custom_resource_definition_status: %s\n"
             % e)
Ejemplo n.º 4
0
    def setup_clients(cls):
        super(BaseQinlingTest, cls).setup_clients()

        cls.client = cls.os_primary.qinling.QinlingClient()
        cls.alt_client = cls.os_alt.qinling.QinlingClient()
        cls.admin_client = cls.os_admin.qinling.QinlingClient()

        # Initilize k8s client
        k8s_client.Configuration().host = CONF.qinling.kube_host
        cls.k8s_v1 = k8s_client.CoreV1Api()
        cls.k8s_v1extention = k8s_client.ExtensionsV1beta1Api()
        cls.namespace = 'qinling'
Ejemplo n.º 5
0
def delete_connectedk8s(cmd, client, resource_group_name, cluster_name,
                        kube_config=None, kube_context=None, no_wait=False):
    logger.warning("Ensure that you have the latest helm version installed before proceeding to avoid unexpected errors.")
    logger.warning("This operation might take a while ...\n")

    # Setting kubeconfig
    kube_config = set_kube_config(kube_config)

    # Removing quotes from kubeconfig path. This is necessary for windows OS.
    trim_kube_config(kube_config)

    # Loading the kubeconfig file in kubernetes client configuration
    try:
        config.load_kube_config(config_file=kube_config, context=kube_context)
    except Exception as e:
        raise CLIError("Problem loading the kubeconfig file." + str(e))
    configuration = kube_client.Configuration()

    # Checking the connection to kubernetes cluster.
    # This check was added to avoid large timeouts when connecting to AAD Enabled
    # AKS clusters if the user had not logged in.
    check_kube_connection(configuration)

    # Checking helm installation
    check_helm_install(kube_config, kube_context)

    # Check helm version
    check_helm_version(kube_config, kube_context)

    # Check Release Existance
    release_namespace = get_release_namespace(kube_config, kube_context)
    if release_namespace is None:
        delete_cc_resource(client, resource_group_name, cluster_name, no_wait)
        return

    # Loading config map
    api_instance = kube_client.CoreV1Api(kube_client.ApiClient(configuration))
    try:
        configmap = api_instance.read_namespaced_config_map('azure-clusterconfig', 'azure-arc')
    except Exception as e:  # pylint: disable=broad-except
        logger.warning("Unable to read ConfigMap 'azure-clusterconfig' in 'azure-arc' namespace: %s\n", e)

    if (configmap.data["AZURE_RESOURCE_GROUP"].lower() == resource_group_name.lower() and
            configmap.data["AZURE_RESOURCE_NAME"].lower() == cluster_name.lower()):
        delete_cc_resource(client, resource_group_name, cluster_name, no_wait)
    else:
        raise CLIError("The current context in the kubeconfig file does not correspond " +
                       "to the connected cluster resource specified. Agents installed on this cluster correspond " +
                       "to the resource group name '{}' ".format(configmap.data["AZURE_RESOURCE_GROUP"]) +
                       "and resource name '{}'.".format(configmap.data["AZURE_RESOURCE_NAME"]))

    # Deleting the azure-arc agents
    delete_arc_agents(release_namespace, kube_config, kube_context, configuration)
Ejemplo n.º 6
0
 def setUp(self):
     super(BaseK8sTest, self).setUp()
     self.kube_api_url = self.cs.clusters.get(self.cluster.uuid).api_address
     config = k8s_config.Configuration()
     config.host = self.kube_api_url
     config.ssl_ca_cert = self.ca_file
     config.cert_file = self.cert_file
     config.key_file = self.key_file
     k8s_client = api_client.ApiClient(configuration=config)
     self.k8s_api = core_v1_api.CoreV1Api(k8s_client)
     # TODO(coreypobrien) https://bugs.launchpad.net/magnum/+bug/1551824
     utils.wait_for_condition(self._is_api_ready, 5, 600)
Ejemplo n.º 7
0
def refresh_instance():
    """Refresh Kubernetes API instance."""
    global _instance
    with open(_authorization_file, 'r') as f:
        authorization = f.read().strip()
    configuration = client.Configuration()
    configuration.api_key['authorization'] = authorization
    configuration.api_key_prefix['authorization'] = 'Bearer'
    configuration.ssl_ca_cert = _ssl_ca_cert_file
    configuration.host = _host
    with client.ApiClient(configuration) as api_client:
        _instance = client.CoreV1Api(api_client)
Ejemplo n.º 8
0
 def __init__(self):
     if not os.path.isfile(KUBE_TOKEN_FILE):
         # Not enable RBAC
         if not KUBE_APISERVER_ADDRESS:
             LOGGER.error("could not get kubernetes api server address")
             raise ValueError("KUBE_APISERVER_ADDRESS is none")
         config = kube_client.Configuration()
         config.host = os.environ.get("KUBE_APISERVER_ADDRESS")
         self._api_client = kube_client.ApiClient(config)
     else:
         kube_config.load_incluster_config()
         self._api_client = None
Ejemplo n.º 9
0
def list_finished_jobs():
    client.Configuration().host="http://localhost:8001"
    v1.client.CoreV1Api()
    job_list = v1.list_namespaced_pod("default")

    finishedJobs = 0

    for job in job_list.items:
        if job.status.phase == "Succeeded":
            finishedJobs += 1

    return finishedJobs
Ejemplo n.º 10
0
    def run(
        self,
        job_name: str = None,
        body: dict = None,
        namespace: str = "default",
        kube_kwargs: dict = None,
        kubernetes_api_key_secret: str = "KUBERNETES_API_KEY",
    ):
        """
        Task run method.

        Args:
            - job_name (str, optional): The name of a job to replace
            - body (dict, optional): A dictionary representation of a Kubernetes V1Job
                specification
            - namespace (str, optional): The Kubernetes namespace to patch this job in,
                defaults to the `default` namespace
            - kube_kwargs (dict, optional): Optional extra keyword arguments to pass to the
                Kubernetes API (e.g. `{"pretty": "...", "dry_run": "..."}`)
            - kubernetes_api_key_secret (str, optional): the name of the Prefect Secret
                which stored your Kubernetes API Key; this Secret must be a string and in
                BearerToken format

        Raises:
            - ValueError: if `body` is `None`
            - ValueError: if `job_name` is `None`
        """
        if not body:
            raise ValueError("A dictionary representing a V1Job must be provided.")

        if not job_name:
            raise ValueError("The name of a Kubernetes job 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.BatchV1Api(client.ApiClient(configuration))
        else:
            try:
                config.load_incluster_config()
            except config.config_exception.ConfigException:
                config.load_kube_config()

            api_client = client.BatchV1Api()

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

        api_client.replace_namespaced_job(
            name=job_name, namespace=namespace, body=body, **kube_kwargs
        )
Ejemplo n.º 11
0
def get_core_v1_api_object(cluster_name, cluster_endpoint, challenge, evalai):
    configuration = client.Configuration()
    aws_eks_api = evalai.get_aws_eks_bearer_token(challenge.get("id"))
    configuration.host = cluster_endpoint
    configuration.verify_ssl = True
    configuration.ssl_ca_cert = "/code/scripts/workers/certificate.crt"
    configuration.api_key["authorization"] = aws_eks_api[
        "aws_eks_bearer_token"
    ]
    configuration.api_key_prefix["authorization"] = "Bearer"
    api_instance = client.CoreV1Api(client.ApiClient(configuration))
    return api_instance
Ejemplo n.º 12
0
    def _get_config_from_params(self, k8s_params):
        """ get the configuration from params
        :params: k8s_params to connect to Kubernetes Master node
        :return: python kubernetes config
        """
        k8s_config = client.Configuration()
        k8s_config.host = k8s_params.get('address')
        if not k8s_config.host.startswith("https://"):
            k8s_config.host = "https://" + k8s_config.host

        k8s_config.username = k8s_params.get('username')
        k8s_config.password = k8s_params.get('password')

        cert_content = base64.decodestring(str.encode(k8s_params.get('cert')))
        key_content = base64.decodestring(str.encode(k8s_params.get('key')))

        k8s_config.cert_file = \
            config.kube_config._create_temp_file_with_content(cert_content)

        k8s_config.key_file = \
            config.kube_config._create_temp_file_with_content(key_content)

        config_content = k8s_params.get('config')
        # Use config file content to set k8s_config if it exist.
        if config_content.strip():
            config_file = \
                config.kube_config. \
                _create_temp_file_with_content(config_content)

            loader = \
                config.kube_config. \
                _get_kube_config_loader_for_yaml_file(config_file)

            loader.load_and_set(k8s_config)

        if k8s_params.get('use_ssl') == "false":
            k8s_config.verify_ssl = False
        else:
            k8s_config.verify_ssl = True

        client.Configuration.set_default(k8s_config)

        v1 = client.CoreV1Api()
        try:
            v1.list_pod_for_all_namespaces(watch=False)
        except Exception as e:
            error_msg = ("Cannot create kubernetes host due "
                         "to an incorrect parameters.")
            logger.error("Kubernetes host error msg: {}".format(e))
            raise Exception(error_msg)

        return k8s_config
Ejemplo n.º 13
0
def main():
    print("Starting collector")

    folderAnnotation = os.getenv('FOLDER_ANNOTATION')
    if folderAnnotation is None:
        print(
            "No folder annotation was provided, defaulting to k8s-sidecar-target-directory"
        )
        folderAnnotation = "k8s-sidecar-target-directory"

    label = os.getenv('LABEL')
    if label is None:
        print("Should have added LABEL as environment variable! Exit")
        return -1

    labelValue = os.getenv('LABEL_VALUE')
    if labelValue:
        print(f"Filter labels with value: {labelValue}")

    targetFolder = os.getenv('FOLDER')
    if targetFolder is None:
        print("Should have added FOLDER as environment variable! Exit")
        return -1

    resources = os.getenv('RESOURCE', 'configmap')
    resources = ("secret",
                 "configmap") if resources == "both" else (resources, )
    print(f"Selected resource type: {resources}")

    method = os.getenv('REQ_METHOD')
    url = os.getenv('REQ_URL')
    payload = os.getenv('REQ_PAYLOAD')

    config.load_incluster_config()
    print("Config for cluster api loaded...")
    currentNamespace = open(
        "/var/run/secrets/kubernetes.io/serviceaccount/namespace").read()

    if os.getenv('SKIP_TLS_VERIFY') == 'true':
        configuration = client.Configuration()
        configuration.verify_ssl = False
        configuration.debug = False
        client.Configuration.set_default(configuration)

    if os.getenv("METHOD") == "LIST":
        for res in resources:
            listResources(label, labelValue, targetFolder, url, method,
                          payload, currentNamespace, folderAnnotation, res)
    else:
        watchForChanges(os.getenv("METHOD"), label, labelValue, targetFolder,
                        url, method, payload, currentNamespace,
                        folderAnnotation, resources)
Ejemplo n.º 14
0
def get_client_base():
    if os.path.exists(os.environ.get("HOME") + "/.kube/config"):
        config.load_kube_config()
        return client.CoreV1Api()

    configuration = client.Configuration()
    configuration.verify_ssl = True
    configuration.host = "https://" + \
        os.environ.get("KUBERNETES_SERVICE_HOST")
    configuration.api_key["authorization"] = _get_token()
    configuration.api_key_prefix["authorization"] = "Bearer"
    configuration.ssl_ca_cert = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"
    return client.ApiClient(configuration)
Ejemplo n.º 15
0
Archivo: tests.py Proyecto: zwunix/seal
def main():
    Token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkYXNoYm9hcmQtYWRtaW4tdG9rZW4tZGhobWMiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGFzaGJvYXJkLWFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiOThkMDcwZWItODc1Yy0xMWU5LWE1MzgtMDAwYzI5N2I0ZmU3Iiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmRhc2hib2FyZC1hZG1pbiJ9.XDFpez2E84R_zlopt_uEHPvVGUtSavypyix6UcYJO3J4imHdJy7MEkfV-wltBA1H8x0TT2AW64rLlXaRJ8OkFWJ0myedfKdjnf7i0oLQ8j-7lw6rT3A0e2pKmpnOaBQfgzRm83-t2I5MMp3Iu9VNUiAbqQpjql4AKwRuJEEGCs99tKStUxzIsJKusmUHh9KAK4BAxySn9h16T2URZ7czLP4mty2crYWNV4KwSwFPthGhFPsl8mnet_hiV5k4me5a8frmXytOy64MmGW8w3TBgiM-7hBYSxt84QGGnyi84LU0EFgtLwBWEOTZeUKKQ6IkoAprMmNcSxX8WUJFlx_uJg"
    APISERVER = 'https://192.168.100.111:6443'
    configuration = client.Configuration()
    configuration.host = APISERVER
    configuration.verify_ssl = False
    configuration.api_key = {"authorization": "Bearer " + Token}
    client.Configuration.set_default(configuration)
    v1 = client.CoreV1Api()
    ret = v1.list_pod_for_all_namespaces(watch=False)

    ret1 = v1.read_namespaced_pod("nginx-58bdcbcd-z8v2s", "default")
    print(ret1)
Ejemplo n.º 16
0
    def __init__(self):
        service_account_path = '/var/run/secrets/kubernetes.io/serviceaccount'

        with open(os.path.join(service_account_path, 'namespace')) as fp:
            self.namespace = fp.read().strip()
        config.load_incluster_config()

        configuration = client.Configuration()
        configuration.verify_ssl = False

        self.oapi_client = DynamicClient(
            client.ApiClient(configuration=configuration)
        )
Ejemplo n.º 17
0
def setup_kubernetes(kubeconfig_path):
    if kubeconfig_path is None:
        kubeconfig_path = config.KUBE_CONFIG_DEFAULT_LOCATION
    kubeconfig = config.kube_config.KubeConfigMerger(kubeconfig_path)

    if kubeconfig.config is None:
        raise Exception('Invalid kube-config file: %s. '
                        'No configuration found.' % kubeconfig_path)
    loader = config.kube_config.KubeConfigLoader(
        config_dict=kubeconfig.config, )
    client_config = client.Configuration()
    loader.load_and_set(client_config)
    return client.ApiClient(configuration=client_config)
Ejemplo n.º 18
0
 def __init__(self, k8host, namespace):
     self.k8host = k8host
     self.namespace = namespace
     #kubernetes.config.load_kube_config(config_file='/opt/monitor/config')
     configuration = client.Configuration()
     configuration.api_key["authorization"] = "token-goes-here"
     configuration.api_key_prefix['authorization'] = 'Bearer'
     configuration.ssl_ca_cert = 'path-to-certificate'
     configuration.host = self.k8host
     configuration.watch = True
     configuration.debug = True
     self.api_instance = client.CoreV1Api(client.ApiClient(configuration))
     self.watch = None
Ejemplo n.º 19
0
def fake_k8s_api_server(print_logs=False):
    with run_service(
        "fakek8s", print_logs=print_logs, path=REPO_ROOT_DIR, dockerfile="./test-services/fakek8s/Dockerfile"
    ) as fakek8s_cont:
        ipaddr = container_ip(fakek8s_cont)
        conf = client.Configuration()
        conf.host = f"https://{ipaddr}:8443"
        conf.verify_ssl = False

        assert wait_for(lambda: tcp_socket_open(ipaddr, 8443)), "fake k8s never opened port"
        warnings.filterwarnings("ignore", category=urllib3.exceptions.InsecureRequestWarning)

        yield [client.ApiClient(conf), {"KUBERNETES_SERVICE_HOST": ipaddr, "KUBERNETES_SERVICE_PORT": "8443"}]
 def connect(self):
     with open('./token.txt', 'r') as file:
         Token = file.read().strip('\n')
     configuration = client.Configuration()
     configuration.host = self.k8s_url
     configuration.verify_ssl = True
     with open('./ca.cert', 'r') as file:
         cacert = file.read().strip('\n')
     configuration.ssl_ca_cert = config.kube_config._create_temp_file_with_content(
         cacert)
     configuration.api_key = {"authorization": "Bearer " + Token}
     client.Configuration.set_default(configuration)
     self.v1 = client.CoreV1Api()
Ejemplo n.º 21
0
def list_pod():
    token = "eyJhbGciOiJSUzI1NiIsImtpZCI6InVjeWJsSDBPRTFpMUM1V2sta1YzOE5xc1M4cHJmVzByblRjMkQ3ck1sa1UifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlcm5ldGVzLWRhc2hib2FyZCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkYXNoYm9hcmQtYWRtaW4tdG9rZW4tODZuOG4iLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGFzaGJvYXJkLWFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiN2E5NjYwMjktOGFiZC00YjFkLTkwNTItMmQyYmU3YWY5N2Y0Iiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmVybmV0ZXMtZGFzaGJvYXJkOmRhc2hib2FyZC1hZG1pbiJ9.bnjv5h86T6-GhiFP4tHZB4JCvfMU6uQIUnBJ5uNiPk5ZY0m7eWq7wHcvG7qJBcQVGg8y1I7WceKxU3XyliOb80BcLEWC_RAgfabZ-JcR3j16vvhyO0ju45Amg2AV2zqD75o8q8B4oVull6CjhajAFL7eV8BPmcw-dqPPW6NiiMjtt2UhoOs8ZIyBA9-e_d4eSurdK_qQ0vEnebr6AUv5SB0GJordkuFrqC_bdLCgSfgrYPK6VxwEy3adlK7OQ_Ke2tNxfgHW9MJFFYKy6CBu3k_hLtsghellu211nLV3uaaFuYjAv-gIsNbXIWy8vRy3rYsZWrFRn088C0bZli5yzg"
    conf = client.Configuration()
    conf.host = "https://192.168.1.135:6443"
    conf.verify_ssl = False
    conf.api_key = {'authorization': 'Bearer ' + token}
    client.Configuration.set_default(conf)
    v1 = client.CoreV1Api()
    print("Listing pods with their IPs:")
    ret = v1.list_pod_for_all_namespaces(watch=False)
    for i in ret.items:
        print("%s\t%s\t%s" %
              (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
Ejemplo n.º 22
0
 def get_client(self):
     baseurl = K8sHost.objects.values('k8s_api').get(
         id=self.confid)['k8s_api']
     token = str(
         K8sHost.objects.values('k8s_api_token').get(
             id=self.confid)['k8s_api_token']).strip()
     aConfiguration = client.Configuration()
     aConfiguration.host = baseurl
     aConfiguration.verify_ssl = False
     aConfiguration.api_key = {"authorization": "Bearer " + token}
     aApiClient = client.ApiClient(aConfiguration)
     v1 = client.CoreV1Api(aApiClient)
     return v1
def kubernetes_api_instance():
    """Return Kubernetes API Instance."""

    configuration = kc.Configuration()

    configuration.api_key['authorization'] = file_contents(
        os.environ.get('API_KEY'))
    configuration.api_key_prefix['authorization'] = 'Bearer'
    configuration.host = os.environ.get('K8S_HOST', '')
    configuration.ssl_ca_cert = os.environ.get('CA_CERT', '')

    api_instance = kc.CustomObjectsApi(kc.ApiClient(configuration))
    return api_instance
 def k8s_conn(self):
     # self.config_path = config.kube_config.load_kube_config(config_file=config_path)
     #获取API的CoreV1Api版本对象
     # self.v1 = client.CoreV1Api()
     Token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IlRDM2hwNlM1ak1vUDZ2NjFtNDB4cEIzT0NlRDZzVmxPSFZiYzlqOEdXQzAifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJhZG1pbi11c2VyLXRva2VuLTV4bGtiIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6ImFkbWluLXVzZXIiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC51aWQiOiI4NWZiMDMyZC05ZTI2LTRjMDgtOGY2Yi0yNDIwZGMxMTA5NDkiLCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6a3ViZS1zeXN0ZW06YWRtaW4tdXNlciJ9.JqaGNnGflGQE7ENiXL9JFtwcBcS1PS3-JGmJX7bdStLm6fNENmtKXIa2L5RM8hzX3zwGZEkw3jKX1Ult6ug7e_EU5yXsP0BZ6lNhowfu6C0vYbEX4o-lJV2sX7DHFp9_-urmtjBeXHaf88J3vJ_Fbg8Yv_5Mfk3cCC0yiRZ7EAAUp7d8H2bjVPIvtGSkxFK4WrL0cj0lsrQZg7vgxDbclJJVCpWDDz8NLINjqURpqpfWGo0ABTwYQ_bV8tdXt9hTPAfVDXNTJYm4cHhP-fDQKjkUH-PGzmo56_e-aT24faIOQQEEefgQPw88ScUGY8UgXdfMXTv_tPJj-A588VSmMg"
     APISERVER = 'https://127.0.0.1:6443'
     configuration = client.Configuration()
     configuration.host = APISERVER
     configuration.verify_ssl = False
     configuration.api_key = {"authorization": "Bearer " + Token}
     client.Configuration.set_default(configuration)
     conn = client.CoreV1Api()
     return conn
Ejemplo n.º 25
0
def test_service_apis():
    from kubernetes import client
    k8s_url = 'https://127.0.0.1:6443'
    with open('token.txt', 'r') as file:
        token = file.read().strip('\n')
    configuration = client.Configuration()
    configuration.host = k8s_url
    configuration.verify_ssl = False
    configuration.api_key = {"authorization": "Bearer " + token}
    client1 = api_client.ApiClient(configuration=configuration)
    api = core_v1_api.CoreV1Api(client1)
    ret = api.list_pod_for_all_namespaces(watch=False)
    print(ret)
Ejemplo n.º 26
0
def quayToken():
    config.load_kube_config('kube')
    configuration = client.Configuration()
    configuration.verify_ssl = False
    client.Configuration.set_default(configuration)
    v1 = client.CoreV1Api()
    base64_data_json = v1.read_namespaced_secret('quay-token-secret',
                                                 'quay-enterprise')
    base64_data = base64_data_json.data['token']
    base64_bytes = base64_data.encode('ascii')
    message_bytes = base64.b64decode(base64_bytes)
    data_decode = message_bytes.decode('ascii')
    return (data_decode)
Ejemplo n.º 27
0
    def __init__(self, squirrel):
        self.squirrel = squirrel
        self.squirrel_length_random = 26
        if path.exists('/.dockerenv'):
            config.load_incluster_config()
            self.configuration = client.Configuration()
            self.configuration.assert_hostname = False
            self.api_instance = client.ApiextensionsApi(
                client.ApiClient(self.configuration))
            self.api_client = client.api_client.ApiClient(
                configuration=self.configuration)

            self.crds = client.CustomObjectsApi(self.api_client)
Ejemplo n.º 28
0
    def make_configuration(self) -> Configuration:
        """生成 Kubernetes SDK 所需的 Configuration 对象"""
        env_name = self.env_querier.do()

        config = client.Configuration()
        config.verify_ssl = False
        # Get credentials
        credentials = self.get_client_credentials(env_name)
        config.host = credentials['host']
        config.api_key = {
            "authorization": f"Bearer {credentials['user_token']}"
        }
        return config
 def get_pod_state(self, pod_name, namespace_id):
     config.load_incluster_config()
     logging.info('Inside pod state before try *******' + pod_name)
     try:
         configuration = client.Configuration()
         api_client = client.ApiClient(configuration)
         api_instance = client.CoreV1Api(api_client)
         api_response_state = api_instance.read_namespaced_pod_status(
             name=str(pod_name) + "-driver", namespace=namespace_id)
         logging.info('Inside pod state *******' + pod_name)
         return api_response_state.status.phase
     except ApiException as e:
         print('Exception in getting status')
Ejemplo n.º 30
0
def sa_usage():
    with open('token.txt', 'r') as fd:
        info = json.loads(fd.read())
    api_server = info['api_server']
    sa_token = info['token']
    configuration = client.Configuration()
    configuration.host = api_server
    configuration.verify_ssl = False
    configuration.api_key = {"authorization": "Bearer " + sa_token}
    client1 = client.api_client.ApiClient(configuration=configuration)
    api_core = client.CoreV1Api(client1)
    ret = api_core.list_namespace()
    print(ret)