<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
<p>First install k8s collections</p>

<pre><code>ansible-galaxy collection install community.kubernetes
</code></pre>

<p>and here is play-book, it will sort all pods and run a command in every pod </p>

<pre><code>---
- 
  hosts: localhost

  vars_files: 
    - vars/main.yaml 

  collections:
    - community.kubernetes    

  tasks:     
    -
      name: Get the pods in the specific namespace
      k8s_info:
        kubeconfig: '{{ k8s_kubeconfig }}'
        kind: Pod
        namespace: test
      register: pod_list


    - 
      name: Print pod names
      debug:
         msg: "pod_list: {{ pod_list | json_query('resources[*].status.podIP')  }} "

    - set_fact:
        pod_names: "{{pod_list|json_query('resources[*].metadata.name')}}"

    - 
      k8s_exec:
        kubeconfig: '{{ k8s_kubeconfig }}'
        namespace: "{{ namespace  }}"
        pod: "{{ item.metadata.name }}"
        command: apt update
      with_items: "{{ pod_list.resources }}"
      register: exec
      loop_control:
        label: "{{ item.metadata.name }}"
</code></pre>
