Kubernetes grant user/service account privilege to use 'kubectl cp' command

6/16/2020

I have a pod which have a java app inside, the java app will watch a directory, and auotmaticly found and load plugin bundle. These bundles are seprate java projects with CI/CD pipelines, now I want to use kubectl cp command in my CI/CD scripts to deploy these bundle files, however, I just want to give minimal privileges to CI/CD user, Is that possible using kubernetes's RBAC API?

-- WestFarmer
kubernetes

2 Answers

6/16/2020

The minimal RBAC Role for kubectl cp looks like this:

kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  namespace: default
  name: copy-to-pod
rules:
- apiGroups: [""]
  resources: ["pods", "pods/exec"]
  verbs: ["get", "create"]
-- Fritz Duchardt
Source: StackOverflow

6/16/2020

kubectl cp internally uses kubectl exec. So the RBAC needs to be on the exec subresource of pod.

kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  namespace: default
  name: pod-copy
rules:
- apiGroups: [""]
  resources: ["pods/exec"]
  verbs: ["create"]

Then you can create RoleBinding to assign this role to the service account

apiVersion: rbac.authorization.k8s.io/v1
# This role binding allows "jane" to read pods in the "default" namespace.
# You need to already have a Role named "pod-reader" in that namespace.
kind: RoleBinding
metadata:
  name: pod-copy-rolebinding
  namespace: default
subjects:
# You can specify more than one "subject"
- kind: ServiceAccount
  name: default # "name" is case sensitive
  namespace: default #namespace where service account is created
roleRef:
  # "roleRef" specifies the binding to a Role / ClusterRole
  kind: Role #this must be Role or ClusterRole
  name: pod-copy # this must match the name of the Role or ClusterRole you wish to bind to
  apiGroup: rbac.authorization.k8s.io

This will give the service account default in default namespace to exec into pods in default namespace.

The same RoleBinding can applied to a user as well by mentioning it the subjects

apiVersion: rbac.authorization.k8s.io/v1
# This role binding allows "jane" to read pods in the "default" namespace.
# You need to already have a Role named "pod-reader" in that namespace.
kind: RoleBinding
metadata:
  name: pod-copy-rolebinding
  namespace: default
subjects:
# You can specify more than one "subject"
- kind: User
  name: Jane # "name" is case sensitive
  apiGroup: rbac.authorization.k8s.io
roleRef:
  # "roleRef" specifies the binding to a Role / ClusterRole
  kind: Role #this must be Role or ClusterRole
  name: pod-copy # this must match the name of the Role or ClusterRole you wish to bind to
  apiGroup: rbac.authorization.k8s.io
-- Arghya Sadhu
Source: StackOverflow