2

So like you said I created a another pod which is of kind:job and included the script.sh.

In the script.sh file, I run "kubectl exec" to the main pod to run few commands

The script gets executed, but I get the error "cannot create resource "pods/exec in API group"

So I created a clusterrole with resources: ["pods/exec"] and bind it to the default service account using ClusterRoleBinding

kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: pod-reader
rules:
- apiGroups: [""]
  resources: ["pods", "pods/log"]
  verbs: ["get", "list"]
- apiGroups: [""]
  resources: ["pods/exec"]
  verbs: ["create"]

--- 

kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: service-account-role-binding
  namespace: default
subjects:
  - kind: ServiceAccount
    name: default
    namespace: default
roleRef:
  kind: ClusterRole
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io

---

apiVersion: v1
kind: ServiceAccount
metadata:
  name: default
  namespace: default


In the pod which is of kind:job, I include the service account like shown below

restartPolicy: Never
serviceAccountName: default

but I still get the same error. What am I doing wrong here ?

Error from server (Forbidden): pods "mongo-0" is forbidden: User "system:serviceaccount:default:default" cannot create resource "pods/exec" in API group "" in the namespace "default"
Mohammed Noureldin
  • 14,913
  • 17
  • 70
  • 99
jeril
  • 1,109
  • 2
  • 17
  • 35
  • Does this answer your question? [how to control access for pods/exec only in kubernetes rbac without pods create binded?](https://stackoverflow.com/questions/47468369/how-to-control-access-for-pods-exec-only-in-kubernetes-rbac-without-pods-create) – Emile Pels Nov 07 '20 at 09:01
  • added cluster role and bindings as you have said. I have edited the question above but I get the same error. – jeril Nov 07 '20 at 12:15
  • 2
    You shouldn't use `kubectl exec` or similar commands to connect to a database or other routine tasks; reserve those for humans to debug. Use a normal MongoDB client library (which may require a more powerful language than a shell script, or installing the `mongo` client in the Job's image). – David Maze Nov 07 '20 at 12:26
  • this post helped me https://stackoverflow.com/questions/54196533/how-to-execute-command-from-one-pod-inside-another-pod-using-kubectl-exec-which @DavidMaze - OK Will try reconsidering my approach.. – jeril Nov 07 '20 at 18:27

1 Answers1

1

If this is something that needs to be regularly run for maintenance look into Kubernetes daemon set object.

John Peterson
  • 354
  • 1
  • 4