0

I am trying to get a Python client to connect to my Kubernetes. I took inspiration from this question and ended up with something like this:

  1. A command to get the key: kubectl describe secret $(kubectl get secrets | grep default | cut -f1 -d ' ') | grep -E '^token' | cut -f2 -d':' | tr -d '\t'

  2. A little program to get the namespaces to check that everything is ok:

from kubernetes import client, config
from kubernetes.client.rest import ApiException
ApiToken = 'eyJhbGciOiJSUzI1NiIsImtpZCI6IlREcVNGVXhTUEljWFBxR0RseV84ZUxPWnlkOG1Fcm8wUVlqOWE0WTV6cUEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImRlZmF1bHQtdG9rZW4tZzZ4Z2oiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGVmYXVsdCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6Ijk1OGM3MTNhLTU1NTQtNGNkOS1hNGNlLTNkNThhZDE0Mjg5NyIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpkZWZhdWx0OmRlZmF1bHQifQ.gPD7NZdD3isvRHTfomAZXfHQr7NtNk0RCtaeDFVseiPunCRq41vyTdDMg5dVY4fAlXscUXs-M26IA6UgurIzvAsVFo8V2a2W8pPwfwAiKW1oYL_tTKu2GszndgdiKOMZvfSyS5-V85eb7QyC_U40cRlfw8hKf7WDlERCZIy77GUegkA2cfpXZNVfmbYiPF8fji5DhWRMocHunCH-1mk80E9b3-uwu5zWJbSwjosU8mCBXzUUBbUYAiN_BkL1_7wno8HVAMDYmDd1skGqaPiXBOQc9rYnisyA8QmnM9urib3jO7H0KEzmK_oHSqpqXBClYICz6_LW7VzBfxgaChfDRQ'
configuration = client.Configuration()
configuration.host = '127.0.0.1:8001'
configuration.verify_ssl=False
configuration.debug = True
configuration.api_key={"authorization":"Bearer "+ ApiToken}
client.Configuration.set_default(configuration)
kubeApi = client.CoreV1Api()

try:
    namespaces = kubeApi.list_namespace()
    print (namespaces)
except ApiException as e:
    print("Exception when calling CoreV1Api->list_pod_for_all_namespaces: %s\n" % e)

But then I get this:

urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='127.0.0.1', port=8001): Max retries exceeded with url: /api/v1/namespaces (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7ff09e174880>: Failed to establish a new connection: [Errno 111] Connection refused'))

I suspect that the problem is the key, but to be honest I do not know Kubernetes very well so i am a bit lost here.

Gaëtan
  • 779
  • 1
  • 8
  • 26
  • 2
    "Connection refused" means that the TCP connection could not even be established. This step happens before the key exchange, so the key is probably not at fault. Check your hostname, port number and firewall settings. – Thomas Jun 30 '21 at 12:44

1 Answers1

3

You get a connection refused, therefore nothing is listening on the port and host you described. Since kubectl works, just use the same settings in your program:

kubectl config view

Shows the configuration for the current context, use the server that is printed there for your program.

Thomas
  • 11,272
  • 2
  • 24
  • 40