Copy sudo -s
mkdir -p ~/k8s-user-certs
cd ~/k8s-user-certs
cert_user = wenlg
cert_group = deployer
openssl genrsa -out ${cert_user} .key 2048
openssl req -new -key ${cert_user} .key -out ${cert_user} .csr -subj "/CN=${cert_user}/O=${cert_group}"
openssl x509 -req -in ${cert_user} .csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out ${cert_user} .crt -days 365
Copy cert_user = wenlg
cert_namespace = office
kubectl config set-credentials ${cert_user} --client-certificate=$( realpath ~/.certs/${cert_user}.crt) --client-key=$( realpath ~/.certs/${cert_user}.key) --embed-certs=true
kubectl config set-context ${cert_user} @kubernetes --cluster=kubernetes --user=${cert_user} --namespace=${cert_namespace}
Copy kubectl --context=${cert_user}@kubernetes get pods
Copy kubectl create namespace ${cert_namespace}
cat << EOS|kubectl apply -f -
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
namespace: ${cert_namespace}
name: deployment-manager
rules:
- apiGroups: ["", "extensions", "apps"]
resources: ["deployments", "replicasets", "pods"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
EOS
Copy cat << EOS|kubectl apply -f -
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: deployment-manager-binding
namespace: ${cert_namespace}
subjects:
- kind: User
name: ${cert_user}
apiGroup: ""
roleRef:
kind: Role
name: deployment-manager
apiGroup: ""
EOS
Copy # 部署一个镜像
kubectl --context=${cert_user}@kubernetes run --image citizenstig/httpbin httpbin
# 显示部署和pod列表
kubectl --context=${cert_user}@kubernetes get deploy,po
Copy ➜ ~ kubectl --context=${cert_user}@kubernetes get deploy,po
NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE
deploy/httpbin 1 1 1 1 47s
NAME READY STATUS RESTARTS AGE
po/httpbin-5c5449d8b8-qr2dz 1/1 Running 0 47s
Copy kubectl --context=${cert_user}@kubernetes get po --namespace=default
Copy ➜ ~ kubectl --context=${cert_user}@kubernetes get po --namespace=default
Error from server (Forbidden): pods is forbidden: User "wenlg" cannot list pods in the namespace "default"