使用python API从GCP管理Kubernetes集群

时间:2018-08-28 09:31:31

标签: python-3.x kubernetes google-cloud-platform google-cloud-functions google-kubernetes-engine

我希望能够通过python编写的Google Cloud函数访问和管理GKE(kubernetes)集群。 我设法从创建的集群中访问和检索数据(至少是端点,用户名和密码),但是我不知道如何在kubernetes软件包api中使用它们。

这是我的进口商品:

import google.cloud.container_v1 as container
from google.auth import compute_engine
from google.cloud.container_v1 import ClusterManagerClient
from kubernetes import client, config

这是集群数据的代码:

project_id = 'my-gcp-project'
zone = 'my-zone'
cluster_id = 'my-existing-cluster'

credentials = compute_engine.Credentials()

gclient: ClusterManagerClient = container.ClusterManagerClient(credentials=credentials)

cluster = gclient.get_cluster(project_id,zone,cluster_id)
cluster_endpoint = cluster.endpoint
print("*** CLUSTER ENDPOINT ***")
print(cluster_endpoint)

cluster_master_auth = cluster.master_auth
print("*** CLUSTER MASTER USERNAME PWD ***")
cluster_username = cluster_master_auth.username
cluster_password = cluster_master_auth.password
print("USERNAME : %s - PASSWORD : %s" % (cluster_username, cluster_password))

那之后我想做这样的事情:

config.load_kube_config()
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))

但是,我不知道如何设置端点和身份验证信息。 有人可以帮我吗?

3 个答案:

答案 0 :(得分:5)

您可以使用承载令牌,而不是使用基本身份验证:

from google.auth import compute_engine
from google.cloud.container_v1 import ClusterManagerClient
from kubernetes import client


def test_gke(request):
    project_id = "my-gcp-project"
    zone = "my-zone"
    cluster_id = "my-existing-cluster"

    credentials = compute_engine.Credentials()

    cluster_manager_client = ClusterManagerClient(credentials=credentials)
    cluster = cluster_manager_client.get_cluster(project_id, zone, cluster_id)

    configuration = client.Configuration()
    configuration.host = f"https://{cluster.endpoint}:443"
    configuration.verify_ssl = False
    configuration.api_key = {"authorization": "Bearer " + credentials.token}
    client.Configuration.set_default(configuration)

    v1 = client.CoreV1Api()
    print("Listing pods with their IPs:")
    pods = v1.list_pod_for_all_namespaces(watch=False)
    for i in pods.items:
        print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

答案 1 :(得分:1)

下面是使用GCP服务帐户生成不记名令牌的示例。

请注意,在连接到群集时,应确保启用SSL验证,否则您很容易受到中间人的攻击。 GKE基于自己的证书为需要手动配置的群集进行此操作。

import base64
import google.auth.transport.requests
from google.oauth2 import service_account
from google.cloud.container_v1 import ClusterManagerClient
from kubernetes import client
from python_hosts.hosts import Hosts, HostsEntry


def test_gke(request):
    project_id = "my-gcp-project"
    zone = "my-zone"
    cluster_id = "my-existing-cluster"

    # Use a service account configured in GCP console,
    # authenticating with a JSON key
    credentials = service_account.Credentials \
        .from_service_account_file('gcloud_key.json')

    # Get cluster details
    cluster_manager_client = ClusterManagerClient(credentials=credentials)
    cluster = cluster_manager_client.get_cluster(
            project_id=project_id, zone=zone,
            cluster_id=cluster_id)

    # Save cluster certificate for SSL verification
    cert = base64.b64decode(cluster.master_auth.cluster_ca_certificate)
    cert_filename = 'cluster_ca_cert'
    cert_file = open(cert_filename, 'w')
    cert_file.write(cert)
    cert_file.close()

    # Configure hostname for SSL verification
    hosts = Hosts()
    hosts.add([HostsEntry(
            entry_type='ipv4',
            address=cluster.endpoint, names=['kubernetes'])])
    hosts.write()

    # Get a token with the scopes required by GKE
    kubeconfig_creds = credentials.with_scopes(
            ['https://www.googleapis.com/auth/cloud-platform',
             'https://www.googleapis.com/auth/userinfo.email'])
    auth_req = google.auth.transport.requests.Request()
    kubeconfig_creds.refresh(auth_req)

    configuration = client.Configuration()
    configuration.host = "https://kubernetes"
    configuration.ssl_ca_cert = cert_filename
    kubeconfig_creds.apply(configuration.api_key)
    client.Configuration.set_default(configuration)

    v1 = client.CoreV1Api()
    print("Listing pods with their IPs:")
    pods = v1.list_pod_for_all_namespaces(watch=False)
    for i in pods.items:
        print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

以下也是此功能的Python库列表(其pip项目名称):

  • kubernetes
  • google-api-python-client
  • google-cloud-container
  • python主机

答案 2 :(得分:0)

You can use google.oauth2 package for authentication using GCP Service Account.

from google.oauth2 import service_account
from google.cloud.container_v1 import ClusterManagerClient
from kubernetes import client, config
import os

def test_gke(project_id, zone, cluster_id):
    SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
    credentials = service_account.Credentials.from_service_account_file(os.getenv('GOOGLE_APPLICATION_CREDENTIALS'), scopes=SCOPES)
    cluster_manager_client = ClusterManagerClient(credentials=credentials)
    cluster = cluster_manager_client.get_cluster(project_id, zone, cluster_id)
    configuration = client.Configuration()
    configuration.host = "https://"+cluster.endpoint+":443"
    configuration.verify_ssl = False
    configuration.api_key = {"authorization": "Bearer " + credentials.token}
    client.Configuration.set_default(configuration)

    v1 = client.CoreV1Api()
    print("Listing pods with their IPs:")
    pods = v1.list_pod_for_all_namespaces(watch=False)
    for i in pods.items:
        print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

Refer the link below to know more about GCP Authorized API calls https://developers.google.com/identity/protocols/OAuth2ServiceAccount