<p>I have the following code:</p>
<pre><code> kubectl get job &lt;JOB-NAME&gt; -o json | jq 'del(.spec.selector)' | jq 'del(.spec.template.metadata.labels)' | kubectl replace --force -f -
</code></pre>
<p>That replaces an existing Kubernetes job with itself. Is it possible to do this with the Python Kubernetes API?</p>
<p>Here's what I am trying to do now:</p>
<pre><code>import kubernetes as kubernetes
from kubernetes import client, config

# Configs can be set in Configuration class directly or using helper utility
config.load_kube_config()

configuration = kubernetes.client.Configuration()
name = &quot;job-1&quot;
namespace = &quot;default&quot;

v1 = client.CoreV1Api()

# Grab the exact name of the pod based on the job
metabase_create_readonly_user_name = ''
pods = v1.list_namespaced_pod(namespace, label_selector='job-name={}'.format(name), watch=False)
for pod in pods.items:
    job_name = pod.metadata.name


# THIS DOES NOT WORK!
v1.replace_namespaced_pod(job_name, namespace)
</code></pre>
<p>However, <code>replace_namespaced_pod</code> needs a <code>body</code> passed in as a parameter, so I'm not sure what to give it there. Is there a way to grab the exact body of the existing job and pass it in here?</p>

jipot
<p>The kubectl replace command has a <strong>--force</strong> option which actually does not use the replace, i.e., PUT, API endpoint. It <strong>forcibly deletes</strong> (DELETE) and then <strong>recreates</strong>, (POST) the resource using the provided spec.</p>
<p>According to the <a href="https://github.com/kubernetes-client/python/tree/master/kubernetes" rel="nofollow noreferrer">kubernetes python client docs</a>:</p>
<p>Under the class <code>BatchV1Api</code>(<a href="https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/BatchV1Api.md" rel="nofollow noreferrer">Api</a>), there are 3 methods:</p>
<p><code>read_namespaced_job</code>, <code>delete_namespaced_job</code> and <code>create_namespaced_job</code>.</p>
<p>So the following code snippet will suffice:</p>
<pre class="lang-py prettyprint-override"><code>from kubernetes import client, config

config.load_kube_config()

batch_v1 = client.BatchV1Api()
...
v1_job = batch_v1.read_namespaced_job(name, namespace)
# some processing to v1_job
v1_job.metadata.resource_version = None
v1_job.metadata.uid = None
# as in your example
v1_job.spec.selector = None
v1_job.spec.template.metadata.labels = None
...
# forcibly deletes
batch_v1.delete_namespaced_job(name, namespace)
# recreates
batch_v1.create_namespaced_job(namespace, v1_job)
</code></pre>
