pods 列表中的 k8s CronJob 循环

k8s CronJob loop on list of pods

我想 运行 在特定命名空间中的 pods 上循环,但是技巧是在 cronJob 中执行,是否可以内联?

kubectl get pods -n foo

这里的技巧是在你得到 pods 的列表后,我需要循环然后一个一个地删除每个超时为 15 秒,是否可以在 cronJob 中做到这一点?

apiVersion: batch/v1
kind: CronJob
metadata:
  name: restart
  namespace: foo
spec:
  concurrencyPolicy: Forbid
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      backoffLimit: 2
      activeDeadlineSeconds: 600
      template:
        spec:
          serviceAccountName: pod-exterminator
          restartPolicy: Never
          containers:
            - name: kubectl
              image: bitnami/kubectl:1.22.3
              command:
                - 'kubectl'
                - 'get'
                - 'pods'
                - '--namespace=foo'

当 运行 运行上面的脚本时,它可以工作,但是当你想 运行 循环时它变得复杂,我该如何内联?

这是我在删除 helm chart 后清理 rabbitmq 实例所做的类似操作(hyperkube 映像可以 运行 kubectl 命令):

apiVersion: batch/v1
kind: Job
metadata:
  name: {{ template "rabbitmq-cluster-operator.fullname" . }}-delete-instances
  namespace: {{ .Release.Namespace }}
  annotations:
    "helm.sh/hook": pre-delete
    "helm.sh/hook-weight": "1"
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded,hook-failed
  labels:
    app: {{ template "rabbitmq-cluster-operator.name" . }}
    release: {{ .Release.Name }}
spec:
  template:
    metadata:
      name: {{ template "rabbitmq-cluster-operator.fullname" . }}-delete- instances
      labels:
        app: {{ template "rabbitmq-cluster-operator.name" . }}
      annotations:
        sidecar.istio.io/inject: "false"
    spec:
      restartPolicy: Never
      serviceAccountName: {{ template "rabbitmq-cluster-operator.serviceAccountName" . }}
      containers:
      - name: kubectl
        image: "{{ .Values.global.hyperkube.image.repository }}/{{ 
 .Values.global.hyperkube.image.name }}:{{ .Values.global.hyperkube.image.tag }}"
        imagePullPolicy: "{{ .Values.global.hyperkube.image.pullPolicy }}"
    command:
    - /bin/sh
    - -c
    - >
        kubectl get rabbitmqclusters | while read -r entry; do
          name=$(echo $entry | awk '{print }');
          kubectl delete rabbitmqcluster $name -n {{ .Release.Namespace }};
        done

请注意,这是一项工作,但可以在 cronjob 中完成类似的事情。

在你的情况下,你可以使用这样的东西:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: restart
  namespace: foo
spec:
  concurrencyPolicy: Forbid
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      backoffLimit: 2
      activeDeadlineSeconds: 600
      template:
        spec:
          serviceAccountName: pod-exterminator
          restartPolicy: Never
          containers:
            - name: kubectl
              image: bitnami/kubectl:1.22.3
              command:
              - /bin/sh
              - -c
              - kubectl get pods -o name |  while read -r POD; do kubectl delete "$POD"; sleep 15; done

但是,你真的需要等15秒吗?如果你想在删除下一个 pod 之前确定 pod 已经消失,你可以使用 --wait=true,因此命令将变为:

kubectl get pods -o name |  while read -r POD; do kubectl delete "$POD" --wait; done