设置 Kubernetes Cronjob:无法在命名空间 "staging" 中的 API 组 "autoscaling" 中获取资源 "horizontalpodautoscalers"

Setting up a Kubernetes Cronjob: Cannot get resource "horizontalpodautoscalers" in API group "autoscaling" in the namespace "staging"

我尝试设置一个 cron 作业来修补水平 pod 自动缩放器,但是作业 returns horizontalpodautoscalers.autoscaling "my-web-service" is forbidden: User "system:serviceaccount:staging:sa-cron-runner" cannot get resource "horizontalpodautoscalers" in API group "autoscaling" in the namespace "staging"

我试过如下设置所有角色权限:

kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  namespace: staging
  name: cron-runner
rules:
- apiGroups: ["autoscaling"]
  resources: ["horizontalpodautoscalers"]
  verbs: ["patch"]

---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: cron-runner
  namespace: staging
subjects:
- kind: ServiceAccount
  name: sa-cron-runner
  namespace: staging
roleRef:
  kind: Role
  name: cron-runner
  apiGroup: rbac.authorization.k8s.io

---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: sa-cron-runner
  namespace: staging
---

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: scale-up-job
  namespace: staging
spec:
  schedule: "16 20 * * 1-6"
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: sa-cron-runner
          containers:
          - name: scale-up-job
            image: bitnami/kubectl:latest
            command:
            - /bin/sh
            - -c
            - kubectl patch hpa my-web-service --patch '{\"spec\":{\"minReplicas\":6}}'
          restartPolicy: OnFailure

kubectl auth can-i patch horizontalpodautoscalers -n staging --as sa-cron-runner 也returnsno,所以权限设置不正确

我该如何调试它?我看不出这是怎么设置不正确的

我认为问题是cronjob需要先获取资源然后Patch一样。因此,您需要在 Role 规范中明确指定 get 的权限。

该错误还提到了获取资源的身份验证问题:

horizontalpodautoscalers.autoscaling "my-web-service" is forbidden: User "system:serviceaccount:staging:sa-cron-runner" cannot get resource "horizontalpodautoscalers" in API group "autoscaling" in the namespace "staging"

尝试将 Roleverbs 部分修改为:

verbs: ["patch", "get"]

您还可以包括 listwatch,具体取决于 cronjob 中 运行 脚本中的要求。