如何从POD A到另一个POD B执行Shell脚本

时间:2020-11-07 08:21:10

标签: kubernetes kubernetes-pod kubernetes-rbac

我有两个在kubernetes集群中运行的Pod。豆荚如下

  1. mongodb容器,类型为:StatefulSet
  2. 一种脚本吊舱:Job

我正在script pod上运行要在mongodb pod上执行的bash脚本。

bash脚本包含以下代码,这些代码将执行到mongodb pod并执行以下命令。

kubectl exec mongo-0 -c mongo -- mongo --eval 'rs.initiate({_id: "rs0", version: 1, members: [ {_id: 0, host: "mongo-0.mongo.default.svc.cluster.local:27017"}, {_id: 1, host: "mongo-1.mongo.default.svc.cluster.local:27017"}, {_id: 2, host: "mongo-2.mongo.default.svc.cluster.local:27017"} ]});'

但是当我运行script pod时,出现以下错误

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"

我该怎么做才能为script pod提供在mongodb pod中运行上述命令的权限?


所以就像您说的,我创建了另一个pod:job,其中包含script.sh。

在script.sh文件中,我在主pod上运行“ kubectl exec”以运行一些命令

脚本已执行,但是出现错误“无法在API组中创建资源“ pods / exec””

因此,我使用以下资源创建了一个clusterrole:[“ pods / exec”],并使用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"

1 个答案:

答案 0 :(得分:1)

如果需要定期运行以进行维护,请查看Kubernetes守护程序设置对象。