kubernetesminikubek8s-serviceaccount

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

we have a default namespace in which the nginx service account does not have the rights to launch the nginx container

when creating a pod, use the command

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

as a result, we get an error

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

as I understand it, it is necessary to write a psp policy that will allow the nginx-sa service account to run under, but I do not understand how to write it correctly for a specific service account

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

Solution

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

    After you get your special psp ready for your nginx, you can grant your nginx-sa to use the special psp like this:

    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