企业级运维---k8s---访问控制

文章目录

  • 一、创建UserAccount
  • 二、Role 和 ClusterRole

一、创建UserAccount

cd /etc/kubernetes/pki/
openssl genrsa -out test.key 2048
openssl req -new -key test.key -out test.csr -subj "/CN=test"
openssl  x509 -req -in test.csr -CA ca.crt -CAkey ca.key  -CAcreateserial -out test.crt -days 365
openssl x509 -in test.crt -text -noout

企业级运维---k8s---访问控制_第1张图片
企业级运维---k8s---访问控制_第2张图片

kubectl config set-credentials test --client-certificate=/etc/kubernetes/pki/test.crt --client-key=/etc/kubernetes/pki/test.key --embed-certs=true	
kubectl  config view
kubectl config set-context test@kubernetes --cluster=kubernetes --user=test
kubectl config use-context test@kubernetes
kubectl  get pod
Error from server (Forbidden): pods is forbidden: User "test" cannot list resource "pods" in API group "" in the namespace "default"	#没权限操作

企业级运维---k8s---访问控制_第3张图片
企业级运维---k8s---访问控制_第4张图片

二、Role 和 ClusterRole

企业级运维---k8s---访问控制_第5张图片
企业级运维---k8s---访问控制_第6张图片
role示例

mkdir roles
cd roles/

编写文件

vim role.yaml
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  namespace: default
  name: myrole
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "watch", "list", "create", "update", "patch", "delete"]

然后开始授权

企业级运维---k8s---访问控制_第7张图片

vim rolebinding.yaml
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: test-read-pods
  namespace: default
subjects:
- kind: User
  name: test
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: myrole
  apiGroup: rbac.authorization.k8s.io

然后就能访问get pod

企业级运维---k8s---访问控制_第8张图片
ClusterRole示例:

kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: myclusterrole
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "watch", "list", "delete", "create", "update"]
- apiGroups: ["extensions", "apps"]
  resources: ["deployments"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]

然后应用

在这里插入图片描述
使用rolebinding绑定clusterRole:

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: rolebind-myclusterrole
  namespace:  default
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: myclusterrole
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: test

在rolebinding.yaml文件里面
添加这些代码

创建clusterrolebinding:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: clusterrolebinding-myclusterrole
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: myclusterrole
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: test

然后就可以查看其他的namespace的服务

在这里插入图片描述

你可能感兴趣的:(运维,kubernetes,linux)