创建Kubernetes的管理帐号
有时需要为某个namespace创建管理员帐号,下面是创建步骤。k8s里面创建资源时需要指定yaml文件,操作起来比较繁琐,这篇文章里面利用shell的特性可以不用每次都创建一个文件
步骤#
创建ServiceAccount#
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: ServiceAccount
metadata:
name: demo-user
namespace: demo
EOF
创建一个Role#
cat <<EOF | kubectl apply -f -
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: admin
namespace: demo
rules:
- apiGroups: ["", "extensions", "apps"]
resources: ["*"]
verbs: ["*"]
- apiGroups: ["batch"]
resources:
- jobs
- cronjobs
verbs: ["*"]
EOF
将创建的ServiceAccount绑定到角色#
cat <<EOF | kubectl apply -f -
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: admin-view
namespace: demo
subjects:
- kind: ServiceAccount
name: demo-user
namespace: demo
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: admin
EOF
获取用户的Token#
export NAMESPACE="demo"
export K8S_USER="demo-user"
kubectl -n ${NAMESPACE} describe secret $(kubectl -n ${NAMESPACE} get secret | (grep ${K8S_USER} || echo "$_") | awk '{print $1}') | grep token: | awk '{print $2}'\n
参考资料#
https://computingforgeeks.com/restrict-kubernetes-service-account-users-to-a-namespace-with-rbac/