¿Cuál es el equivalente de la API de Kubernetes de '--contexto'?

Con la kubectl línea de comandos, puedo ejecutar comandos en un contexto dado usando el --context bandera, como:

kubectl --context  get deploy messenger

Sin embargo, cuando estoy tratando de enumerar las cápsulas usando la siguiente API, no parece haber una manera de pasar en el contexto.

 from kubernetes import client
 v1 = client.CoreV1Api()
 pods = v1.list_namespaced_pod("messenger")

El comando anterior parece darme las cápsulas en el contexto actual.

¿Hay una manera de enumerar las cápsulas bajo un contexto diferente usando la API de Python?

He mirado los siguientes documentos y he buscado la String. context pero no ha encontrado nada iluminador.

https://kubernetes.io/docs/tasks/administer-cluster/access-cluster-api/https://github.com/kubernetes-client/python/blob/master/kubernetes/README.md

Pregunta hecha hace 3 años, 5 meses, 0 días - Por syntaxsensei


3 Respuestas:

  • puede leer los contextos del archivo y pasarlo al CoreV1Api función como abajo

    # Copyright 2016 The Kubernetes Authors.
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #     http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    
    """
    Allows you to pick a context and then lists all pods in the chosen context.
    Please install the pick library before running this example.
    """
    
    from kubernetes import client, config
    from kubernetes.client import configuration
    from pick import pick  # install pick using `pip install pick`
    
    
    def main():
        contexts, active_context = config.list_kube_config_contexts()
        if not contexts:
            print("Cannot find any context in kube-config file.")
            return
        contexts = [context['name'] for context in contexts]
        active_index = contexts.index(active_context['name'])
        cluster1, first_index = pick(contexts, title="Pick the first context",
                                     default_index=active_index)
        cluster2, _ = pick(contexts, title="Pick the second context",
                           default_index=first_index)
    
        client1 = client.CoreV1Api(
            api_client=config.new_client_from_config(context=cluster1))
        client2 = client.CoreV1Api(
            api_client=config.new_client_from_config(context=cluster2))
    
        print("\nList of pods on %s:" % cluster1)
        for i in client1.list_pod_for_all_namespaces().items:
            print("%s\t%s\t%s" %
                  (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
    
        print("\n\nList of pods on %s:" % cluster2)
        for i in client2.list_pod_for_all_namespaces().items:
            print("%s\t%s\t%s" %
                  (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
    
    
    if __name__ == '__main__':
        main()
    

    Código se puede encontrar en allí la carpeta de ejemplo github también https://github.com/kubernetes-client/python/blob/master/examples/multiple_clusters.py

    Respondida el Dec 19, 2020 a las 03:23 - por pixelprodigy

    Votos positivos: 0 | Votos negativos: 0

  • En la API de Python para Kubernetes, puedes usar la clase Configuration del cliente para establecer un contexto diferente al interactuar con el clúster. Aquí tienes un ejemplo de cómo puedes hacerlo:

    python
    from kubernetes import client, config
    
    

    Cargar la configuración del contexto deseado

    config.load_kube_config(context="mycontext")

    Crear una instancia del cliente API

    v1 = client.CoreV1Api()

    Obtener la lista de pods en un espacio de nombres específico en el contexto seleccionado

    pods = v1.list_namespaced_pod("messenger")

    Iterar sobre los pods

    for pod in pods.items: print(pod.metadata.name)

    En este ejemplo, config.load_kube_config(context="mycontext") te permite cargar la configuración del contexto mycontext antes de interactuar con el clúster. A partir de ese punto, cualquier operación que realices con el cliente API se ejecutará en el contexto especificado.

    Espero que esta solución te ayude a manejar el contexto deseado al utilizar la API de Kubernetes en Python. Si tienes alguna otra pregunta o necesitas más ayuda, ¡no dudes en decírmelo!

    Respondida el Dec 20, 2020 a las 03:27 - por Gpt

    Votos positivos: 0 | Votos negativos: 0

  • Para especificar el contexto al listar pods usando la API de Python de Kubernetes, puedes utilizar el argumento context del método configuration del objeto del cliente. Aquí tienes un ejemplo:

    python
    from kubernetes import client, config
    
    

    Cargar la configuración del contexto deseado.

    config.load_kube_config(context="mycontext")

    Crear un objeto de cliente.

    v1 = client.CoreV1Api()

    Listar pods en el contexto especificado.

    pods = v1.list_namespaced_pod("messenger")

    El argumento context acepta el nombre del contexto que deseas utilizar. Puedes obtener una lista de los contextos disponibles ejecutando el siguiente comando:

    
    kubectl config get-contexts
    

    Ten en cuenta que debes tener las credenciales adecuadas para acceder al contexto especificado.

    Respondida el Dec 20, 2020 a las 03:35 - por Gemini

    Votos positivos: 0 | Votos negativos: 0