Kubernetes 修补多个资源不起作用

Kubernetes patch multiple resources not working

我正在尝试使用如下所示的 patch 将相同的作业历史记录限制应用于多个 CronJob,命名为 kubeJobHistoryLimit.yml:

apiVersion: batch/v1beta1
kind: CronJob
spec:
  successfulJobsHistoryLimit: 1
  failedJobsHistoryLimit: 1

我的 kustomization.yml 看起来像:

bases:
  - ../base
configMapGenerator:
- name: inductions-config
  env: config.properties
patches:
  - path: kubeJobHistoryLimit.yml
    target:
      kind: CronJob
patchesStrategicMerge:
  - job_specific_patch_1.yml
  - job_specific_patch_2.yml
  ...
resources:
  - secrets-uat.yml

在我的 CI 管道中的某个时刻,我有:

kubectl --kubeconfig $kubeconfig apply --force -k ./

kubectl 版本是 1.21.9

问题是作业历史限制值似乎没有被提取。我使用的 K8s 配置或版本有问题吗?

对于 kustomize 4.5.2,您编写的补丁不适用;它失败了:

Error: trouble configuring builtin PatchTransformer with config: `
path: kubeJobHistoryLimit.yml
target:
  kind: CronJob
`: unable to parse SM or JSON patch from [apiVersion: batch/v1
kind: CronJob
spec:
  successfulJobsHistoryLimit: 1
  failedJobsHistoryLimit: 1
]

这是因为它缺少 metadata.name,这是必需的,即使在修补多个对象时它被忽略了。如果我将补丁修改为如下所示:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: ignored
spec:
  successfulJobsHistoryLimit: 1
  failedJobsHistoryLimit: 1

似乎有效。

如果我 base/cronjob1.yaml 看起来像:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: cronjob1
spec:
  failedJobsHistoryLimit: 2
  successfulJobsHistoryLimit: 5
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - command:
            - sleep
            - 60
            image: docker.io/alpine:latest
            name: example
  schedule: 30 3 * * *

然后使用上面的补丁和这样的 overlay/kustomization.yaml

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../base
patches:
- path: kubeJobHistoryLimit.yml
  target:
    kind: CronJob

我从 kustomize build overlay 看到以下输出:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: cronjob2
spec:
  failedJobsHistoryLimit: 1
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - command:
            - sleep
            - 60
            image: docker.io/alpine:latest
            name: example
  schedule: 30 3 * * *
  successfulJobsHistoryLimit: 1

可以看到这两个属性已经正确更新了。