Esempio n. 1
0
def kubernetes_api_client(rancher_client, cluster_name):
    c = rancher_client.by_id_cluster(cluster_name)
    kc = c.generateKubeconfig()
    loader = KubeConfigLoader(config_dict=yaml.load(kc.config))
    client_configuration = type.__call__(Configuration)
    loader.load_and_set(client_configuration)
    k8s_client = ApiClient(configuration=client_configuration)
    return k8s_client
Esempio n. 2
0
def kubernetes_api_client(rancher_client, cluster_name):
    c = rancher_client.by_id_cluster(cluster_name)
    kc = c.generateKubeconfig()
    loader = KubeConfigLoader(config_dict=yaml.full_load(kc.config))
    client_configuration = type.__call__(Configuration)
    loader.load_and_set(client_configuration)
    k8s_client = ApiClient(configuration=client_configuration)
    return k8s_client
Esempio n. 3
0
    def set_kubecfg(self, kubeconfig_dict: dict):
        not_none(kubeconfig_dict)

        configuration = kubernetes.client.Configuration()
        cfg_loader = KubeConfigLoader(dict(kubeconfig_dict))
        cfg_loader.load_and_set(configuration)
        # pylint: disable=no-member
        kubernetes.client.Configuration.set_default(configuration)
        # pylint: enable=no-member
        self.kubeconfig = configuration
Esempio n. 4
0
    def set_kubecfg(self, kubeconfig_dict: typing.Union[dict, model.kubernetes.KubernetesConfig]):
        not_none(kubeconfig_dict)
        if isinstance(kubeconfig_dict, model.kubernetes.KubernetesConfig):
            kubeconfig_dict = kubeconfig_dict.kubeconfig()

        configuration = kubernetes.client.Configuration()
        cfg_loader = KubeConfigLoader(dict(kubeconfig_dict))
        cfg_loader.load_and_set(configuration)
        # pylint: disable=no-member
        kubernetes.client.Configuration.set_default(configuration)
        # pylint: enable=no-member
        self.kubeconfig = configuration
def load_kube_config_from_dict(config_dict):
    """
    Loads authentication and cluster information from dict.
    """

    config_loader = KubeConfigLoader(config_dict=config_dict)

    client_configuration = Configuration()
    config_loader.load_and_set(client_configuration=client_configuration)
    Configuration.set_default(client_configuration)

    return config_loader
Esempio n. 6
0
    def _load_kubeconfig(self, path_to_kubeconfig: str):
        if not os.path.isfile(path_to_kubeconfig):
            print(f"No file found at '{path_to_kubeconfig}'")
            exit(1)

        with open(path_to_kubeconfig, 'r') as kubeconfig_file:
            kubeconfig = yaml.safe_load(kubeconfig_file.read())

        k8s_config = kubernetes.client.Configuration()
        cfg_loader = KubeConfigLoader(kubeconfig)
        cfg_loader.load_and_set(k8s_config)
        return k8s_config
Esempio n. 7
0
File: utils.py Progetto: jpza/ekscli
def load_kubeconf(config_file):
    with open(config_file, 'r') as f:
        config = yaml.load(f)
        user = [user for user in config['users']
                if user['name'] == 'aws'][0]['user']
        command = [user['exec']['command']]
        command.extend(user['exec']['args'])
        output = subprocess.check_output(command)
        c = json.loads(output.decode('utf-8'))
        user['token'] = c['status']['token']
        del user['exec']

        loader = KubeConfigLoader(config)
        config = type.__call__(Configuration)
        loader.load_and_set(config)
        Configuration.set_default(config)
Esempio n. 8
0
    def get_api_client(self):
        """
        Create Kubernetes API client with configuration from string.

        Returns:
            str: Kubeconfig file path

        """

        # This super-ugly code configuration is causes by wrong design of config-loading
        # functions in https://github.com/kubernetes-client/python
        client_config = type.__call__(client.Configuration)
        kubeconfig = self.cluster.get_kubeconfig()
        kcl = KubeConfigLoader(config_dict=kubeconfig, )
        kcl.load_and_set(client_config)

        return client.ApiClient(configuration=client_config)
Esempio n. 9
0
def k8s_api_client(client, cluster_name, kube_path=None):
    kube_path = None
    if kube_path is not None:
        kube_file = open(kube_path, "r")
        kube_config = kube_file.read()
        kube_file.close()
    else:
        cluster = client.rancher_api_client().by_id_cluster(cluster_name)
        kube_config = cluster.generateKubeconfig().config

    loader = KubeConfigLoader(config_dict=yaml.full_load(kube_config))

    client_configuration = type.__call__(Configuration)
    loader.load_and_set(client_configuration)
    client_configuration.api_key = {}
    client_configuration.verify_ssl = False
    k8s_client = ApiClient(configuration=client_configuration)
    return CustomObjectsApi(api_client=k8s_client).api_client
Esempio n. 10
0
def handler(event, context):
    print(event)
    eks_kubeconfig = build_eks_kubeconfig()
    print(eks_kubeconfig)
    k8s_config = yaml.safe_load(yaml.dump(eks_kubeconfig, default_flow_style=False))
    config = KubeConfigLoader(
        config_dict=k8s_config,
        config_base_path=None)
    kube_config.load_kube_config(client_configuration=config)

    coreApi = client.AppsV1Api()

    ecr_event_data = event["CodePipeline.job"]["data"]["inputArtifacts"]
