Connect to kubernetes api from pod

Using kubernetes API you can do some cool things like pod discovery. This page describes how to connect to API inside the pod.

Service token is a plain text file /var/run/secrets/kubernetes.io/serviceaccount/token which can be passed to curl or some http library as an Authorization header.

export TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)

echo $TOKEN

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImRlZmF1bHQtdG9rZW4tYTlhdXoiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGVmYXVsdCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6ImM2Y2U3ZjVmLTJlMzYtMTFlNi1hMGFlLTAyMzc4NzRiOGRkNSIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpkZWZhdWx0OmRlZmF1bHQifQ.zbVgwiDOZ4nDD54GOs68oJ_O9RcxFDX_cWPAUdWiGBdfPbastqrxGaq2W4w4UaQ_tVZ-6tD6CS9LkuepPFfUrZjD7TXZpme3nAOe_RPIcS2TLIPoBl_aLd9z2YRLZWqcpB-NzKf6NCCzGOXOnz5Dyduf4DIQpBFRZ_D1Cv3OkcvjkJvktiWs7czCL7sySxrI5EpaZ1zIN8idqCJu6gBoYYLHKMtqMhOhoW-6Uc8LRZcdHpwKuPFGy-lnMxo2NFEv5sJeJkV5kY12N3dsisFfqDvmuMvfdvDx6CIf5ociygU-TfPkjwcdG-haz2fDElOaRUu5P5RfA0XQqMUO3YBeeQ

curl -sSk -H "Authorization: Bearer ${TOKEN}" https://${KUBERNETES_SERVICE_HOST}/api/v1/services
{
  "kind": "ServiceList",
  "apiVersion": "v1",
  "metadata": {
    "selfLink": "/api/v1/services",
    "resourceVersion": "2378779"
  },
  "items": 
...