如何在 k8s 中只为特定用户编写 psp?

How to write a psp in k8s only for a specific user?

minikube start
--extra-config=apiserver.enable-admission-plugins=PodSecurityPolicy
--addons=pod-security-policy

我们有一个默认命名空间,其中 nginx 服务帐户无权启动 nginx 容器

创建pod时,使用命令

kubectl run nginx --image=nginx -n default --as system:serviceaccount:default:nginx-sa

因此,我们得到一个错误

 Error: container has runAsNonRoot and image will run as root (pod: "nginx_default(49e939b0-d238-4e04-a122-43f4cfabea22)", container: nginx)

按我的理解,有必要写一个psp策略,让nginx-sa服务账号在运行下,但我不明白如何正确地为特定的服务账号写

apiVersion: v1
kind: ServiceAccount
metadata:
  name: nginx-sa
  namespace: default

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

---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: nginx-sa-role-binding
  namespace: default
subjects:
  - kind: ServiceAccount
    name: nginx-sa
    namespace: default
roleRef:
  kind: Role
  name: nginx-sa-role
  apiGroup: rbac.authorization.k8s.io

...but I do not understand how to write it correctly for a specific service account

在为您的 nginx 准备好您的专用 psp 后,您可以授予您的 nginx-sa 使用专用 psp,如下所示:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: role-to-use-special-psp
rules:
- apiGroups:
  - policy
  resourceNames:
  - special-psp-for-nginx
  resources:
  - podsecuritypolicies
  verbs:
  - use
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: bind-to-role
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: role-to-use-special-psp
subjects:
- kind: ServiceAccount
  name: nginx-sa
  namespace: default