Esempio n. 11
0
    def get_api_client(self):
        """
        Create Kubernetes API client with configuration from string.

        Returns:
            str: Kubeconfig file path

        """

        # This super-ugly code configuration is causes by wrong design of config-loading
        # functions in https://github.com/kubernetes-client/python
        client_config = type.__call__(client.Configuration)
        kubeconfig = self.cluster.get_kubeconfig()
        if kubeconfig is None:
            raise ValueError(
                "Could not create kubernetes API client: kubeconfig is not found "
            )
        kcl = KubeConfigLoader(config_dict=kubeconfig, )

        kcl.load_and_set(client_config)
        if self.cluster.provisioner.engine == 'kqueen.engines.OpenstackKubesprayEngine':
            client_config.assert_hostname = False
        return client.ApiClient(configuration=client_config)
Esempio n. 12
0
 def load_and_set(self, client_configuration):
     KubeConfigLoader.load_and_set(self, client_configuration)
     client_configuration.refresh_api_key = self.refresh_api_key
Esempio n. 13
0
 def __init__(self, *args, **kwargs):
     KubeConfigLoader.__init__(self, *args, **kwargs)
     self.api_key_expire_ts = None
Esempio n. 14
0
 def _read_kube_config(self, config_file_path):
     with open(config_file_path, "r") as f:
         loader = KubeConfigLoader(config_dict=yaml.safe_load(f))
         config = client.Configuration()
         loader.load_and_set(config)
         return config
Esempio n. 15
0
def build_management_cmd(config_dict: dict,
                         cmd: str = "",
                         tag: str = "") -> str:
    from kubernetes import client, config
    from kubernetes.client.models import V1Container
    from kubernetes.client.rest import ApiException
    from kubernetes.config.kube_config import KubeConfigMerger, KubeConfigLoader, KUBE_CONFIG_DEFAULT_LOCATION
    from kubernetes.config.config_exception import ConfigException

    config.load_kube_config()

    # Workaround to read the proxy-url as it is not currently read by load_kube_config()
    # TODO: submit as pull request to kubernetes python
    try:
        kcfg = KubeConfigMerger(KUBE_CONFIG_DEFAULT_LOCATION)
        k = KubeConfigLoader(config_dict=kcfg.config)
        proxy_url = k._cluster['proxy-url']
    except ConfigException:
        proxy_url = None

    if tag is not None:
        print(tag)

    if proxy_url is not None:
        client.Configuration._default.proxy = proxy_url

    app_v1_api = client.AppsV1Api()

    try:
        deployment = app_v1_api.read_namespaced_deployment(
            config_dict['project_name'],
            config_dict['namespace'],
            pretty=False)
    except ApiException as e:
        raise ExecuteError('AppsV1Api deployment not installed')

    container_v1 = deployment.spec.template.spec.containers[0]
    image_pull_secrets = None

    try:
        image_pull_secrets = deployment.spec.template.spec.image_pull_secrets[
            0]
    except ApiException as e:
        raise ExecuteError(
            'Exception when calling AppsV1Api->image_pull_secret \n')
    except TypeError as e:
        print(
            f'image_pull_secrets does not exist and its ok, carrying on. Info: {e}'
        )
        pass

    if tag:
        image_tag = container_v1.image.rsplit(':', 1)[0]
        image_tag = f'{image_tag}:{tag}'
        container = V1Container(env_from=container_v1.env_from,
                                env=container_v1.env,
                                image=image_tag,
                                command=cmd.split(),
                                args=[],
                                name="management",
                                stdin=True,
                                tty=True)
    else:
        container = V1Container(env_from=container_v1.env_from,
                                env=container_v1.env,
                                image=container_v1.image,
                                command=cmd.split(),
                                args=[],
                                name="management",
                                stdin=True,
                                tty=True)

    def create_dict_json_attributes(obj):
        if not hasattr(obj, 'to_dict'):
            return obj
        obj_dict = obj.to_dict()
        ret = dict()
        for key, value in obj_dict.items():
            attrib = getattr(obj, key)
            if attrib is None:
                # Don't patch with null values
                continue

            if isinstance(attrib, str) \
                    or isinstance(attrib, int) \
                    or isinstance(attrib, float) \
                    or isinstance(attrib, bool):
                ret[obj.attribute_map[key]] = value
            elif isinstance(attrib, list):
                ret[obj.attribute_map[key]] = [
                    create_dict_json_attributes(a) for a in attrib
                ]
            else:
                ret[obj.attribute_map[key]] = create_dict_json_attributes(
                    attrib)
        return ret

    # Convert V1_k8s_object to dictionary
    container_dict = create_dict_json_attributes(container)
    # Create dictionary
    overrides = dict(spec=dict(containers=[container_dict]))

    if image_pull_secrets:
        image_p_s_dict = create_dict_json_attributes(image_pull_secrets)
        overrides["spec"]["imagePullSecrets"] = [image_p_s_dict]

    overrides_str = dumps(overrides)

    return f'kubectl run management --rm --tty=true --stdin=true '\
        f'--image={container.image} '\
        f'--overrides=\'{overrides_str}\' '\
        f'--output yaml --command -- \'\''