<p>I have a cronjob that cleans some job since my kubernetes is on older version so cannot use <code>ttlafterfinished</code>.  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?</p>
<p>This is my cronjob:</p>
<pre><code>kind: CronJob
metadata:
  name: jobs-cleanup
spec:
  schedule: &quot;*/30 * * * *&quot;
  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 &quot;job-init&quot; | 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 &quot;fusionauth-job&quot; | cut -d' ' -f1 | tac | tail -n +2 | xargs -I % kubectl delete jobs % -n stg1
              kubectl get jobs --sort-by=.metadata.creationTimestamp -n pt1 | grep &quot;fusionauth-job&quot; | cut -d' ' -f1 | tac | tail -n +2 | xargs -I % kubectl delete jobs % -n pt1
              kubectl get jobs --sort-by=.metadata.creationTimestamp -n sit1 | grep &quot;fusionauth-job&quot; | cut -d' ' -f1 | tac | tail -n +2 | xargs -I % kubectl delete jobs % -n sit1
            command:
            - /bin/sh
          restartPolicy: Never
          imagePullSecrets:
            - name: secret
</code></pre>

cloudbud
<p>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.</p>
<p>Below is a simpler (IMO) version of your command that uses the <code>-o=jsonpath</code> support instead in <code>kubectl</code> to specify a search criteria.</p>
<pre class="lang-sh prettyprint-override"><code># The list of jobs you want to delete from any/all namespaces.
jobs_list=&quot;job-init fusionauth-job&quot;

for job_name in ${jobs_list}; do
    kubectl get jobs -A --sort-by=.metadata.creationTimestamp \
        -o=jsonpath=&quot;{range .items[?(@.metadata.name == '${job_name}')]}{.metadata.namespace} {.metadata.name}{'\n'}{end}&quot; \
          | while read namespace job;do kubectl delete job ${job} -n ${namespace};done;
done
</code></pre>
<blockquote>
<p><strong><em>The following was added as a result of the comments/conversation below.</em></strong></p>
</blockquote>
<p>If the job names in your cluster have incrementing suffixes, such as <code>fusionauth-job-01</code>, <code>fusionauth-job-02</code>, etc, and you want to keep <em>only</em> the latest instance of that job in a particular namespace, then you will need to leverage something like <code>jq</code> so you can do some regular expression matching.  <code>kubectl</code>'s <code>jsonpath</code> feature doesn't support regular expressions.</p>
<p>As an example, let's assume your cluster has the jobs shown below.</p>
<pre><code>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
</code></pre>
<p>Furthermore, the jobs are listed in timestamp order, meaning <code>fusionauth-job-03</code> is the newest job (whose name matches <code>fusionauth-job*</code>) in namespace <code>team2</code>, <code>job-init-02</code> is the newest job (whose name matches <code>job-init*</code>) in namespace <code>team1</code>, <code>fusionauth-job-02</code> is the newest job (of that name pattern) in namespace <code>team1</code>, and <code>fusionauth-job-01</code> is the only job running in namespace <code>default</code>.</p>
<p>After running your <code>jobs-cleanup</code> job, the expectation is that the following jobs would be left:</p>
<pre><code>NAMESPACE   NAME
default     fusionauth-job-01
team1       fusionauth-job-02
team1       job-init-02 
team2       fusionauth-job-03
</code></pre>
<p>A script to produce these results is shown here:</p>
<pre class="lang-sh prettyprint-override"><code># The list of job name prefixes you want to delete from any/all namespaces.
jobs_list=&quot;job-init fusionauth-job&quot;

for job_name in ${jobs_list}; do
    ns_observed=&quot;&quot;
    echo &quot;Searching for ${job_name}*&quot;
    kubectl get jobs -A --sort-by=.metadata.creationTimestamp -o json \
        | jq -r '.items[] | select(.metadata.name | test('\&quot;${job_name}\&quot;')) | .metadata.namespace + &quot; &quot; + .metadata.name' \
        | tac \
        | while read namespace job;do
            if test &quot;${ns_observed#*$namespace}&quot; != &quot;$ns_observed&quot;;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=&quot;$ns_observed $namespace&quot;;
            fi;
        done;
done
</code></pre>
