python kubernetes 使用1-认证

  • 前言

  kubernetes 是真的火呀,前段时间,项目要绑定资源,正好项目放在了k8s 集群,本文不做k8s 的解释,只针对python 使用k8s。

  • 安装

pip install kubernetes==12.0.1
  • k8s 认证

    • HTTPS 证书认证: 基于CA证书签名的数字证书认证
    • HTTP Token 认证: 通过生成的Token 登陆验证 (详情可自行百度 kubernetes token 安全认证)
  • HTTPS 证书认证

from kubernetes import config
path = "~/.kube/config"
config.load_kube_config(path)
View Code
  • HTTP Token 认证

1 from kubernetes import config, client
2 token = ""  # 命令生成
3 configuration = client.Configuration()
4 configuration.host = "https://192.168.3.201:16443"  # APISERVER地址
5 configuration.ssl_ca_cert="ca.crt"  # CA证书 /etc/kubernetes/pki/ca.crt
6 configuration.verify_ssl = True  # 启用证书验证
7 configuration.api_key = dict(authorization=f"Bearer {token}")
8 configuration.api_key = {"authorization": "Bearer " + token}  # 指定Token字符串
9 client.Configuration.set_default(configuration)
View Code
  • HTTPS 认证问题

  • k8s 配置文件在集群master机器上

  • 服务放在pod 内,读取不到master 机器上配置文件

  • k8s 配置放到代码内不安全等

  • 解决

  • 配置conf 转换成字典(配置仍然暴露在存储上)

1 import yaml
2 from kubernetes.config import load_kube_config_from_dict
3 from kubernetes import client
4 # 默认获取到的k8s配置
5 config = "apiVersion: v1\nclusters:\n- cluster:\n    server: https://172.6.2.20:6443\n    certificate-authority-data: data\n  name: kubernetes\ncontexts:\n- context:\n    cluster: kubernetes\n    user: \"kubernetes-admin\"\n  name: kubernetes-admin-\ncurrent-context: kubernetes-admin-c3ded8a2a8ef7ec06d2\nkind: Config\npreferences: {}\nusers:\n- name: \"kubernetes-admin\"\n  user:\n    client-certificate-data: data\n    client-key-data: data=="
6 load_kube_config_from_dict(yaml.safe_load(config))
7 client.AppsV1Api().list_deployment_for_all_namespaces()
  • 报错: urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='x.x.x.x', port=6443): Max retries exceeded with url: /api/v1/pods?watch=False (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:877)'),))

# 源码
def load_kube_config_from_dict(config_dict, context=None,
                               client_configuration=None,
                               persist_config=True):
    """Loads authentication and cluster information from config_dict file
    and stores them in kubernetes.client.configuration.

    :param config_dict: Takes the config file as a dict.
    :param context: set the active context. If is set to None, current_context
        from config file will be used.
    :param client_configuration: The kubernetes.client.Configuration to
        set configs to.
    :param persist_config: If True, config file will be updated when changed
        (e.g GCP token refresh).
    """

    if config_dict is None:
        raise ConfigException(
            'Invalid kube-config dict. '
            'No configuration found.')

    loader = _get_kube_config_loader(
        config_dict=config_dict, active_context=context,
        persist_config=persist_config)

    if client_configuration is None:
        config = type.__call__(Configuration)  # 注意这里
        loader.load_and_set(config)
        Configuration.set_default(config)
    else:
        loader.load_and_set(client_configuration)

# Configuration init 部分代码
        self.verify_ssl = True
        """SSL/TLS verification
           Set this to false to skip verifying SSL certificate when calling API
           from https server.
        """
View Code
 1 #重写 load_kube_config_from_dict
 2 from kubernetes.config.kube_config import _get_kube_config_loader
 3 from kubernetes.config.kube_config import load_kube_config_from_dict
 4 from kubernetes.config.config_exception import ConfigException
 5 from kubernetes.client.configuration import Configuration
 6 
 7 
 8 def load_kube_config_from_dict(config_dict, context=None,
 9                                client_configuration=None,
10                                persist_config=True):
11     """Loads authentication and cluster information from config_dict file
12     and stores them in kubernetes.client.configuration.
13 
14     :param config_dict: Takes the config file as a dict.
15     :param context: set the active context. If is set to None, current_context
16         from config file will be used.
17     :param client_configuration: The kubernetes.client.Configuration to
18         set configs to.
19     :param persist_config: If True, config file will be updated when changed
20         (e.g GCP token refresh).
21     """
22 
23     if config_dict is None:
24         raise ConfigException(
25             'Invalid kube-config dict. '
26             'No configuration found.')
27 
28     loader = _get_kube_config_loader(
29         config_dict=config_dict, active_context=context,
30         persist_config=persist_config)
31 
32     if client_configuration is None:
33         config = type.__call__(Configuration)
34         config.verify_ssl = False  #加上这个
35         loader.load_and_set(config)
36         Configuration.set_default(config)
37     else:
38         loader.load_and_set(client_configuration)
  • 报错 

    /usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py:1050: InsecureRequestWarning: Unverified HTTPS request is being made to host 'x.x.x.x'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
    InsecureRequestWarning,

  当请求关闭认证后,提示异常

      解决方法: 

 1 from kubernetes.config.kube_config import _get_kube_config_loader
 2 from kubernetes.config.kube_config import load_kube_config_from_dict
 3 from kubernetes.config.config_exception import ConfigException
 4 from kubernetes.client.configuration import Configuration
 5 import urllib3
 6 
 7 urllib3.disable_warnings()
 8 
 9 def load_kube_config_from_dict(config_dict, context=None,
10                                client_configuration=None,
11                                persist_config=True):
12     """Loads authentication and cluster information from config_dict file
13     and stores them in kubernetes.client.configuration.
14 
15     :param config_dict: Takes the config file as a dict.
16     :param context: set the active context. If is set to None, current_context
17         from config file will be used.
18     :param client_configuration: The kubernetes.client.Configuration to
19         set configs to.
20     :param persist_config: If True, config file will be updated when changed
21         (e.g GCP token refresh).
22     """
23 
24     if config_dict is None:
25         raise ConfigException(
26             'Invalid kube-config dict. '
27             'No configuration found.')
28 
29     loader = _get_kube_config_loader(
30         config_dict=config_dict, active_context=context,
31         persist_config=persist_config)
32 
33     if client_configuration is None:
34         config = type.__call__(Configuration)
35         config.verify_ssl = False
36         loader.load_and_set(config)
37         Configuration.set_default(config)
38     else:
39         loader.load_and_set(client_configuration)
  • k8s 配置转成字典使用

# 后来发现,正好用了阿里云的服务,获取配置
import yaml
from kubernetes import client
from kubernetes.config.kube_config import _get_kube_config_loader
from kubernetes.config.kube_config import load_kube_config_from_dict
from kubernetes.config.config_exception import ConfigException
from kubernetes.client.configuration import Configuration
import urllib3

urllib3.disable_warnings()

def load_kube_config_from_dict(config_dict, context=None,
                               client_configuration=None,
                               persist_config=True):
    """Loads authentication and cluster information from config_dict file
    and stores them in kubernetes.client.configuration.

    :param config_dict: Takes the config file as a dict.
    :param context: set the active context. If is set to None, current_context
        from config file will be used.
    :param client_configuration: The kubernetes.client.Configuration to
        set configs to.
    :param persist_config: If True, config file will be updated when changed
        (e.g GCP token refresh).
    """

    if config_dict is None:
        raise ConfigException(
            'Invalid kube-config dict. '
            'No configuration found.')

    loader = _get_kube_config_loader(
        config_dict=config_dict, active_context=context,
        persist_config=persist_config)

    if client_configuration is None:
        config = type.__call__(Configuration)
        config.verify_ssl = False
        loader.load_and_set(config)
        Configuration.set_default(config)
    else:
        loader.load_and_set(client_configuration)
# 默认从阿里云获取到的配置
config = "apiVersion: v1\nclusters:\n- cluster:\n    server: https://172.6.2.20:6443\n    certificate-authority-data: data\n  name: kubernetes\ncontexts:\n- context:\n    cluster: kubernetes\n    user: \"kubernetes-admin\"\n  name: kubernetes-admin-\ncurrent-context: kubernetes-admin-c3ded8a2a8ef7ec06d2\nkind: Config\npreferences: {}\nusers:\n- name: \"kubernetes-admin\"\n  user:\n    client-certificate-data: data\n    client-key-data: data=="
load_kube_config_from_dict(yaml.safe_load(config))
client.AppsV1Api().list_deployment_for_all_namespaces()
  • 总结

  目前k8s 认证到此结束,k8s 目前只是在学习过程中,后期会继续更新,感谢了.

  

  

posted @ 2022-06-23 15:40  Simba辛巴  阅读(915)  评论(0编辑  收藏  举报