方法为:
- 创建一个ServiceAccount
- 给ServiceAccount赋权限为admin(也可以根据实际情况自定义权限)
- 使用token就可以访问整个k8s api server的所有资源了
# 1. 定义一个ServiceAccount
apiVersion: v1
kind: ServiceAccount
metadata:
name: demo-sa
namespace: demo-ns
---
# 2. 将ServiceAccount绑定为ROLE admin
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: demo-sa
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin
subjects:
- kind: ServiceAccount
name: demo-sa
namespace: demo-ns
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: demo-app
namespace: demo-ns
labels:
app: demo-app
spec:
replicas: 1
selector:
matchLabels:
app: demo-app
template:
metadata:
labels:
app: demo-app
spec:
containers:
- name: demo-app
image: registry.my:15000/demo/demo-app:1.0.0
imagePullPolicy: Always
# 使用ServiceAccount给POD授权
serviceAccount: demo-sa
serviceAccountName: demo-sa
restartPolicy: Always
在POD中使用ServiceAccount,demo-sa会被挂载到路径 /var/run/secrets/kubernetes.io/serviceaccount/token
中。
$ TOKEN=`cat /var/run/secrets/kubernetes.io/serviceaccount/token`
$ APISERVER="https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_SERVICE_PORT_HTTPS"
$ curl --header "Authorization: Bearer $TOKEN" -k -s $APISERVER/apis/batch/v1/jobs
{
...略去...
}
常见的URL包括两大类/api和/apis
其中,/api对应的是core资源,例如:namespace、pod;/apis对应的非核心资源,例如:deployment、statefulset
小技巧:可以使用kubectl explain
命令来查询
通过命令kubectl explain
查询到的内容,根据VERSION可以看出使用/api访问还是通过/apis访问。
例如:
$ kubectl explain pod
KIND: Pod
VERSION: v1
DESCRIPTION:
Pod is a collection of containers that can run on a host. This resource is
created by clients and scheduled onto hosts.
... 略去 ...
VRESION: v1,则通过/api访问
api/v1/pods
如果是其他VERSION,则通过VERSION中提供的group和版本号进行访问
例如:
$ kubectl explain job
KIND: Job
VERSION: batch/v1
DESCRIPTION:
Job represents the configuration of a single job.
...略去...
则通过/apis访问
apis/batch/v1/jobs
CRD对象也适用于以上的规则,例如:
$ kubectl explain Kibana
KIND: Kibana
VERSION: kibana.k8s.elastic.co/v1
DESCRIPTION:
Kibana represents a Kibana resource in a Kubernetes cluster.
...略去...
可以通过/apis/kibana.k8s.elastic.co/v1/kibanas
进行访问,例如:
$ curl --header "Authorization: Bearer $TOKEN" -k -s $APISERVER/apis/kibana.k8s.elastic.co/v1/kibanas
{
"apiVersion": "kibana.k8s.elastic.co/v1",
"items": [
{
"apiVersion": "kibana.k8s.elastic.co/v1",
"kind": "Kibana",
"metadata": {
"...略去...": ""
},
"...略去...": ""
}
],
"kind": "KibanaList",
"metadata": {
"continue": "",
"resourceVersion": "185223937"
}
}