How to expose Kubernetes API internally in new namespace?

7/15/2017

Kubernetes by default adds a kubernetes service in the default namesapce. This allows access to the kubernetes API from any pod in that namespace.

For example, I can

TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
kubectl exec -it $SOME_POD -- bash
curl -v https://kubernetes/api/v1/ \
  -H "Authorization: Bearer $TOKEN" \
  -k -v

And get something like:

< HTTP/1.1 200 OK
< Content-Type: application/json
< Date: Sat, 15 Jul 2017 22:16:09 GMT
< Transfer-Encoding: chunked
<
{
  "kind": "APIResourceList",
  "groupVersion": "v1",
  "resources": [
    {
      "name": "bindings",
      "namespaced": true,
  ...

If I create a new namespace, there is no kubernetes service by default. I'm trying to create one by using the following resource service definition (basically copied from the default namespace):

apiVersion: v1
kind: Service
metadata:
  labels:
    component: apiserver
    provider: kubernetes
  name: kubernetes
  resourceVersion: "12"
spec:
  ports:
  - name: https
    port: 443
    protocol: TCP
    targetPort: 443
  sessionAffinity: ClientIP
  type: ClusterIP

But this doesn't seem to work since there seems to be tied to any pod.

Basically, I want the same behavior as in the default namespace in a newly created namespace.

Current Version:

{
  "major": "1",
  "minor": "5",
  "gitVersion": "v1.5.7",
  "gitCommit": "8eb75a5810cba92ccad845ca360cf924f2385881",
  "gitTreeState": "clean",
  "buildDate": "2017-04-27T09:42:05Z",
  "goVersion": "go1.7.5",
  "compiler": "gc",
  "platform": "linux/amd64"
}
-- Jorge Silva
kubernetes
networking

2 Answers

7/15/2017

You can access the kubernetes service from other namespaces by qualifying the hostname:

The hostnames kubernetes.default.svc, kubernetes.default.svc.cluster.local, and the IP contained in $KUBERNETES_SERVICE_HOST will all resolve to the kubernetes API service from any namespace.

Following your example, you could do this from any namespace:

TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
kubectl exec -it $SOME_POD -- bash
curl -v https://kubernetes.default.svc/api/v1/ \
  -H "Authorization: Bearer $TOKEN" 
  -k -v
-- Jordan Liggitt
Source: StackOverflow

7/15/2017

I think service IP is same for all the name spaces. for the new namespace kubernetes service IP comes to POD as environment variable KUBERNETES_SERVICE_HOST.

you can access api like this.

TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
curl -k -v https://$KUBERNETES_SERVICE_HOST/api/v1/   -H "Authorization: Bearer $TOKEN

I tested this version 1.7.1 . I didn't have the older version of the cluster. you can test this and update the status.

Thanks SR

-- sfgroups
Source: StackOverflow