简体   繁体   English

如何将 kubernetes 命名空间动态传递给 k8s cronjob

[英]How to pass kubernetes namespaces dynamically to k8s cronjob

I have a cronjob that cleans some job since my kubernetes is on older version so cannot use ttlafterfinished .我有一个 cronjob 可以清理一些工作,因为我的 kubernetes 是旧版本,所以不能使用ttlafterfinished How can I fetch the namespaces that have this job deployed and pass the namespaces name dynamically instead of repeating the same command several times?如何获取部署了此作业的命名空间并动态传递命名空间名称,而不是多次重复相同的命令?

This is my cronjob:这是我的 cronjob:

kind: CronJob
metadata:
  name: jobs-cleanup
spec:
  schedule: "*/30 * * * *"
  successfulJobsHistoryLimit: 1
  failedJobsHistoryLimit: 1
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: cleanup-operator
          containers:
          - name: jobs-cleanup
            image: google.io/test/job:1.0
            args:
            - -c
            - |
              for i in $(seq 9);do 
              kubectl get jobs --sort-by=.metadata.creationTimestamp -n dev$i | grep "job-init" | cut -d' ' -f1 | tac | tail -n +2 | xargs -I % kubectl delete jobs % -n dev$i;done
              kubectl get jobs --sort-by=.metadata.creationTimestamp -n stg1 | grep "fusionauth-job" | cut -d' ' -f1 | tac | tail -n +2 | xargs -I % kubectl delete jobs % -n stg1
              kubectl get jobs --sort-by=.metadata.creationTimestamp -n pt1 | grep "fusionauth-job" | cut -d' ' -f1 | tac | tail -n +2 | xargs -I % kubectl delete jobs % -n pt1
              kubectl get jobs --sort-by=.metadata.creationTimestamp -n sit1 | grep "fusionauth-job" | cut -d' ' -f1 | tac | tail -n +2 | xargs -I % kubectl delete jobs % -n sit1
            command:
            - /bin/sh
          restartPolicy: Never
          imagePullSecrets:
            - name: secret

A more flexible alternative to what you're doing now would be to store the list of job names you want to delete in a list/array.您现在正在做的更灵活的替代方法是将要删除的作业名称列表存储在列表/数组中。 Then, you can iterate through the list of job names and execute the command.然后,您可以遍历作业名称列表并执行命令。

Below is a simpler (IMO) version of your command that uses the -o=jsonpath support instead in kubectl to specify a search criteria.下面是您的命令的更简单 (IMO) 版本,它在kubectl中使用-o=jsonpath支持来指定搜索条件。

# The list of jobs you want to delete from any/all namespaces.
jobs_list="job-init fusionauth-job"

for job_name in ${jobs_list}; do
    kubectl get jobs -A --sort-by=.metadata.creationTimestamp \
        -o=jsonpath="{range .items[?(@.metadata.name == '${job_name}')]}{.metadata.namespace} {.metadata.name}{'\n'}{end}" \
          | while read namespace job;do kubectl delete job ${job} -n ${namespace};done;
done

The following was added as a result of the comments/conversation below.由于下面的评论/对话,添加了以下内容。

If the job names in your cluster have incrementing suffixes, such as fusionauth-job-01 , fusionauth-job-02 , etc, and you want to keep only the latest instance of that job in a particular namespace, then you will need to leverage something like jq so you can do some regular expression matching.如果集群中的作业名称具有递增的后缀,例如fusionauth-job-01fusionauth-job-02等,并且您只想在特定命名空间中保留该作业的最新实例,那么您将需要利用像jq这样你就可以做一些正则表达式匹配。 kubectl 's jsonpath feature doesn't support regular expressions. kubectljsonpath特性不支持正则表达式。

As an example, let's assume your cluster has the jobs shown below.例如,假设您的集群具有如下所示的作业。

NAMESPACE   NAME
default     fusionauth-job-01
team1       fusionauth-job-01
team1       fusionauth-job-02
team1       job-init-01
team1       job-init-02 
team2       fusionauth-job-01
team2       fusionauth-job-02
team2       fusionauth-job-03

Furthermore, the jobs are listed in timestamp order, meaning fusionauth-job-03 is the newest job (whose name matches fusionauth-job* ) in namespace team2 , job-init-02 is the newest job (whose name matches job-init* ) in namespace team1 , fusionauth-job-02 is the newest job (of that name pattern) in namespace team1 , and fusionauth-job-01 is the only job running in namespace default .此外,作业按时间戳顺序列出,这意味着fusionauth-job-03是命名空间team2中最新的作业(其名称与fusionauth-job*匹配), job-init-02是最新的作业(其名称与job-init*匹配) 在命名空间team1中, fusionauth-job-02是命名空间team1中的最新作业(该名称模式),而fusionauth-job-01是在命名空间default中运行的唯一作业。

After running your jobs-cleanup job, the expectation is that the following jobs would be left:运行您的jobs-cleanup作业后,预期会留下以下作业:

NAMESPACE   NAME
default     fusionauth-job-01
team1       fusionauth-job-02
team1       job-init-02 
team2       fusionauth-job-03

A script to produce these results is shown here:生成这些结果的脚本如下所示:

# The list of job name prefixes you want to delete from any/all namespaces.
jobs_list="job-init fusionauth-job"

for job_name in ${jobs_list}; do
    ns_observed=""
    echo "Searching for ${job_name}*"
    kubectl get jobs -A --sort-by=.metadata.creationTimestamp -o json \
        | jq -r '.items[] | select(.metadata.name | test('\"${job_name}\"')) | .metadata.namespace + " " + .metadata.name' \
        | tac \
        | while read namespace job;do
            if test "${ns_observed#*$namespace}" != "$ns_observed";then
                # If we've seen this namespace already for this job, then delete the
                # job, since the one we found previously is the newest.
                kubectl delete job ${job} -n ${namespace};
            else
                # Otherwise, if this is the first time observing this namespace, then
                # this is the newest job that starts with this job name in this namespace.
                ns_observed="$ns_observed $namespace";
            fi;
        done;
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM