77 lines
3.3 KiB
YAML

---
- name: List VMs and Containers on Proxmox hosts
hosts: proxmox_cluster
gather_facts: false
vars:
proxmox_user: "{{ lookup('env','PROXMOX_USER') }}"
proxmox_password: "{{ lookup('env','PROXMOX_PASSWORD') }}"
proxmox_verify_ssl: false
tasks:
- name: Ensure credentials are provided
ansible.builtin.assert:
that:
- proxmox_user is defined
- proxmox_password is defined
fail_msg: "Set PROXMOX_USER and PROXMOX_PASSWORD environment variables before running."
- name: Build Proxmox Authorization header (use token if available)
ansible.builtin.set_fact:
proxmox_auth_header: >-
{% if lookup('env','PROXMOX_TOKEN_ID') and lookup('env','PROXMOX_TOKEN_SECRET') %}
PVEAPIToken={{ lookup('env','PROXMOX_TOKEN_ID') }}={{ lookup('env','PROXMOX_TOKEN_SECRET') }}
{% elif lookup('env','PROXMOX_USER') and '!' in lookup('env','PROXMOX_USER') and lookup('env','PROXMOX_PASSWORD') %}
PVEAPIToken={{ lookup('env','PROXMOX_USER') }}={{ lookup('env','PROXMOX_PASSWORD') }}
{% else %}
{% endif %}
- name: Query nodes on the host
ansible.builtin.uri:
url: "https://{{ ansible_host }}:8006/api2/json/nodes"
method: GET
validate_certs: "{{ proxmox_verify_ssl }}"
headers: "{{ {'Authorization': proxmox_auth_header} if proxmox_auth_header|length > 0 else {} }}"
return_content: true
register: nodes_resp
failed_when: false
- name: Set list of nodes
ansible.builtin.set_fact:
proxmox_nodes: "{{ nodes_resp.json.data | map(attribute='node') | list }}"
when: nodes_resp.status == 200 and nodes_resp.json is defined and nodes_resp.json.data is defined
- name: Query QEMU VMs for each node
ansible.builtin.uri:
url: "https://{{ ansible_host }}:8006/api2/json/nodes/{{ item }}/qemu"
method: GET
validate_certs: "{{ proxmox_verify_ssl }}"
headers: "{{ {'Authorization': proxmox_auth_header} if proxmox_auth_header|length > 0 else {} }}"
return_content: true
loop: "{{ proxmox_nodes | default([]) }}"
register: qemu_results
failed_when: false
when: proxmox_nodes is defined
- name: Query LXC containers for each node
ansible.builtin.uri:
url: "https://{{ ansible_host }}:8006/api2/json/nodes/{{ item }}/lxc"
method: GET
validate_certs: "{{ proxmox_verify_ssl }}"
headers: "{{ {'Authorization': proxmox_auth_header} if proxmox_auth_header|length > 0 else {} }}"
return_content: true
loop: "{{ proxmox_nodes | default([]) }}"
register: lxc_results
failed_when: false
when: proxmox_nodes is defined
- name: Compute counts
ansible.builtin.set_fact:
qemu_count: "{{ qemu_results.results | map(attribute='json.data') | map('length') | sum(default=0) }}"
lxc_count: "{{ lxc_results.results | map(attribute='json.data') | map('length') | sum(default=0) }}"
when: proxmox_nodes is defined
- name: Report VMs/CTs on host
ansible.builtin.debug:
msg: "Host {{ inventory_hostname }} ({{ ansible_host }}) nodes={{ proxmox_nodes | default([]) }} qemu={{ qemu_count | default(0) }} lxc={{ lxc_count | default(0) }} total={{ (qemu_count|default(0)) + (lxc_count|default(0)) }}"