Wednesday, August 21, 2019

[Kubernetes] Call Kubernetes APIs

If you want to use Bash Shell  to call Kubernetes APIs, Here is the way to get the token and use it as follows:

Prepare variables
#APISERVER="https://10.10.0.100:6443"
$ APISERVER=$(kubectl config view | grep server | cut -f 2- -d ":" | tr -d " ")
$ TOKEN=$(kubectl describe secret $(kubectl get secrets | grep default | cut -f1 -d ' ') | \
    grep -E '^token' | cut -f2 -d':' | tr -d '\t')
Call APIs
$ curl $APISERVER/api --header "Authorization: Bearer ${TOKEN//[[:space:]]/}" --insecure
{
  "kind": "APIVersions",
  "versions": [
    "v1"
  ],
  "serverAddressByClientCIDRs": [
    {
      "clientCIDR": "0.0.0.0/0",
      "serverAddress": "192.168.0.100:6443"
    }
  ]
}

Using Python to call Kubernetes API
https://github.com/kubernetes-client/python
$ sudo pip3 install kubernetes
$ ipython3
 
In [1]: 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))
   ...:
Listing pods with their IPs: 192.168.0.98 default danny-deploy 192.168.0.93 default hello-world-6db874c846-fdq7x 192.168.0.90 default hello-world-6db874c846-mp5cl 10.10.0.100 kube-system calico-node-rs7xw 192.168.0.92 kube-system coredns-5c98db65d4-8bg68 192.168.0.91 kube-system coredns-5c98db65d4-ccf8k 192.168.0.92 kube-system coredns-5c98db65d4-8bg68 192.168.0.91 kube-system coredns-5c98db65d4-ccf8k 192.168.0.92 kube-system coredns-5c98db65d4-8bg68 192.168.0.91 kube-system coredns-5c98db65d4-ccf8k 192.168.0.92 kube-system coredns-5c98db65d4-8bg68 192.168.0.91 kube-system coredns-5c98db65d4-ccf8k 10.10.0.100 kube-system etcd-51-0a50338-01 10.10.0.100 kube-system kube-apiserver-51-0a50338-01 10.10.0.100 kube-system kube-controller-manager-51-0a50338-01 10.10.0.100 kube-system kube-proxy-pflzg 10.10.0.100 kube-system kube-scheduler-51-0a50338-01 192.168.0.95 kube-system nvidia-device-plugin-daemonset-1.12-l5vdw 192.168.0.95 kube-system nvidia-device-plugin-daemonset-1.12-l5vdw 192.168.0.95 kube-system nvidia-device-plugin-daemonset-1.12-l5vdw 192.168.0.95 kube-system nvidia-device-plugin-daemonset-1.12-l5vdw 192.168.0.94 default busybox


No comments: