Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_vm_tools_installer.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_tools_installer
12 short_description: Connects the VMware Tools CD installer as a CD-ROM for the guest
13 operating system
14 description: Connects the VMware Tools CD installer as a CD-ROM for the guest operating
15 system. On Windows guest operating systems with autorun, this should cause the
16 installer to initiate the Tools installation which will need user input to complete.
17 On other (non-Windows) guest operating systems this will make the Tools installation
18 available, and a a user will need to do guest-specific actions. On Linux, this
19 includes opening an archive and running the installer. To monitor the status of
20 the Tools install, clients should check the Tools.Info.version-status and Tools.Info.run-state
21 from Tools.get
22 options:
23 session_timeout:
24 description:
25 - 'Timeout settings for client session. '
26 - 'The maximal number of seconds for the whole operation including connection
27 establishment, request sending and response. '
28 - The default value is 300s.
29 type: float
30 version_added: 2.1.0
31 state:
32 choices:
33 - connect
34 - disconnect
35 description: []
36 required: true
37 type: str
38 vcenter_hostname:
39 description:
40 - The hostname or IP address of the vSphere vCenter
41 - If the value is not specified in the task, the value of environment variable
42 C(VMWARE_HOST) will be used instead.
43 required: true
44 type: str
45 vcenter_password:
46 description:
47 - The vSphere vCenter password
48 - If the value is not specified in the task, the value of environment variable
49 C(VMWARE_PASSWORD) will be used instead.
50 required: true
51 type: str
52 vcenter_rest_log_file:
53 description:
54 - 'You can use this optional parameter to set the location of a log file. '
55 - 'This file will be used to record the HTTP REST interaction. '
56 - 'The file will be stored on the host that runs the module. '
57 - 'If the value is not specified in the task, the value of '
58 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
59 type: str
60 vcenter_username:
61 description:
62 - The vSphere vCenter username
63 - If the value is not specified in the task, the value of environment variable
64 C(VMWARE_USER) will be used instead.
65 required: true
66 type: str
67 vcenter_validate_certs:
68 default: true
69 description:
70 - Allows connection when SSL certificates are not valid. Set to C(false) when
71 certificates are not trusted.
72 - If the value is not specified in the task, the value of environment variable
73 C(VMWARE_VALIDATE_CERTS) will be used instead.
74 type: bool
75 vm:
76 description:
77 - Virtual machine ID
78 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_info).
79 This parameter is mandatory.
80 required: true
81 type: str
82 author:
83 - Ansible Cloud Team (@ansible-collections)
84 version_added: 0.1.0
85 requirements:
86 - vSphere 7.0.3 or greater
87 - python >= 3.6
88 - aiohttp
89 notes:
90 - Tested on vSphere 7.0.3
91 """
92
93 EXAMPLES = r"""
94 - name: Create a VM
95 vmware.vmware_rest.vcenter_vm:
96 placement:
97 cluster: "{{ lookup('vmware.vmware_rest.cluster_moid', '/my_dc/host/my_cluster') }}"
98 datastore: "{{ lookup('vmware.vmware_rest.datastore_moid', '/my_dc/datastore/local') }}"
99 folder: "{{ lookup('vmware.vmware_rest.folder_moid', '/my_dc/vm') }}"
100 resource_pool: "{{ lookup('vmware.vmware_rest.resource_pool_moid', '/my_dc/host/my_cluster/Resources') }}"
101 name: test_vm1
102 guest_OS: RHEL_7_64
103 hardware_version: VMX_11
104 memory:
105 hot_add_enabled: true
106 size_MiB: 1024
107 disks:
108 - type: SATA
109 backing:
110 type: VMDK_FILE
111 vmdk_file: '[local] test_vm1/{{ disk_name }}.vmdk'
112 - type: SATA
113 new_vmdk:
114 name: second_disk
115 capacity: 32000000000
116 cdroms:
117 - type: SATA
118 sata:
119 bus: 0
120 unit: 2
121 nics:
122 - backing:
123 type: STANDARD_PORTGROUP
124 network: "{{ lookup('vmware.vmware_rest.network_moid', '/my_dc/network/VM Network') }}"
125 register: my_vm
126
127 - name: Update the vm-tools
128 vmware.vmware_rest.vcenter_vm_tools_installer:
129 vm: '{{ my_vm.id }}'
130 state: connect
131 """
132 RETURN = r"""
133 # content generated by the update_return_section callback# task: Update the vm-tools
134 value:
135 description: Update the vm-tools
136 returned: On success
137 sample: {}
138 type: dict
139 """
140
141
142 # This structure describes the format of the data expected by the end-points
143 PAYLOAD_FORMAT = {
144 "connect": {"query": {}, "body": {}, "path": {"vm": "vm"}},
145 "disconnect": {"query": {}, "body": {}, "path": {"vm": "vm"}},
146 } # pylint: disable=line-too-long
147
148 from ansible.module_utils.basic import env_fallback
149 import os
150
151 if os.getenv("VMWARE_ENABLE_TURBO", False):
152 try:
153 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
154 AnsibleTurboModule as AnsibleModule,
155 )
156
157 AnsibleModule.collection_name = "vmware.vmware_rest"
158 except ImportError:
159 from ansible.module_utils.basic import AnsibleModule
160 else:
161 from ansible.module_utils.basic import AnsibleModule
162
163 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
164 exists,
165 gen_args,
166 get_subdevice_type,
167 open_session,
168 prepare_payload,
169 session_timeout,
170 update_changed_flag,
171 )
172
173
174 def prepare_argument_spec():
175 argument_spec = {
176 "vcenter_hostname": dict(
177 type="str",
178 required=True,
179 fallback=(env_fallback, ["VMWARE_HOST"]),
180 ),
181 "vcenter_username": dict(
182 type="str",
183 required=True,
184 fallback=(env_fallback, ["VMWARE_USER"]),
185 ),
186 "vcenter_password": dict(
187 type="str",
188 required=True,
189 no_log=True,
190 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
191 ),
192 "vcenter_validate_certs": dict(
193 type="bool",
194 required=False,
195 default=True,
196 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
197 ),
198 "vcenter_rest_log_file": dict(
199 type="str",
200 required=False,
201 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
202 ),
203 "session_timeout": dict(
204 type="float",
205 required=False,
206 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
207 ),
208 }
209
210 argument_spec["state"] = {
211 "required": True,
212 "type": "str",
213 "choices": ["connect", "disconnect"],
214 }
215 argument_spec["vm"] = {"required": True, "type": "str"}
216
217 return argument_spec
218
219
220 async def main():
221 required_if = list([])
222
223 module_args = prepare_argument_spec()
224 module = AnsibleModule(
225 argument_spec=module_args, required_if=required_if, supports_check_mode=False
226 )
227 if not module.params["vcenter_hostname"]:
228 module.fail_json("vcenter_hostname cannot be empty")
229 if not module.params["vcenter_username"]:
230 module.fail_json("vcenter_username cannot be empty")
231 if not module.params["vcenter_password"]:
232 module.fail_json("vcenter_password cannot be empty")
233 try:
234 session = await open_session(
235 vcenter_hostname=module.params["vcenter_hostname"],
236 vcenter_username=module.params["vcenter_username"],
237 vcenter_password=module.params["vcenter_password"],
238 validate_certs=module.params["vcenter_validate_certs"],
239 log_file=module.params["vcenter_rest_log_file"],
240 )
241 except Exception as err:
242 if hasattr(err, "get_message"):
243 module.fail_json(err.get_message())
244 else:
245 module.fail_json(str(err))
246 result = await entry_point(module, session)
247 module.exit_json(**result)
248
249
250 # template: default_module.j2
251 def build_url(params):
252 return ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/tools/installer").format(
253 **params
254 )
255
256
257 async def entry_point(module, session):
258
259 if module.params["state"] == "present":
260 if "_create" in globals():
261 operation = "create"
262 else:
263 operation = "update"
264 elif module.params["state"] == "absent":
265 operation = "delete"
266 else:
267 operation = module.params["state"]
268
269 func = globals()["_" + operation]
270
271 return await func(module.params, session)
272
273
274 async def _connect(params, session):
275 _in_query_parameters = PAYLOAD_FORMAT["connect"]["query"].keys()
276 payload = prepare_payload(params, PAYLOAD_FORMAT["connect"])
277 subdevice_type = get_subdevice_type(
278 "/api/vcenter/vm/{vm}/tools/installer?action=connect"
279 )
280 if subdevice_type and not params[subdevice_type]:
281 _json = await exists(params, session, build_url(params))
282 if _json:
283 params[subdevice_type] = _json["id"]
284 _url = (
285 "https://{vcenter_hostname}"
286 # aa
287 "/api/vcenter/vm/{vm}/tools/installer?action=connect"
288 ).format(**params) + gen_args(params, _in_query_parameters)
289 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
290 try:
291 if resp.headers["Content-Type"] == "application/json":
292 _json = await resp.json()
293 except KeyError:
294 _json = {}
295 if "value" not in _json: # 7.0.2
296 _json = {"value": _json}
297
298 return await update_changed_flag(_json, resp.status, "connect")
299
300
301 async def _disconnect(params, session):
302 _in_query_parameters = PAYLOAD_FORMAT["disconnect"]["query"].keys()
303 payload = prepare_payload(params, PAYLOAD_FORMAT["disconnect"])
304 subdevice_type = get_subdevice_type(
305 "/api/vcenter/vm/{vm}/tools/installer?action=disconnect"
306 )
307 if subdevice_type and not params[subdevice_type]:
308 _json = await exists(params, session, build_url(params))
309 if _json:
310 params[subdevice_type] = _json["id"]
311 _url = (
312 "https://{vcenter_hostname}"
313 # aa
314 "/api/vcenter/vm/{vm}/tools/installer?action=disconnect"
315 ).format(**params) + gen_args(params, _in_query_parameters)
316 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
317 try:
318 if resp.headers["Content-Type"] == "application/json":
319 _json = await resp.json()
320 except KeyError:
321 _json = {}
322 if "value" not in _json: # 7.0.2
323 _json = {"value": _json}
324
325 return await update_changed_flag(_json, resp.status, "disconnect")
326
327
328 if __name__ == "__main__":
329 import asyncio
330
331 current_loop = asyncio.new_event_loop()
332 try:
333 asyncio.set_event_loop(current_loop)
334 current_loop.run_until_complete(main())
335 finally:
336 current_loop.close()