环境变量
变量名称 |
变量值 |
说明 |
SERVICE_ACCOUNT_NAME |
nocalhost |
Account名称 |
NOCALHOST_SECRET |
nocalhost-secret |
Secret名称 |
export SERVICE_ACCOUNT_NAME="nocalhost"
export NOCALHOST_SECRET="nocalhost-secret"
1. 创建具有 cluster-admin
权限的 ServiceAccount
文件名: nocalhost-service-account.yaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| kubectl apply -f - <<EOF # 创建一个ServiceAccount apiVersion: v1 kind: ServiceAccount metadata: name: ${SERVICE_ACCOUNT_NAME} namespace: default # 根据需要更改命名空间 ---
# 创建具有 cluster-admin 权限的 ClusterRoleBinding apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: nocalhost-cluster-admin namespace: default # 与 Service Account 相同的命名空间 subjects: - kind: ServiceAccount name: ${SERVICE_ACCOUNT_NAME} namespace: default roleRef: kind: ClusterRole name: cluster-admin apiGroup: rbac.authorization.k8s.io EOF
|
2. 创建类型 kubernetes.io/service-account-token
的Secret
1 2 3 4 5 6 7 8 9
| kubectl apply -f - <<EOF apiVersion: v1 kind: Secret type: kubernetes.io/service-account-token metadata: name: ${NOCALHOST_SECRET} annotations: kubernetes.io/service-account.name: ${SERVICE_ACCOUNT_NAME} EOF
|
3. 创建.kubeconfig
获取 ServiceAccount Token到变量 SERVICE_ACCOUNT_TOKEN
1
| export SERVICE_ACCOUNT_TOKEN=$(kubectl get secret ${NOCALHOST_SECRET} -o jsonpath="{.data.token}" | base64 -d)
|
获取 ServiceAccount CaCert到变量 SERVICE_ACCOUNT_CACERT
1
| export SERVICE_ACCOUNT_CACERT=$(kubectl get secret ${NOCALHOST_SECRET} -o jsonpath="{.data.ca\.crt}")
|
获取集群的API Server地址到变量 API_SERVER
1
| export API_SERVER=$(kubectl config view --minify -o jsonpath="{.clusters[0].cluster.server}")
|
打印变量值,查看是否正确
1 2 3
| echo "SERVICE_ACCOUNT_TOKEN: ${SERVICE_ACCOUNT_TOKEN}" echo "SERVICE_ACCOUNT_CACERT: ${SERVICE_ACCOUNT_CACERT}" echo "API_SERVER: ${API_SERVER}"
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| cat <<EOF > ~/.kube/config-nocalhost apiVersion: v1 kind: Config clusters: - cluster: server: ${API_SERVER} certificate-authority-data: ${SERVICE_ACCOUNT_CACERT} name: nocalhost-cluster contexts: - context: cluster: nocalhost-cluster user: nocalhost-user name: nocalhost-context current-context: nocalhost-context users: - name: nocalhost-user user: token: ${SERVICE_ACCOUNT_TOKEN} EOF
|
把~/.kube/config-nocalhost导入到nocalhost即可