curl 命令远程连接 kubernetes 集群

尝试通过远程的一台电脑用 curl 命令连接 k8s 集群,实地体验 k8s 的安全机制。

直接 curl 命令连接 control plane

curl https://k8s-api:6443 

报错

curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: https://curl.haxx.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

这是由于缺少 ca 证书,在集群 master 服务器通过下面的命令拿到 ca 证书

kubectl get secret \
    $(kubectl get secrets | grep default-token | awk '{print $1}') \
    -o jsonpath="{['data']['ca\.crt']}" | base64 --decode

curl 命令加上 ca 证书进行连接

 curl --cacert ca.crt  https://k8s-api:6443

服务器响应403

{
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {},
  "status": "Failure",
  "message": "forbidden: User \"system:anonymous\" cannot get path \"/\"",
  "reason": "Forbidden",
  "details": {},
  "code": 403
}

这是由于缺少与 ServiceAccount 对应的 access token ,创建一个 ServiceAccount

kubectl create serviceaccount curl-user -n kube-system

将该账号加入到 cluster-admin 角色

kubectl create clusterrolebinding curl-user-binding --clusterrole=cluster-admin --serviceaccount=kube-system:curl-user -n kube-system

拿到该账号对应的 access token

kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep curl-user | awk '{print $1}')

curl 命令带上 access token 连接集群

curl --cacert ca.crt -H "Authorization: Bearer $TOKEN"  https://k8s-api:6443

连接成功

{
  "paths": [
    "/.well-known/openid-configuration",
    "/api",
    "/api/v1",
    "/apis",
    "/apis/",
    ...
  ]
}
小结

连接集群三要素:
1)control plane 地址(api server 地址)
2)集群 ca 证书
3)ServiceAccount token(访问 api server 的 access token)

posted @ 2021-03-05 11:58  dudu  阅读(146)  评论(0编辑  收藏  举报