kubernetes鉴权

kubernetes鉴权

实现,创建一个devuser 用户,创建一个dev命名空间。给devuser分配dev命名空间操作权限

创建用户

useradd devuser
passwd devuser

下载证书工具

mkdir tools&&cd tools
wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64
wget https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64
wget https://pkg.cfssl.org/R1.2/cfssl-certinfo_linux-amd64
mv cfssl-certinfo_linux-amd64 cfssl-certinfo
mv cfssljson_linux-amd64 cfssljson
mv cfssl_linux-amd64 cfssl
mv * /usr/local/bin/
cd /usr/local/bin/
chmod a+x *

创建证书

cd /etc/kubernetes/pki/
cfssl gencert -ca=ca.crt -ca-key=ca.key -profile=kubernetes /root/install-k8s/cert/devuser/devuser-csr.json | cfssljson -bare devuser

会产生三个文件:

[root@k8s-master01 pki]# ls devuser*
devuser.csr  devuser-key.pem  devuser.pem

设置集群参数

cd /root/install-k8s/cert/devuser/
export KUBE_APISERVER="https://192.168.183.10:6443"
kubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/pki/ca.crt \
--embed-certs=true \
--server=${KUBE_APISERVER} \
--kubeconfig=devuser.kubeconfig

此时得到一个devuser.kubeconfig文件

设置客户端认证参数

kubectl config set-credentials devuser \
--client-certificate=/etc/kubernetes/pki/devuser.pem \
--client-key=/etc/kubernetes/pki/devuser-key.pem \
--embed-certs=true \
--kubeconfig=devuser.kubeconfig

cat devuser.kubeconfig,会看的users中设置了devuser的信息

创建命名空间

kubectl create namespace dev

设置上下文参数

kubectl config set-context kubernetes \
--cluster=kubernetes \
--user=devuser \
--namespace=dev \
--kubeconfig=devuser.kubeconfig

cat devuser.kubeconfig,会看的contexts中设置了namespace的信息

rolebinding

kubectl create rolebinding devuser-admin-binding --clusterrole=admin --user=devuser --namespace=dev

配置devuser .kube

mkdir /home/devuser/.kube/
cp devuser.kubeconfig /home/devuser/.kube/
mv /home/devuser/.kube/devuser.kubeconfig /home/devuser/.kube/config
chown devuser:devuser -R /home/devuser/.kube

切换上下文

使用devuser登录master01,切换上下文

cd ~/.kube/
kubectl config use-context kubernetes --kubeconfig=config 

创建pod,查看pod

[devuser@k8s-master01 .kube]$ kubectl run mynginx --image=hub.hdj.com/library/nginx:v1  #使用devuser,在dev命名空间中创建一个pod
kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
deployment.apps/mynginx created
[devuser@k8s-master01 .kube]$ kubectl get pod #查看pod
NAME                       READY   STATUS    RESTARTS   AGE
mynginx-57fbf8768f-s2knd   1/1     Running   0          8s

切换root,查看dev命名空间的pod,可以看到dev命名空间中的mynginx-57fbf8768f-s2knd这个pod。

[root@k8s-master01 devuser]# kubectl get pod -n dev
NAME                       READY   STATUS    RESTARTS   AGE
mynginx-57fbf8768f-s2knd   1/1     Running   0          25s

你可能感兴趣的:(kubernetes)