4
1

More than 3 years have passed since last update.

Kubernetes Client -Python-を使ってみる

Last updated at Posted at 2019-12-19

まえがき

変わらずやったことを並べただけです。Pythonあまり触ったこともなかったので、勉強かねて使ってみました。
参考になるかはわかりませんが、同じように使う際には辿ってくださるといいかもしれません。

環境

使用している環境は下記の通り。
- macOS Mojave
- Core i5
- 8GB
- python3.8.0(brew・pyenvで導入)

また、KubernetesはIBM Cloud Kubernetes Service(IKS)を利用していますが、どこでも使える内容かと。

python clientの導入・利用

導入・サンプルコード実装

gitにそって実施します。pipでClientを導入。

pip install kubernetes

サンプルコード(全てのpodを参照する)

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

このコードでは、環境変数のKUBECONGIGを元にクラスターにアクセスする。そのため、IKSクラスターのconfigを取得する必要がある。

KUBECONFIGの取得

IBM Cloud CLIを利用して、KUBECONFIGを取得します。

対象のアカウントにログイン後、以下コマンドを実行。

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

警告: 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. 詳しくは、http://ibm.biz/iks-cli-v1 を参照してください

OK
mycluster の構成は正常にダウンロードされました。

環境変数をエクスポートして Kubernetes の使用を開始してください。

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

※来年サポート予定の新しいCLIを使うとこのexport文を実行しなくても良くなるようです。
※私がやったときは ❌/plugins/kubernetes-service →⭕️/plugins/container-service でしたがそこまで気にする必要はないかと。

サンプルコード実行

$ 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
・・・・・・・
・・・・・・・

pod一覧を取れました。

RemoteClusterへの接続

kube-configを利用しない接続の方法として、トークンやTLS証明書を利用した接続方法があります。
単純にこれ。→https://github.com/kubernetes-client/python/blob/master/examples/remote_cluster.py

私がしたかったことは、ServiceAccountを作成して、その認証情報をもとにKubernetes APIを利用する。
ということでした。

ServiceAccount周りもまだ勉強中なところがあるので、やったことだけ紹介しますと、
1. ServiceAccount作成(Kubernetes APIを使う人。)
2. ClusterRole作成(Kubernetes Cluster上での役割と、許可されるAPIのルール)
3. ClusterRoleBinding作成(ServiceAccountとClusterRoleの対応付け。APIを使う人に、役割とルールを教える。)
4. ServiceAccountのConfig情報を取得(Secretができている?はずなのでそこから持ってきます。)
5. 取得したConfig情報からca.certファイルを作る。

Config情報のSecretから使う情報は、token、ca.crtです。Bese64デコードして使います。

作ったca.cartファイルはこんな形式。デコードするとすでにこの状態のはずなのでそのまま貼り付けます。

-----BEGIN CERTIFICATE-----
文字列文字列文字列文字列文字文字もじもjimo・・・・・・・
-----END CERTIFICATE-----

Pythonのコードでは、上記のconfig.load_kube_config()に当たる部分が以下のようになります。

  # 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'
  #取得したtokenをそのまま突っ込みます。
  configuration.api_key['authorization'] = '<token>'
  configuration.api_key_prefix['authorization'] = 'Bearer'
  #ca.certへのパスです。そのまま突っ込んでも動きません。
  configuration.ssl_ca_cert = './ca.cert'
  namespace = 'default'

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

これでAPIが使える!はず!
色々面倒な手順を取ってしまっていると思いますが、その辺は各自で調整をお願いします。特に権限周り。

ここさえ超えてしまえれば、ほとんどサンプル集通りに動きます。

メモ書き程度の内容ですが、以上。

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1