K8S 创建 user account 步骤

mkdir -p /data/useraccount/hdyl/ && cd /data/useraccount/hdyl/

# 创建 user 私钥
openssl genrsa -out hdyl.key 2048

# 创建签署请求
# 注意:O=组织信息,CN=用户名
openssl req -new -key hdyl.key -out hdyl.csr -subj "/CN=hdyl/O=huidiancloud"

# 使用 k8s 的 ca 签署证书
openssl x509 -req -in hdyl.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out hdyl.crt -days 3650


# 创建集群配置
kubectl config set-cluster k8s-hdyl \
--server=https://bigdata.inter.huidiancloud.com:6443 \
--certificate-authority=/etc/kubernetes/pki/ca.crt \
--embed-certs=true \
--kubeconfig=/data/useraccount/hdyl/k8s-hdyl.conf

kubectl config view --kubeconfig=/data/useraccount/hdyl/k8s-hdyl.conf

# 创建用户配置
kubectl config set-credentials hdyl \
--client-certificate=hdyl.crt \
--client-key=hdyl.key \
--embed-certs=true \
--kubeconfig=/data/useraccount/hdyl/k8s-hdyl.conf

# 创建context配置
kubectl config set-context hdyl@k8s-hdyl \
--cluster=k8s-hdyl \
--user=hdyl \
--kubeconfig=/data/useraccount/hdyl/k8s-hdyl.conf


# 设置context配置
kubectl config use-context hdyl@k8s-hdyl \
--kubeconfig=/data/useraccount/hdyl/k8s-hdyl.conf

创建对应的权限

cd /data/useraccount/hdyl/ 

# 让 hdyl 用户在 basic-service 命名空间有所有的权限

cat >> hdyl-2-basic-service-role.yaml << EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: hdyl
  namespace: basic-service
rules:
  - apiGroups: ['*']
    resources: ['*']
    verbs: ['*']
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: hdyl
  namespace: basic-service
subjects:
  - kind: User
    name: hdyl
    apiGroup: ""
roleRef: 
  kind: Role
  name: hdyl
  apiGroup: rbac.authorization.k8s.io
EOF

kubectl apply -f hdyl-2-basic-service-role.yaml

# user account 可以绑定多个 role 

# ClusterRole 和 ClusterRoleBinding 的例子
cat >> cluster-reader.yaml << EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: namespaces-reader
rules:
- apiGroups: [""]
  resources: ["namespaces", "resourcequotas"]
  verbs: ["get", "list", "watch", "create"]
- apiGroups: ["batch"]
  resources: ["jobs"]
  verbs: ["watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: hdyl-namespaces-reader
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: namespaces-reader
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: hdyl
EOF

测试

# 创建系统用户
useradd hdyl
mkdir -p /home/hdyl/.kube
cp /data/useraccount/hdyl/k8s-hdyl.conf /home/hdyl/.kube/config
chown hdyl.hdyl -R /home/hdyl/
su - hdyl

kubectl get pod
Error from server (Forbidden): pods is forbidden: User "hdyl" cannot list resource "pods" in API group "" in the namespace "default"

kubectl -n basic-service get pod 
posted @ 2023-07-14 17:16  klvchen  阅读(55)  评论(0)    收藏  举报