Need to a have a post deployment task on the pod of same deployment

1/28/2021

I am writing ansible scripts for deploying services using Kubernetes, I am stuck with a step that is for the post-deployment process:

I have deployed a service having "replicas: 3", 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.

I can do it manually by getting into the container individually and then run the script but this will again require manual intervention.

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.

Is there a way to do this?

-- Anuj Kishor
ansible
kubernetes
kubernetes-pod

2 Answers

1/28/2021

@Vasili Angapov is right - k8s_exec module is probably the best solution in this case but I would like to add some useful notes.


To use k8s_exec we need to know the exact Pod name (we need to pass it as pod parameter in ansible task). As you wrote, I assume that your Pods are managed by Deployment, so every Pod has random string in its name added by ReplicaSet. Therefore, you have to find the full names of the Pods somehow.<br><br> I've created simple playbook to illustrate how we can find Pod names for all Pods with label: app=web and then run sample touch file123456789 command on these Pods.

---
- hosts: localhost
  collections:
    - community.kubernetes

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

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

    - name: "Run command on every Pod labelled app=web"
      k8s_exec:
        namespace: default
        pod: "{{ item }}"
        command: touch file123456789
      with_items: "{{ pod_names }}"

NOTE: Instead of k8s_exec module you can use command module as well. In our example instead of k8s_exec task we can have:<br>

- name: "Run command on every Pod labelled app=web"
  command: >
    kubectl exec "{{ item }}" -n default -- touch file123456789
  with_items: "{{ pod_names }}"
-- matt_j
Source: StackOverflow

1/28/2021

Take a look at k8s_exec module.

- name: Check RC status of command executed
  community.kubernetes.k8s_exec:
    namespace: myproject
    pod: busybox-test
    command: cmd_with_non_zero_exit_code
  register: command_status
  ignore_errors: True

- name: Check last command status
  debug:
    msg: "cmd failed"
  when: command_status.return_code != 0
-- Vasili Angapov
Source: StackOverflow