<p>I'm trying to write simple ansible playbook that would be able to execute some arbitrary command against the pod (container) running in kubernetes cluster.</p>

<p>I would like to utilise kubectl connection plugin: <a href="https://docs.ansible.com/ansible/latest/plugins/connection/kubectl.html" rel="nofollow noreferrer">https://docs.ansible.com/ansible/latest/plugins/connection/kubectl.html</a> but having struggle to figure out how to actually do that.</p>

<p>Couple of questions:</p>

<ol>
<li>Do I need to first have inventory for k8s defined? Something like: <a href="https://docs.ansible.com/ansible/latest/plugins/inventory/k8s.html" rel="nofollow noreferrer">https://docs.ansible.com/ansible/latest/plugins/inventory/k8s.html</a>. My understanding is that I would define kube config via inventory which would be used by the kubectl plugin to actually connect to the pods to perform specific action.</li>
<li>If yes, is there any example of arbitrary command executed via kubectl plugin (but not via shell plugin that invokes kubectl on some remote machine - this is not what I'm looking for)</li>
</ol>

<p>I'm assuming that, during the ansible-playbook invocation, I would point to k8s inventory.</p>

<p>Thanks.</p>

Bakir Jusufbegovic
<blockquote>
  <p>I would like to utilise kubectl connection plugin: <a href="https://docs.ansible.com/ansible/latest/plugins/connection/kubectl.html" rel="nofollow noreferrer">https://docs.ansible.com/ansible/latest/plugins/connection/kubectl.html</a> but having struggle to figure out how to actually do that.</p>
</blockquote>

<p>The <a href="https://docs.ansible.com/ansible/2.9/plugins/connection.html#using-connection-plugins" rel="nofollow noreferrer">fine manual</a> describes how one uses connection plugins, and while it is <a href="https://docs.ansible.com/ansible/2.9/reference_appendices/playbooks_keywords.html#task" rel="nofollow noreferrer">possible to use in in tasks</a>, that is unlikely to make any sense unless your inventory <em>started</em> with Pods.</p>

<p>The way I have seen that connection used is to start by identifying the Pods against which you might want to take action, and then run a playbook against a unique group for that purpose:</p>

<pre><code>- hosts: all
  tasks:
  - set_fact:
      # this is *just an example for brevity*
      # in reality you would use `k8s:` or `kubectl get -o name pods -l my-selector=my-value` to get the pod names
      pod_names:
      - nginx-12345
      - nginx-3456
  - add_host:
      name: '{{ item }}'
      groups:
      - my-pods
    with_items: '{{ pod_names }}'

- hosts: my-pods
  connection: kubectl
  tasks:
  # and now you are off to the races
  - command: ps -ef
  # watch out if the Pod doesn't have a working python installed
  # as you will have to use raw: instead
  # (and, of course, disable "gather_facts: no")
  - raw: ps -ef
</code></pre>
