Управление кластером Kubernetes из GCP с помощью Python API - PullRequest
0 голосов
/ 28 августа 2018

Я хотел бы иметь возможность доступа и управления кластером GKE (kubernetes) из функции Google Cloud, написанной на python. Мне удалось получить доступ и получить данные из созданного кластера (по крайней мере, конечную точку, имя пользователя и пароль), однако я не знаю, как использовать их с пакетом API kubernetes.

Вот мой импорт:

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))

Однако я не могу понять, как настроить конечную точку и информацию об аутентификации. Может кто-нибудь помочь мне, пожалуйста?

Ответы [ 2 ]

0 голосов
/ 17 апреля 2019

Вы можете использовать пакет google.oauth2 для аутентификации с использованием учетной записи службы GCP.

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))

Обратитесь по ссылке ниже, чтобы узнать больше об авторизованных вызовах API GCP. https://developers.google.com/identity/protocols/OAuth2ServiceAccount

0 голосов
/ 29 августа 2018

Вы можете использовать токен на предъявителя вместо обычной аутентификации:

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))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...