使用 Kubernetes 的基于角色的访问控制 (RBAC) 系统,创建一个只能访问特定命名空间的服务帐户。
kubeconfig中主要由如下部分组成:
apiVersion: v1
kind: Config
preferences: {}
clusters:
- cluster:
certificate-authority-data:
server: https://127.0.0.1:6443
name: kubernetes
users:
- name: kubernetes-admin
user:
client-certificate-data:
client-key-data:
contexts:
- context:
cluster: kubernetes
user: kubernetes-admin
name: kubernetes-admin@kubernetes
current-context: kubernetes-admin@kubernetes
apiVersion: v1
kind: Config
preferences: {}
clusters:
- cluster:
certificate-authority-data:
server: https://127.0.0.1:6443
name: kubernetes
users:
- name: kubernetes-admin
user:
as-user-extra: {}
client-key-data:
token:
contexts:
- context:
cluster: kubernetes
user: kubernetes-admin
name: kubernetes-admin@kubernetes
current-context: kubernetes-admin@kubernetes
namespace full access
apiVersion: v1
kind: ServiceAccount
metadata:
name: ${user}
namespace: ${namespace}
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: ${namespace}-${user}-full-access
namespace: ${namespace}
rules:
- verbs:
- '*'
apiGroups:
- '*'
resources:
- '*'
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: ${namespace}-${user}
namespace: ${namespace}
subjects:
- kind: ServiceAccount
name: {user}
namespace: ${namespace}
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: ${namespace}-${user}-full-access
#获取secret name
kubectl get secret -n ${namespace}
NAME TYPE DATA AGE
${namespace}-${user}-token-tncrk kubernetes.io/service-account-token 3 16m
#获取token
kubectl get secret -n ${namespace} ${namespace}-${user}-token-tncrk -o "jsonpath={.data.token}" |base64 -D
eyJhbGciOiJSUzI1NiIsImtpZCI6Ik1fVDJTS1NhM0V1enlHTGFuN3BfNGZmOVM2bm9RTmdLZjlqWlpnbzA3ZEEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOi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Q1MwcTZVOGRoZ1pVYkpTVmhWMHBCYVFDRmpLTS9jamFpCm96ajcvc2tUYjVhaDVqQVFqbFZBQi83cjlWVHk1U253eUg0QQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg==%
apiVersion: v1
kind: Config
preferences: {}
clusters:
- cluster:
certificate-authority-data: ${ca}
server: https://127.0.0.1:6443
name: ${clusterName}
users:
- name: ${userName}
user:
as-user-extra: {}
client-key-data: ${ca}
token: ${token}
contexts:
- context:
cluster: ${clusterName}
namespace: ${namespace}
user: ${userName}
name: ${userName}@${clusterName}
current-context: ${userName}@${clusterName}
${userName}不可以相同,否则出现"error: You must be logged in to the server (Unauthorized)"
KUBECONFIG=${config1-path}:${config2-path} kubectl config view --flatten > $HOME/.kube/config