使用curl访问kubernetes API (https、RBAC认证)

1. 我们先创建一个带有集群管理员权限的service account (cicd)用来实验 :

 参考:使用service account(sa) 方式 远程访问k8s集群

2. 创建一个POD ,并配置该pod 使用 cicd sa :

mac-temp:curl test$ cat ./deployment.yaml 
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: curl
spec:
  replicas: 1 
  template:
    metadata:
      labels:
        app: curl
    spec:
      serviceAccountName: cicd
      containers:
      - name: curl
        image: appropriate/curl
        command: ["sleep"]
        args: ["5000"]

mac-temp:curl test$ kubectl create -f ./deployment.yaml

3. 访问kubernetes API :

#查出curl pod的全名:
mac-temp:curl test$ kubectl get po |grep curl
curl-6f9755dc85-l8td4            1/1       Running   0          24m

#把servile account 的 token 保存在变量中:
mac-temp:curl test$ TOKEN_VALUE=$(kubectl exec curl-6f9755dc85-l8td4 -- cat /var/run/secrets/kubernetes.io/serviceaccount/token)

#list所有POD:
mac-temp:curl test$ kubectl exec curl-6f9755dc85-l8td4 -- curl -k --cacert /var/run/secrets/kubernetes.io/serviceaccount/ca.crt -H  "Authorization: Bearer $TOKEN_VALUE" https://kubenetes/api/v1/pods?resourceVersion=0

#list所有service:
mac-temp:curl test$ kubectl exec curl-6f9755dc85-l8td4 -- curl -k --cacert /var/run/secrets/kubernetes.io/serviceaccount/ca.crt -H  "Authorization: Bearer $TOKEN_VALUE" https://kubenetes/api/v1/services?resourceVersion=0

#list所有namespace:
mac-temp:curl test$ kubectl exec curl-6f9755dc85-l8td4 -- curl -k --cacert /var/run/secrets/kubernetes.io/serviceaccount/ca.crt -H  "Authorization: Bearer $TOKEN_VALUE" https://kubenetes/api/v1/namespaces?resourceVersion=0
kubernetes API 详细文档: https://kubernetes.io/docs/reference/


4. 其他

在集群内部访问kubernetes API,一般使用下面两个地址:

  1. https://kubenetes/
  2. https://10.254.0.1/
如果你配置不一样,你可以使用以下方法确认地址:
mac-temp:curl test$ kubectl get svc |grep kubernetes
kubernetes      ClusterIP   10.254.0.1              443/TCP       184d

5.如果你发现pod有如下访问kubernetes api错误认知,你可以使用以上方法检查:

E0911 05:40:55.639605       1 reflector.go:199] k8s.io/dns/vendor/k8s.io/client-go/tools/cache/reflector.go:94: Failed to list *v1.Endpoints: Get https://10.254.0.1/api/v1/endpoints?resourceVersion=0: x509: failed to load system roots and no roots provided



你可能感兴趣的:(kubernetes)