Debian Codegraph @

ansible_collections/community/proxmox/plugins/modules/proxmox_vm_info.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2023, Sergei Antipov <greendayonfire at gmail.com>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7
8 DOCUMENTATION = r"""
9 module: proxmox_vm_info
10 short_description: Retrieve information about one or more Proxmox VE virtual machines
11 description:
12 - Retrieve information about one or more Proxmox VE virtual machines.
13 author: 'Sergei Antipov (@UnderGreen) <greendayonfire at gmail dot com>'
14 options:
15 node:
16 description:
17 - Restrict results to a specific Proxmox VE node.
18 type: str
19 type:
20 description:
21 - Restrict results to a specific virtual machine(s) type.
22 type: str
23 choices:
24 - all
25 - qemu
26 - lxc
27 default: all
28 vmid:
29 description:
30 - Restrict results to a specific virtual machine by using its ID.
31 - If VM with the specified vmid does not exist in a cluster then resulting list will be empty.
32 type: int
33 name:
34 description:
35 - Restrict results to a specific virtual machine(s) by using their name.
36 - If VM(s) with the specified name do not exist in a cluster then the resulting list will be empty.
37 type: str
38 config:
39 description:
40 - Whether to retrieve the VM configuration along with VM status.
41 - If set to V(none) (default), no configuration will be returned.
42 - If set to V(current), the current running configuration will be returned.
43 - If set to V(pending), the configuration with pending changes applied will be returned.
44 type: str
45 choices:
46 - none
47 - current
48 - pending
49 default: none
50 network:
51 description:
52 - Whether to retrieve the current network status.
53 - Requires enabled/running qemu-guest-agent on qemu VMs.
54 type: bool
55 default: false
56 extends_documentation_fragment:
57 - community.proxmox.proxmox.actiongroup_proxmox
58 - community.proxmox.proxmox.documentation
59 - community.proxmox.attributes
60 - community.proxmox.attributes.info_module
61 """
62
63 EXAMPLES = r"""
64 - name: List all existing virtual machines on node
65 community.proxmox.proxmox_vm_info:
66 node: node01
67
68 - name: List all QEMU virtual machines on node
69 community.proxmox.proxmox_vm_info:
70 node: node01
71 type: qemu
72
73 - name: Retrieve information about specific VM by ID
74 community.proxmox.proxmox_vm_info:
75 node: node01
76 type: qemu
77 vmid: 101
78
79 - name: Retrieve information about specific VM by name and get current configuration
80 community.proxmox.proxmox_vm_info:
81 node: node01
82 type: lxc
83 name: lxc05.home.arpa
84 config: current
85 """
86
87 RETURN = r"""
88 proxmox_vms:
89 description: List of virtual machines.
90 returned: on success
91 type: list
92 elements: dict
93 sample:
94 [
95 {
96 "cpu": 0.258944410905281,
97 "cpus": 1,
98 "disk": 0,
99 "diskread": 0,
100 "diskwrite": 0,
101 "id": "qemu/100",
102 "maxcpu": 1,
103 "maxdisk": 34359738368,
104 "maxmem": 4294967296,
105 "mem": 35158379,
106 "name": "pxe.home.arpa",
107 "netin": 99715803,
108 "netout": 14237835,
109 "node": "pve",
110 "pid": 1947197,
111 "status": "running",
112 "template": False,
113 "type": "qemu",
114 "uptime": 135530,
115 "vmid": 100
116 },
117 {
118 "cpu": 0,
119 "cpus": 1,
120 "disk": 0,
121 "diskread": 0,
122 "diskwrite": 0,
123 "id": "qemu/101",
124 "maxcpu": 1,
125 "maxdisk": 0,
126 "maxmem": 536870912,
127 "mem": 0,
128 "name": "test1",
129 "netin": 0,
130 "netout": 0,
131 "node": "pve",
132 "status": "stopped",
133 "template": False,
134 "type": "qemu",
135 "uptime": 0,
136 "vmid": 101
137 }
138 ]
139 """
140
141 from ansible_collections.community.proxmox.plugins.module_utils.proxmox import (
142 ProxmoxAnsible,
143 create_proxmox_module,
144 proxmox_to_ansible_bool,
145 )
146
147
148 def module_args():
149 return dict(
150 node=dict(type="str", required=False),
151 type=dict(type="str", choices=["lxc", "qemu", "all"], default="all", required=False),
152 vmid=dict(type="int", required=False),
153 name=dict(type="str", required=False),
154 config=dict(type="str", choices=["none", "current", "pending"], default="none", required=False),
155 network=dict(type="bool", default=False, required=False),
156 )
157
158
159 def module_options():
160 return {}
161
162
163 class ProxmoxVmInfoAnsible(ProxmoxAnsible):
164 def get_vms_from_cluster_resources(self):
165 try:
166 return self.proxmox_api.cluster().resources().get(type="vm")
167 except Exception as e:
168 self.module.fail_json(msg=f"Failed to retrieve VMs information from cluster resources: {e}")
169
170 def get_vms_from_nodes( # noqa: PLR0913
171 self, cluster_machines, resource_type, vmid=None, name=None, node=None, config=None, network=False
172 ):
173 # Leave in dict only machines that user wants to know about
174 filtered_vms = {
175 vm: info
176 for vm, info in cluster_machines.items()
177 if not (
178 resource_type != info["type"]
179 or (node and info.get("node") != node)
180 or (vmid and int(info.get("vmid", -1)) != vmid)
181 or (name is not None and info.get("name") != name)
182 )
183 }
184 # Get list of unique node names and loop through it to get info about machines.
185 nodes = frozenset([info["node"] for vm, info in filtered_vms.items() if "node" in info])
186 for this_node in nodes:
187 # resource_type is "qemu" or "lxc" - matches Proxmox API nodes(node).qemu / nodes(node).lxc attributes.
188 call_vm_getter = getattr(self.proxmox_api.nodes(this_node), resource_type)
189 vms_from_this_node = call_vm_getter().get()
190 for detected_vm in vms_from_this_node:
191 this_vm_id = int(detected_vm["vmid"])
192 desired_vm = filtered_vms.get(this_vm_id)
193 if desired_vm:
194 desired_vm.update(detected_vm)
195 desired_vm["vmid"] = this_vm_id
196 desired_vm["template"] = proxmox_to_ansible_bool(desired_vm.get("template", 0))
197 # When user wants to retrieve the VM configuration
198 if config != "none":
199 # pending = 0, current = 1
200 config_type = 0 if config == "pending" else 1
201 # GET /nodes/{node}/qemu/{vmid}/config current=[0/1]
202 desired_vm["config"] = call_vm_getter(this_vm_id).config().get(current=config_type)
203 if network:
204 if resource_type == "qemu":
205 desired_vm["network"] = (
206 call_vm_getter(this_vm_id).agent("network-get-interfaces").get()["result"]
207 )
208 elif resource_type == "lxc":
209 desired_vm["network"] = call_vm_getter(this_vm_id).interfaces.get()
210
211 return filtered_vms
212
213 def get_qemu_vms(self, cluster_machines, vmid=None, name=None, node=None, config=None, network=False): # noqa: PLR0913
214 try:
215 return self.get_vms_from_nodes(cluster_machines, "qemu", vmid, name, node, config, network)
216 except Exception as e:
217 self.module.fail_json(msg=f"Failed to retrieve QEMU VMs information: {e}")
218
219 def get_lxc_vms(self, cluster_machines, vmid=None, name=None, node=None, config=None, network=False): # noqa: PLR0913
220 try:
221 return self.get_vms_from_nodes(cluster_machines, "lxc", vmid, name, node, config, network)
222 except Exception as e:
223 self.module.fail_json(msg=f"Failed to retrieve LXC VMs information: {e}")
224
225
226 def main():
227 module = create_proxmox_module(module_args(), **module_options())
228 proxmox = ProxmoxVmInfoAnsible(module)
229
230 node = module.params["node"]
231 resource_type = module.params["type"]
232 vmid = module.params["vmid"]
233 name = module.params["name"]
234 config = module.params["config"]
235 network = module.params["network"]
236
237 result = dict(changed=False)
238
239 if node and proxmox.get_node(node) is None:
240 module.fail_json(msg=f"Node {node} doesn't exist in PVE cluster")
241
242 vms_cluster_resources = proxmox.get_vms_from_cluster_resources()
243 cluster_machines = {int(machine["vmid"]): machine for machine in vms_cluster_resources}
244 vms = {}
245
246 if resource_type == "lxc":
247 vms = proxmox.get_lxc_vms(cluster_machines, vmid, name, node, config, network)
248 elif resource_type == "qemu":
249 vms = proxmox.get_qemu_vms(cluster_machines, vmid, name, node, config, network)
250 else:
251 vms = proxmox.get_qemu_vms(cluster_machines, vmid, name, node, config, network)
252 vms.update(proxmox.get_lxc_vms(cluster_machines, vmid, name, node, config, network))
253
254 result["proxmox_vms"] = [info for vm, info in sorted(vms.items())]
255 module.exit_json(**result)
256
257
258 if __name__ == "__main__":
259 main()