简体   繁体   English

在 GCP 中使用 python Kubernetes api 的身份验证不起作用

[英]Authentication using python Kubernetes api in GCP is not working

I would like to be able to access GKE (kubernetes) cluster in GCP from python kubernetes client.我希望能够从 python kubernetes 客户端访问 GCP 中的 GKE (kubernetes) 集群。 I cant authenticate and connect to my cluster and i dont find the reason.我无法验证并连接到我的集群,也找不到原因。 Here is what i tried so far.这是我到目前为止所尝试的。

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


def test_gke(request):
    project_id = "myproject"
    zone = "myzone"
    cluster_id = "mycluster"

    credentials = compute_engine.Credentials()

    cluster_manager_client = ClusterManagerClient(credentials=credentials)
    cluster = cluster_manager_client.get_cluster(name=f'projects/{project_id}/locations/{zone}/clusters/{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))

I'd like to get the configuration working I have it work where, the code is running off cluster and it produces the kubectl config file for itself. 我想让配置工作 我让它工作在哪里,代码在集群外运行,它为自己生成kubectl配置文件。 (see update at end) (见最后更新)

Original原来的

The first solution assumes (!) you've the cluster configured in your local ( ~/.kube/config and probably adjusted by KUBE_CONFIG ) config.第一个解决方案假设(!)您已经在本地( ~/.kube/config并且可能通过KUBE_CONFIG )配置中配置了集群。

from google.cloud.container_v1 import ClusterManagerClient
from kubernetes import client,config

config.load_kube_config()
api_instance = client.CoreV1Api()

resp = api_instance.list_pod_for_all_namespaces()
for i in resp.items:
    print(f"{i.status.pod_ip}\t{i.metadata.namespace}\t{i.metadata.name}")

NOTE笔记

  1. Assumes you've run gcloud containers clusters get-credentials to set the ~/.kube/config file for the current cluster (and has a current-context set.假设您已经运行gcloud containers clusters get-credentials来为当前集群设置~/.kube/config文件(并且设置了current-context
  2. Uses your user credentials in the ~/.kube/config file so no additional credentials are needed.~/.kube/config文件中使用您的用户凭据,因此不需要额外的凭据。

Update更新

Okay, I have it working.好的,我有它的工作。 Here's the code that will generate a kubectl config and connect to the cluster.这是将生成kubectl配置并连接到集群的代码。 This code uses Application Default Credentials to provide a Service Account key to the code (usually export GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json )此代码使用应用程序默认凭据为代码提供服务帐户密钥(通常export GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json

import os
import google.auth
import base64

from google.cloud.container_v1 import ClusterManagerClient
from kubernetes import client,config
from ruamel import yaml

PROJECT = os.getenv("PROJECT")
ZONE = os.getenv("ZONE")
CLUSTER = os.getenv("CLUSTER")

# Get Application Default Credentials
# `project_id` is the Service Account's
# This may differ to the cluster's `PROJECT`
credentials, project_id = google.auth.default()

# Get the cluster config from GCP
cluster_manager_client = ClusterManagerClient(credentials=credentials)

name=f"projects/{PROJECT}/locations/{ZONE}/clusters/{CLUSTER}"
cluster = cluster_manager_client.get_cluster(name=name)

SERVER = cluster.endpoint
CERT = cluster.master_auth.cluster_ca_certificate

configuration = client.Configuration()

# Create's a `kubectl` config
NAME="freddie" # arbitrary
CONFIG=f"""
apiVersion: v1
kind: Config
clusters:
- name: {NAME}
  cluster:
    certificate-authority-data: {CERT}
    server: https://{SERVER}
contexts:
- name: {NAME}
  context:
    cluster: {NAME}
    user: {NAME}
current-context: {NAME}
users:
- name: {NAME}
  user:
    auth-provider:
      name: gcp
      config:
        scopes: https://www.googleapis.com/auth/cloud-platform
"""

# The Python SDK doesn't directly support providing a dict
# See: https://github.com/kubernetes-client/python/issues/870
kubeconfig = yaml.safe_load(CONFIG)

loader = config.kube_config.KubeConfigLoader(kubeconfig)
loader.load_and_set(configuration)

api_client= client.ApiClient(configuration)
api_instance = client.CoreV1Api(api_client)

# Enumerate e.g. Pods
resp = api_instance.list_pod_for_all_namespaces()
for i in resp.items:
     print(f"{i.status.pod_ip}\t{i.metadata.namespace}\t{i.metadata.name}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM