用 Ansible 取得 Kubernetes pod 資訊

要使用 Ansible 來連到 kubernetes,可以透過 kubernetes.core 這個 collection。

kubernetes.core 這個 collection 主要是使用 Kubernetes Python Client 這個函式庫,得用 apt install 安裝 python3-kubernetes

sudo apt install -y python3-kuberentes
ansible-galaxy collections install kubernetes.core

接下來就可以寫個 playbook 來取得指定名稱空間裡的 pods

---
- name: Fetch pod information
  hosts: localhost

  tasks:
    - name: Fetch all pods which are running
      ansible.builtin.set_fact:
         deployments_pod: "{{ lookup('k8s', kind='Pod', namespace='practice', wantlist=True) }}"

    - name: Display deployments_pod
      when: false
      ansible.builtin.debug:
        msg: "{{ deployments_pod | to_json }}"

這樣輸出的結果有點多,這邊要利用 json_query 來整理一下,所以先用 ansible-galaxy 安裝 community.general

ansible-galaxy collection install community.general

然後改寫 playbook 如下

---
- name: Fetch pod information
  hosts: localhost

  tasks:
    - name: Fetch all pods which are running
      ansible.builtin.set_fact:
         deployments_pod: "{{ lookup('k8s', kind='Pod', namespace='practice', wantlist=True) }}"

    - name: Display deployments_pod
      ansible.builtin.debug:
        msg: "{{ deployments_pod | community.general.json_query('[].metadata.name') | join(',') }}"

透過 json_query ,可以只取出 pod 的名稱出來顯示,這邊加上了 join(','),將結果用 ‘,’ 做分隔。

結果會是這樣子

PLAY [Fetch pod information] *******************************************************************************************

TASK [Gathering Facts] *************************************************************************************************
ok: [localhost]

TASK [Fetch all pods which are running] ********************************************************************************
ok: [localhost]

TASK [Display deployments_pod] *****************************************************************************************
ok: [localhost] => {
    "msg": "security-context-demo-default,hello-nginx-58f6cb4d7c-ttrrp"
}

PLAY RECAP *************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

參考資料