<p><strong>Problem Statement</strong></p>
<p>I have a Kubernetes cluster with many pods running in a particular namespace. I want to read the logs of a particular pod using Python with the Paramiko SSH client.</p>
<p>I have pods running below</p>
<pre><code>kubectl get pods -n &lt;myNameSpace&gt;
</code></pre>
<p>The result of the above command will look like</p>
<pre><code>service1-8457bd9899-4jdzz
service2-765b497fbf-2w82j
</code></pre>
<p>Here is my Python code, I know the deployment names such as service1, service2 etc</p>
<p>I want to read the logs using those names alone like</p>
<pre><code>kubectl logs service1* -n &lt;myNameSpace&gt; -f --tail 100
</code></pre>
<p>But the above command won't work because that regular expression won't work.</p>
<p><strong>My Solution</strong></p>
<p>I am running two commands one to get the full pod name and the other to check the logs using that full name</p>
<pre><code> ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(f'kubectl get pods -n namespace1 |grep service1')
 pod_name_service1 = ssh_stdout.read().decode(&quot;utf-8&quot;).split(' ')[0]
 ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(
                f'kubectl logs {pod_name_service1} -n edge -f --tail 100')
 service1_logs = ssh_stdout.read().decode(&quot;utf-8&quot;)
</code></pre>
<p><strong>Question</strong></p>
<p>How to use just the service depolyment name alone (without replicaset name + random 5-digit alphanumeric) to retrieve logs? Is there any other way exist for this?</p>

KBNanda
<p>If there is only one replica, or if you don't care which replica you get, you can directly use the Deployment name on the command line</p>
<pre class="lang-bash prettyprint-override"><code>kubectl logs -n my-namespace deployment/service1 --tail 100 -f
</code></pre>
<p>Note that this is one of a couple of commands that actually works on a specific Pod, even though you can use a <code>deployment/name</code> syntax (other object types will work too).  If the specific Pod that this attaches to exits then the <code>kubectl logs</code> command will stop too, even if other replicas remain running uninterrupted.</p>
<p>(I would also strongly suggest fixing the shell-injection vulnerability in your code.  Consider using a Kubernetes SDK over executing <code>kubectl</code> commands, maybe port-forwarding the Kubernetes API endpoint over the ssh connection if needed.)</p>
