I am working on an application which is hosted in kubernetes and currently it does not support any kind of API. The only way to automate the workflow what we are trying to achieve is to login into one of the pod of that application and run a commds which will run the conciliation
So i have written a ansible playbook and to keep it simple i have installed kubernetes python library on the target machine using which i am accessing the kubernetes application
pip install kubernetes
Once done i have wrote a ansible playbook the config are loaded from ~/.kube/config file on that server and below is the sample playbook. here am executing a sample play which is printing the nginx pod host name but it can be replace with the actual command we want to run
- name: Execute command inside a Kubernetes pod selected by label
hosts: all
gather_facts: no
collections:
- kubernetes.core
vars:
namespace: "default" ## add namespace here
label_selector: "app=nginx" # add lable selector here
container_name: "" # optional — leave empty to use default container
exec_command: "/usr/bin/hostname" # command to run inside the container
tasks:
- name: Get pods matching label selector
kubernetes.core.k8s_info:
api_version: v1
kind: Pod
namespace: "{{ namespace }}"
label_selectors:
- "{{ label_selector }}"
register: pod_list
- name: Fail if no pods found
fail:
msg: "No pods found with label {{ label_selector }} in {{ namespace }}"
when: pod_list.resources | length == 0
- name: Select the first pod
set_fact:
target_pod: "{{ pod_list.resources[0].metadata.name }}"
- debug:
msg: "Selected pod: {{ target_pod }}"
- name: Exec command inside pod
kubernetes.core.k8s_exec:
namespace: "{{ namespace }}"
pod: "{{ target_pod }}"
container: "{{ container_name | default(omit) }}"
command: "{{ exec_command }}"
register: exec_output
- debug:
var: exec_output.stdout
Sample output
No comments:
Post a Comment