Try using Kubernetes Client -Python-

Preface

I just arranged what I did unchanged. I haven't touched Python so much, so I tried using it for studying. I don't know if it will be helpful, but if you want to use it in the same way, you may want to follow it.

environment

The environment used is as follows.

Also, Kubernetes uses IBM Cloud Kubernetes Service (IKS), but I wonder if it can be used anywhere.

Introduction and use of python client

Introduction / sample code implementation

Follow git. Introduced Client with pip.

pip install kubernetes

Sample code (Refer to all pods)

from kubernetes import client, config

# Configs can be set in Configuration class directly or using helper utility
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))

This code accesses the cluster based on the environment variable KUBECONGIG. Therefore, it is necessary to get the config of the IKS cluster.

Obtaining KUBECONFIG

Use the IBM Cloud CLI to get the KUBECONFIG.

After logging in to the target account, execute the following command.

$ ibmcloud ks cluster config --cluster mycluster
Kubernetes version 1.16 has removed deprecated APIs. For more information, see <http://ibm.biz/k8s-1-16-apis>

warning: The behavior of this command in your current CLI version is deprecated, and becomes unsupported when CLI version 1.0 is released in March 2020. To use the new behavior now, set the '{{.BetaVar}}' environment variable. In {{.Shell}}, run '{{.Command}}'.
Note: Changing the beta version can include other breaking changes.For more information, http://ibm.biz/iks-cli-See v1

OK
The mycluster configuration has been successfully downloaded.

Export your environment variables to get started with Kubernetes.

export KUBECONFIG=/Users/<user_name>/.bluemix/plugins/kubernetes-service/clusters/..../zzzz.yml

Sample code execution

$ python kubeapi.py Listing pods with their IPs:
10.76.68.235    kube-system     calico-kube-controllers-7ddc977c56-ccrkh
10.76.68.235    kube-system     calico-node-7b88g
・ ・ ・ ・ ・ ・ ・
・ ・ ・ ・ ・ ・ ・

I got a list of pods.

Connection to Remote Cluster

As a connection method that does not use kube-config, there is a connection method that uses a token or TLS certificate. Simply this. → https://github.com/kubernetes-client/python/blob/master/examples/remote_cluster.py

What I wanted to do was create a ServiceAccount and use the Kubernetes API based on that credentials. It was that.

I'm still studying around Service Account, so I would like to introduce only what I did.

  1. Create Service Account (People who use Kubernetes API)
  2. Create Cluster Role (role on Kubernetes Cluster and allowed API rules)
  3. Create ClusterRoleBinding (Association of ServiceAccount and ClusterRole. Teaching roles and rules to those who use API.)
  4. Get the Config information of Service Account (Is Secret done? It should be, so bring it from there.)
  5. Create a ca.cert file from the obtained Config information.

The information used from Secret of Config information is token, ca.crt. Bese64 decode and use.

The created ca.cart file has this format. If you decode it, it should already be in this state, so paste it as it is.

-----BEGIN CERTIFICATE-----
Character string Character string Character string Character string Character Mojimo jimo ...
-----END CERTIFICATE-----

In the Python code, the part corresponding to the above config.load_kube_config () is as follows.

  # Configs can be set in Configuration class directly or using helper utility
  configuration = client.Configuration()
  configuration.verify_ssl = True
  configuration.host = 'https://xxx.xxx.xx.xx.xx.:yyy'
  #Insert the acquired token as it is.
  configuration.api_key['authorization'] = '<token>'
  configuration.api_key_prefix['authorization'] = 'Bearer'
  #ca.The path to cert. It doesn't move even if it is thrust as it is.
  configuration.ssl_ca_cert = './ca.cert'
  namespace = 'default'

  v1 = client.CoreV1Api(client.ApiClient(configuration))

Now you can use the API! Should be! I think that you have taken various troublesome steps, but please adjust it by yourself. Especially around authority.

If you go beyond this, it will work almost according to Samples.

It's about writing notes, but that's it.

Recommended Posts

Try using Kubernetes Client -Python-
Try using Tweepy [Python2.7]
[Python] Try using Tkinter's canvas
Try python
Try using Pleasant's API (python / FastAPI)
Try using LevelDB in Python (plyvel)
Try using Python argparse's action API
Try using the Python Cmd module
Try using Leap Motion in Python
Try using Amazon DynamoDB from Python
Try using Tkinter
Try using the Wunderlist API in Python
Try using docker-py
Try mathematical formulas using Σ with python
Try using the Kraken API in Python
Try using PDFMiner
Try using Dialogflow (formerly API.AI) Python SDK #dialogflow
Start using Python
Try using geopandas
Try using Python with Google Cloud Functions
Try using Selenium
Try using scipy
Python> try: / except:
Try using Junos On-box Python # 2 Commit Script
Try to operate Excel using Python (Xlwings)
Try using pandas.DataFrame
Try using Junos On-box Python # 1 Op Script
Try using django-swiftbrowser
Try using matplotlib
Try using tf.metrics
Try using PyODE
Scraping using Python
Develop and deploy Python APIs using Kubernetes and Docker
Try using the BitFlyer Ligntning API in Python
Python: Try using the UI on Pythonista 3 on iPad
Try using the Python web framework Tornado Part 1
Try using the collections module (ChainMap) of python3
Try using tensorflow ① Build python environment and introduce tensorflow
Try using the Python web framework Tornado Part 2
Try using ChatWork API and Qiita API in Python
Try using the DropBox Core API in Python
Try scraping with Python.
Python StatsD client configuration
Fibonacci sequence using Python
Data analysis using Python 0
Try using virtualenv (virtualenvwrapper)
Use LiquidTap Python Client ③
Data cleaning using Python
[Azure] Try using Azure Functions
Try Debian + Python 3.4 + django1.7 ...
Using Python #external packages
Try using virtualenv now
WiringPi-SPI communication using Python
Try gRPC in Python
Try using W & B
Age calculation using python
Try using Django templates.html
Use LiquidTap Python Client ②
[Kaggle] Try using LGBM
Try using Python's feedparser.
Try using Python's Tkinter