---
# System prepended metadata

title: http req to k8s api
tags: [K8s]

---

在 master 下 `kubectl get --raw="/api/v1/pods"` 會拿到扁平化的json物件
```
/api/v1/namespaces
/api/v1/pods
/api/v1/namespaces/my-namespace/pods
/apis/apps/v1/deployments
/apis/apps/v1/namespaces/my-namespace/deployments
/apis/apps/v1/namespaces/my-namespace/deployments/my-deployment
```

先創一個ns
kubectl create my-namespace

1. 創一個service account
`kubectl create serviceaccount my-service-account -n my-namespace`
2. 幫sa分配clusterRole
```kubectl create clusterrolebinding my-cluster-role-binding -n my-namespace --clusterrole=view --serviceaccount=my-namespace:my-service-account```
3. 創一個pod並分配sa
建立一個yaml
```apiVersion: v1
kind: Pod
metadata:
  name: my-pod
  namespace: test-token
spec:
  serviceAccountName: my-service-account
  containers:
  - name: my-container
    image: nginx
```
之後再創一個pod
`kubectl apply -f my-pod.yaml`
4. 檢查token存不存在
```
kubectl exec -n test-token my-pod -- cat /var/run/secrets/kubernetes.io/serviceaccount/token
```
理論上會噴token給你
5. 把它當成一個變數然後嘗試發http req
```TOKEN=$(kubectl exec -n test-token my-pod -- cat /var/run/secrets/kubernetes.io/serviceaccount/token)```
然後
```curl -X GET https://your-cluster-ip/api/v1/namespaces/test-token/pods --header "Authorization: Bearer $TOKEN" --insecure```
就發現url出問題
可以翻`$HOME/.kube/config` 或是打`kubectl config view`找裡面的`server:your-cluster-ip`把替換掉上面的url

然後就發現拿到的json檔案寫forbidden
```
{
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {},
  "status": "Failure",
  "message": "pods is forbidden: User \"system:anonymous\" cannot list resource \"pods\" in API group \"\" in the namespace \"test-token\"",
  "reason": "Forbidden",
  "details": {
    "kind": "pods"
  },
  "code": 403
}
```
嘿嘿 記得對好\$ip 和$token
理論上都沒弄錯會拿到一大包json檔案










https://kubernetes.io/docs/reference/using-api/api-concepts/