Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_vm_info.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # Copyright: (c) 2021, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # template: header.j2
6 # This module is autogenerated using the ansible.content_builder.
7 # See: https://github.com/ansible-community/ansible.content_builder
8
9
10 DOCUMENTATION = r"""
11 module: vcenter_vm_info
12 short_description: Returns information about a virtual machine.
13 description: Returns information about a virtual machine.
14 options:
15 clusters:
16 description:
17 - Clusters that must contain the virtual machine for the virtual machine to
18 match the filter.
19 - If unset or empty, virtual machines in any cluster match the filter.
20 - When clients pass a value of this structure as a parameter, the field must
21 contain the id of resources returned by M(vmware.vmware_rest.vcenter_cluster_info).
22 elements: str
23 type: list
24 datacenters:
25 aliases:
26 - filter_datacenters
27 description:
28 - Datacenters that must contain the virtual machine for the virtual machine
29 to match the filter.
30 - If unset or empty, virtual machines in any datacenter match the filter.
31 - When clients pass a value of this structure as a parameter, the field must
32 contain the id of resources returned by M(vmware.vmware_rest.vcenter_datacenter_info).
33 elements: str
34 type: list
35 folders:
36 aliases:
37 - filter_folders
38 description:
39 - Folders that must contain the virtual machine for the virtual machine to
40 match the filter.
41 - If unset or empty, virtual machines in any folder match the filter.
42 - When clients pass a value of this structure as a parameter, the field must
43 contain the id of resources returned by M(vmware.vmware_rest.vcenter_folder_info).
44 elements: str
45 type: list
46 hosts:
47 description:
48 - Hosts that must contain the virtual machine for the virtual machine to match
49 the filter.
50 - If unset or empty, virtual machines on any host match the filter.
51 - When clients pass a value of this structure as a parameter, the field must
52 contain the id of resources returned by M(vmware.vmware_rest.vcenter_host_info).
53 elements: str
54 type: list
55 names:
56 aliases:
57 - filter_names
58 description:
59 - Names that virtual machines must have to match the filter (see I(name)).
60 - If unset or empty, virtual machines with any name match the filter.
61 elements: str
62 type: list
63 power_states:
64 description:
65 - Power states that a virtual machine must be in to match the filter (see
66 I()
67 - If unset or empty, virtual machines in any power state match the filter.
68 elements: str
69 type: list
70 resource_pools:
71 description:
72 - Resource pools that must contain the virtual machine for the virtual machine
73 to match the filter.
74 - If unset or empty, virtual machines in any resource pool match the filter.
75 - When clients pass a value of this structure as a parameter, the field must
76 contain the id of resources returned by M(vmware.vmware_rest.vcenter_resourcepool_info).
77 elements: str
78 type: list
79 session_timeout:
80 description:
81 - 'Timeout settings for client session. '
82 - 'The maximal number of seconds for the whole operation including connection
83 establishment, request sending and response. '
84 - The default value is 300s.
85 type: float
86 version_added: 2.1.0
87 vcenter_hostname:
88 description:
89 - The hostname or IP address of the vSphere vCenter
90 - If the value is not specified in the task, the value of environment variable
91 C(VMWARE_HOST) will be used instead.
92 required: true
93 type: str
94 vcenter_password:
95 description:
96 - The vSphere vCenter password
97 - If the value is not specified in the task, the value of environment variable
98 C(VMWARE_PASSWORD) will be used instead.
99 required: true
100 type: str
101 vcenter_rest_log_file:
102 description:
103 - 'You can use this optional parameter to set the location of a log file. '
104 - 'This file will be used to record the HTTP REST interaction. '
105 - 'The file will be stored on the host that runs the module. '
106 - 'If the value is not specified in the task, the value of '
107 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
108 type: str
109 vcenter_username:
110 description:
111 - The vSphere vCenter username
112 - If the value is not specified in the task, the value of environment variable
113 C(VMWARE_USER) will be used instead.
114 required: true
115 type: str
116 vcenter_validate_certs:
117 default: true
118 description:
119 - Allows connection when SSL certificates are not valid. Set to C(false) when
120 certificates are not trusted.
121 - If the value is not specified in the task, the value of environment variable
122 C(VMWARE_VALIDATE_CERTS) will be used instead.
123 type: bool
124 vm:
125 description:
126 - Virtual machine identifier.
127 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_info).
128 Required with I(state=['get'])
129 type: str
130 vms:
131 description:
132 - Identifiers of virtual machines that can match the filter.
133 - If unset or empty, virtual machines with any identifier match the filter.
134 - When clients pass a value of this structure as a parameter, the field must
135 contain the id of resources returned by M(vmware.vmware_rest.vcenter_vm_info).
136 elements: str
137 type: list
138 author:
139 - Ansible Cloud Team (@ansible-collections)
140 version_added: 0.1.0
141 requirements:
142 - vSphere 7.0.3 or greater
143 - python >= 3.6
144 - aiohttp
145 notes:
146 - Tested on vSphere 7.0.3
147 """
148
149 EXAMPLES = r"""
150 - name: Create a VM
151 vmware.vmware_rest.vcenter_vm:
152 placement:
153 cluster: "{{ lookup('vmware.vmware_rest.cluster_moid', '/my_dc/host/my_cluster') }}"
154 datastore: "{{ lookup('vmware.vmware_rest.datastore_moid', '/my_dc/datastore/local') }}"
155 folder: "{{ lookup('vmware.vmware_rest.folder_moid', '/my_dc/vm') }}"
156 resource_pool: "{{ lookup('vmware.vmware_rest.resource_pool_moid', '/my_dc/host/my_cluster/Resources') }}"
157 name: test_vm1
158 guest_OS: RHEL_7_64
159 hardware_version: VMX_11
160 memory:
161 hot_add_enabled: true
162 size_MiB: 1024
163 disks:
164 - type: SATA
165 backing:
166 type: VMDK_FILE
167 vmdk_file: '[local] test_vm1/{{ disk_name }}.vmdk'
168 - type: SATA
169 new_vmdk:
170 name: second_disk
171 capacity: 32000000000
172 cdroms:
173 - type: SATA
174 sata:
175 bus: 0
176 unit: 2
177 nics:
178 - backing:
179 type: STANDARD_PORTGROUP
180 network: "{{ lookup('vmware.vmware_rest.network_moid', '/my_dc/network/VM Network') }}"
181 register: my_vm
182
183 - name: Wait until my VM is off
184 vmware.vmware_rest.vcenter_vm_info:
185 vm: '{{ my_vm.id }}'
186 register: vm_info
187 until:
188 - vm_info is not failed
189 - vm_info.value.power_state == "POWERED_OFF"
190 retries: 60
191 delay: 5
192
193 - register: _should_be_empty
194 name: Search with an invalid filter
195 vmware.vmware_rest.vcenter_vm_info:
196 filter_names: test_vm1_does_not_exists
197
198 - name: Look up the VM called test_vm1 in the inventory
199 register: search_result
200 vmware.vmware_rest.vcenter_vm_info:
201 filter_names:
202 - test_vm1
203
204 - name: Collect information about a specific VM
205 vmware.vmware_rest.vcenter_vm_info:
206 vm: '{{ search_result.value[0].vm }}'
207 register: test_vm1_info
208 """
209 RETURN = r"""
210 # content generated by the update_return_section callback# task: Wait until my VM is off
211 id:
212 description: moid of the resource
213 returned: On success
214 sample: vm-1049
215 type: str
216 value:
217 description: Wait until my VM is off
218 returned: On success
219 sample:
220 boot:
221 delay: 0
222 enter_setup_mode: 0
223 retry: 0
224 retry_delay: 10000
225 type: BIOS
226 boot_devices: []
227 cdroms:
228 '16002':
229 allow_guest_control: 0
230 backing:
231 auto_detect: 1
232 device_access_type: EMULATION
233 type: HOST_DEVICE
234 label: CD/DVD drive 1
235 sata:
236 bus: 0
237 unit: 2
238 start_connected: 0
239 state: NOT_CONNECTED
240 type: SATA
241 cpu:
242 cores_per_socket: 1
243 count: 1
244 hot_add_enabled: 0
245 hot_remove_enabled: 0
246 disks:
247 '16000':
248 backing:
249 type: VMDK_FILE
250 vmdk_file: '[local] test_vm1/rhel-8.5.vmdk'
251 capacity: 16106127360
252 label: Hard disk 1
253 sata:
254 bus: 0
255 unit: 0
256 type: SATA
257 '16001':
258 backing:
259 type: VMDK_FILE
260 vmdk_file: '[local] test_vm1_1/second_disk.vmdk'
261 capacity: 32000000000
262 label: Hard disk 2
263 sata:
264 bus: 0
265 unit: 1
266 type: SATA
267 floppies: {}
268 guest_OS: RHEL_7_64
269 hardware:
270 upgrade_policy: NEVER
271 upgrade_status: NONE
272 version: VMX_11
273 identity:
274 bios_uuid: 4231943a-a1b5-9d24-1e05-d447e9ff0396
275 instance_uuid: 5031e081-01a7-d61a-31f8-4bc54057ec60
276 name: test_vm1
277 instant_clone_frozen: 0
278 memory:
279 hot_add_enabled: 1
280 size_MiB: 1024
281 name: test_vm1
282 nics:
283 '4000':
284 allow_guest_control: 0
285 backing:
286 network: network-1041
287 network_name: VM Network
288 type: STANDARD_PORTGROUP
289 label: Network adapter 1
290 mac_address: 00:50:56:b1:22:7d
291 mac_type: ASSIGNED
292 pci_slot_number: 160
293 start_connected: 0
294 state: NOT_CONNECTED
295 type: VMXNET3
296 upt_compatibility_enabled: 0
297 wake_on_lan_enabled: 0
298 nvme_adapters: {}
299 parallel_ports: {}
300 power_state: POWERED_OFF
301 sata_adapters:
302 '15000':
303 bus: 0
304 label: SATA controller 0
305 pci_slot_number: 32
306 type: AHCI
307 scsi_adapters: {}
308 serial_ports: {}
309 type: dict
310 """
311
312
313 # This structure describes the format of the data expected by the end-points
314 PAYLOAD_FORMAT = {
315 "get": {"query": {}, "body": {}, "path": {"vm": "vm"}},
316 "list": {
317 "query": {
318 "clusters": "clusters",
319 "datacenters": "datacenters",
320 "folders": "folders",
321 "hosts": "hosts",
322 "names": "names",
323 "power_states": "power_states",
324 "resource_pools": "resource_pools",
325 "vms": "vms",
326 },
327 "body": {},
328 "path": {},
329 },
330 } # pylint: disable=line-too-long
331
332 from ansible.module_utils.basic import env_fallback
333 import os
334
335 if os.getenv("VMWARE_ENABLE_TURBO", False):
336 try:
337 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
338 AnsibleTurboModule as AnsibleModule,
339 )
340
341 AnsibleModule.collection_name = "vmware.vmware_rest"
342 except ImportError:
343 from ansible.module_utils.basic import AnsibleModule
344 else:
345 from ansible.module_utils.basic import AnsibleModule
346
347 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
348 build_full_device_list,
349 exists,
350 gen_args,
351 open_session,
352 session_timeout,
353 update_changed_flag,
354 )
355
356
357 def prepare_argument_spec():
358 argument_spec = {
359 "vcenter_hostname": dict(
360 type="str",
361 required=True,
362 fallback=(env_fallback, ["VMWARE_HOST"]),
363 ),
364 "vcenter_username": dict(
365 type="str",
366 required=True,
367 fallback=(env_fallback, ["VMWARE_USER"]),
368 ),
369 "vcenter_password": dict(
370 type="str",
371 required=True,
372 no_log=True,
373 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
374 ),
375 "vcenter_validate_certs": dict(
376 type="bool",
377 required=False,
378 default=True,
379 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
380 ),
381 "vcenter_rest_log_file": dict(
382 type="str",
383 required=False,
384 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
385 ),
386 "session_timeout": dict(
387 type="float",
388 required=False,
389 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
390 ),
391 }
392
393 argument_spec["clusters"] = {"type": "list", "elements": "str"}
394 argument_spec["datacenters"] = {
395 "aliases": ["filter_datacenters"],
396 "type": "list",
397 "elements": "str",
398 }
399 argument_spec["folders"] = {
400 "aliases": ["filter_folders"],
401 "type": "list",
402 "elements": "str",
403 }
404 argument_spec["hosts"] = {"type": "list", "elements": "str"}
405 argument_spec["names"] = {
406 "aliases": ["filter_names"],
407 "type": "list",
408 "elements": "str",
409 }
410 argument_spec["power_states"] = {"type": "list", "elements": "str"}
411 argument_spec["resource_pools"] = {"type": "list", "elements": "str"}
412 argument_spec["vm"] = {"type": "str"}
413 argument_spec["vms"] = {"type": "list", "elements": "str"}
414
415 return argument_spec
416
417
418 async def main():
419 required_if = list([])
420
421 module_args = prepare_argument_spec()
422 module = AnsibleModule(
423 argument_spec=module_args, required_if=required_if, supports_check_mode=True
424 )
425 if not module.params["vcenter_hostname"]:
426 module.fail_json("vcenter_hostname cannot be empty")
427 if not module.params["vcenter_username"]:
428 module.fail_json("vcenter_username cannot be empty")
429 if not module.params["vcenter_password"]:
430 module.fail_json("vcenter_password cannot be empty")
431 try:
432 session = await open_session(
433 vcenter_hostname=module.params["vcenter_hostname"],
434 vcenter_username=module.params["vcenter_username"],
435 vcenter_password=module.params["vcenter_password"],
436 validate_certs=module.params["vcenter_validate_certs"],
437 log_file=module.params["vcenter_rest_log_file"],
438 )
439 except Exception as err:
440 if hasattr(err, "get_message"):
441 module.fail_json(err.get_message())
442 else:
443 module.fail_json(str(err))
444 result = await entry_point(module, session)
445 module.exit_json(**result)
446
447
448 # template: info_list_and_get_module.j2
449 def build_url(params):
450 import yarl
451
452 if params.get("vm"):
453 _in_query_parameters = PAYLOAD_FORMAT["get"]["query"].keys()
454 return yarl.URL(
455 ("https://{vcenter_hostname}" "/api/vcenter/vm/").format(**params)
456 + params["vm"]
457 + gen_args(params, _in_query_parameters),
458 encoded=True,
459 )
460 _in_query_parameters = PAYLOAD_FORMAT["list"]["query"].keys()
461 return yarl.URL(
462 ("https://{vcenter_hostname}" "/api/vcenter/vm").format(**params)
463 + gen_args(params, _in_query_parameters),
464 encoded=True,
465 )
466
467
468 async def entry_point(module, session):
469 url = build_url(module.params)
470 async with session.get(url, **session_timeout(module.params)) as resp:
471 _json = await resp.json()
472
473 if "value" not in _json: # 7.0.2+
474 _json = {"value": _json}
475
476 if module.params.get("vm"):
477 _json["id"] = module.params.get("vm")
478 elif module.params.get("label"): # TODO extend the list of filter
479 _json = await exists(module.params, session, str(url))
480 elif (
481 isinstance(_json["value"], list)
482 and len(_json["value"]) > 0
483 and isinstance(_json["value"][0], str)
484 ):
485 # this is a list of id, we fetch the details
486 full_device_list = await build_full_device_list(session, str(url), _json)
487 _json = {"value": [i["value"] for i in full_device_list]}
488
489 return await update_changed_flag(_json, resp.status, "get")
490
491
492 if __name__ == "__main__":
493 import asyncio
494
495 current_loop = asyncio.new_event_loop()
496 try:
497 asyncio.set_event_loop(current_loop)
498 current_loop.run_until_complete(main())
499 finally:
500 current_loop.close()