Kubernetes - Access another cluster services with service account token

This post will show you how to access other cluster service with an authorization token

It would like:

curl $APISERVER/api/v1/namespaces/default/services/httpbin:80/proxy/get --header "Authorization: Bearer $TOKEN" --insecure

Deploy resource

Please know what you are going to deploy.

kustomize build github.com/RammusXu/toolkit/k8s/access-service-with-service-account-token

Apply

kustomize build github.com/RammusXu/toolkit/k8s/access-service-with-service-account-token | kubectl apply -f -

Get service account token

NAMESPACE=default
SERVICE_ACCOUNT_NAME=service-proxy
APISERVER=$(kubectl config view --minify | grep server | cut -f 2- -d ":" | tr -d " ")
SECRET_NAME=$(kubectl get secrets -n $NAMESPACE | grep ^$SERVICE_ACCOUNT_NAME | cut -f1 -d ' ')
TOKEN=$(kubectl describe secret $SECRET_NAME -n $NAMESPACE | grep -E '^token' | cut -f2 -d':' | tr -d " ")
curl $APISERVER/api/v1/namespaces/default/services/httpbin:http/proxy/get --header "Authorization: Bearer $TOKEN" --insecure

## result
{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip",
"Host": "35.10.10.10",
"User-Agent": "curl/7.54.0",
"X-Forwarded-Uri": "/api/v1/namespaces/default/services/httpbin:http/proxy/get"
},
"origin": "59.10.10.10",
"url": "http://35.10.10.10/get"
}

Clean

kustomize build github.com/RammusXu/toolkit/k8s/access-service-with-service-account-token | kubectl delete -f -

Troubleshooting

“services "httpbin" is forbidden: User "system:serviceaccount:default:default" cannot get resource "services/proxy" in API group "" in the namespace "default"“

It needs RBAC: services/proxy

kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: rammus:service-proxy
rules:
- apiGroups: [""]
resources: ["services/proxy"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]

no endpoints available for service "httpbin"

"status": "Failure",
"message": "no endpoints available for service \"httpbin\"",
"reason": "ServiceUnavailable",
"code": 503

The correct way to access are:


curl $APISERVER/api/v1/namespaces/default/services/httpbin:80/proxy/get --header "Authorization: Bearer $TOKEN" --insecure

curl $APISERVER/api/v1/namespaces/default/services/httpbin:http/proxy/get --header "Authorization: Bearer $TOKEN" --insecure

curl $APISERVER/api/v1/namespaces/default/services/httpbin/proxy/get --header "Authorization: Bearer $TOKEN" --insecure

curl $APISERVER/api/v1/namespaces/default/services/httpbin:http/proxy --header "Authorization: Bearer $TOKEN" --insecure

Reference