<p>I am writing ansible scripts for deploying services using Kubernetes, I am stuck with a step that is for the post-deployment process:</p>
<p>I have deployed a service having &quot;<strong>replicas: 3</strong>&quot;, and all the replicas are up and running now my problem is to I have to do a migration for which I have to get into the container and run a script already present there.</p>
<p>I can do it manually by getting into the container individually and then run the script but this will again require manual intervention.</p>
<p>What I want to achieve is once the deployment is done and all the replicas are up and running I want to run the scripts by getting into the containers and all these steps should be performed by ansible script and no manual effort required.</p>
<p>Is there a way to do this?</p>

Anuj Kishor
<p>@Vasili Angapov is right - <strong>k8s_exec</strong> module is probably the best solution in this case but I would like to add some useful notes.</p>
<hr />
<p>To use <strong>k8s_exec</strong> we need to know the exact <code>Pod</code> name (we need to pass it as <code>pod</code> parameter in ansible task). As you wrote, I assume that your <code>Pods</code> are managed by <code>Deployment</code>, so every <code>Pod</code> has random string in its name added by <code>ReplicaSet</code>. Therefore, you have to find the full names of the <code>Pods</code> somehow.<br><br>
I've created simple playbook to illustrate how we can find <code>Pod</code> names for all <code>Pods</code> with label: <code>app=web</code> and then run sample <code>touch file123456789</code> command on these <code>Pods</code>.</p>
<pre><code>---
- hosts: localhost
  collections:
    - community.kubernetes

  tasks:     
    - name: &quot;Search for all Pods labelled app=web&quot;
      k8s_info:
        kind: Pod
        label_selectors:
          - app = web
      register: pod_names

    - name: &quot;Get Pod names&quot;
      set_fact:
        pod_names: &quot;{{ pod_names | json_query('resources[*].metadata.name') }}&quot;

    - name: &quot;Run command on every Pod labelled app=web&quot;
      k8s_exec:
        namespace: default
        pod: &quot;{{ item }}&quot;
        command: touch file123456789
      with_items: &quot;{{ pod_names }}&quot;
</code></pre>
<p><strong>NOTE:</strong> Instead of <code>k8s_exec</code> module you can use <code>command</code> module as well.
In our example instead of <code>k8s_exec</code> task we can have:<br></p>
<pre><code>- name: &quot;Run command on every Pod labelled app=web&quot;
  command: &gt;
    kubectl exec &quot;{{ item }}&quot; -n default -- touch file123456789
  with_items: &quot;{{ pod_names }}&quot;
</code></pre>
