一. 访问控制
二.UserAccount与serviceaccount区别 将认证信息添加到serviceAccount中,要比直接在Pod指定imagePullSecrets要安全很多
1. 首先命令创建sa
2 把serviceaccount和pod绑定起来 vim pod3.yaml
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
serviceAccountName: admin #指定的sa创建的admin用户
containers:
- name: game2048
image: reg.westos.org/westos/game2048
3. 添加secrets到serviceaccount中
kubectl patch serviceaccount admin -p '{"imagePullSecrets": [{"name": "myregistrykey"}]}'
#此时镜像拉取策略
这里的私有仓库未公开仍然可以拉取
三.UserAccount认证
cd /etc/kubernetes/pki/ #默认证书生成位置
openssl genrsa -out test.key 2048 #生成自签名证书
openssl req -new -key test.key -out test.csr -subj "/CN=test" #通过csr拿到test.key
openssl x509 -req -in test.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out test.crt -days 365
kubectl config set-credentials test --client-certificate=/etc/kubernetes/pki/test.crt --client-key=/etc/kubernetes/pki/test.key --embed-certs=true #创建安全上下文(test用户)
kubectl config set-context test@kubernetes --cluster=kubernetes --user=test#创建对应的上下文切换
kubectl config use-context test@kubernetes #切换用户为testkubectl config use-context kubernetes-admin@kubernetes #切换用户为admin切换用户后执行命令报错因没有权限
开始设置权限测试 vim roles.yaml
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
namespace: default #在这里创建的
name: myrole #创建的角色
rules:
- apiGroups: [""]
resources: ["pods"] #针对pod设置的以下权限
verbs: ["get", "watch", "list", "create", "update", "patch", "delete"]---
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
设置权限测试 (2)
此时在文件中添加权限模块解决这个问题
记得切回admin用户 在上面文件中添加模块即可 vim roles.yaml
---
kind: ClusterRole #全局资源
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: myclusterrole
rules:
- apiGroups: [""]
resources: ["pods"] #针对的资源pod下命令
verbs: ["get", "watch", "list", "delete", "create", "update"]
- apiGroups: ["extensions", "apps"]
resources: ["deployments"] #和资源deployment下面的命令
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding #RoleBinding必须指定namespace
metadata:
name: rolebind-myclusterrole
namespace: default #指定的namespace
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: myclusterrole
subjects:
- apiGroup: rbac.authorization.k8s.io
kind: User
name: test
设置权限测试 (3)
此时在文件中添加权限模块解决这个问题
记得切回admin用户 在上面文件中添加模块即可 vim roles.yaml
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding #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回收实验: kubectl delete -f roles.yaml
kubectl config delete-user test
kubectl config delete-context test@kubernetes
四. 服务账户的自动化