Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_vm_tools.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
12 short_description: Update the properties of VMware Tools.
13 description: Update the properties of VMware Tools.
14 options:
15 command_line_options:
16 description:
17 - Command line options passed to the installer to modify the installation
18 procedure for Tools.
19 - Set if any additional options are desired.
20 type: str
21 session_timeout:
22 description:
23 - 'Timeout settings for client session. '
24 - 'The maximal number of seconds for the whole operation including connection
25 establishment, request sending and response. '
26 - The default value is 300s.
27 type: float
28 version_added: 2.1.0
29 state:
30 choices:
31 - present
32 - upgrade
33 default: present
34 description: []
35 type: str
36 upgrade_policy:
37 choices:
38 - MANUAL
39 - UPGRADE_AT_POWER_CYCLE
40 description:
41 - The I(upgrade_policy) enumerated type defines when Tools are auto-upgraded
42 for a virtual machine.
43 type: str
44 vcenter_hostname:
45 description:
46 - The hostname or IP address of the vSphere vCenter
47 - If the value is not specified in the task, the value of environment variable
48 C(VMWARE_HOST) will be used instead.
49 required: true
50 type: str
51 vcenter_password:
52 description:
53 - The vSphere vCenter password
54 - If the value is not specified in the task, the value of environment variable
55 C(VMWARE_PASSWORD) will be used instead.
56 required: true
57 type: str
58 vcenter_rest_log_file:
59 description:
60 - 'You can use this optional parameter to set the location of a log file. '
61 - 'This file will be used to record the HTTP REST interaction. '
62 - 'The file will be stored on the host that runs the module. '
63 - 'If the value is not specified in the task, the value of '
64 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
65 type: str
66 vcenter_username:
67 description:
68 - The vSphere vCenter username
69 - If the value is not specified in the task, the value of environment variable
70 C(VMWARE_USER) will be used instead.
71 required: true
72 type: str
73 vcenter_validate_certs:
74 default: true
75 description:
76 - Allows connection when SSL certificates are not valid. Set to C(false) when
77 certificates are not trusted.
78 - If the value is not specified in the task, the value of environment variable
79 C(VMWARE_VALIDATE_CERTS) will be used instead.
80 type: bool
81 vm:
82 description:
83 - Identifier of the virtual machine.
84 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_info).
85 This parameter is mandatory.
86 required: true
87 type: str
88 author:
89 - Ansible Cloud Team (@ansible-collections)
90 version_added: 0.1.0
91 requirements:
92 - vSphere 7.0.3 or greater
93 - python >= 3.6
94 - aiohttp
95 notes:
96 - Tested on vSphere 7.0.3
97 """
98
99 EXAMPLES = r"""
100 - name: Look up the VM called test_vm1 in the inventory
101 register: search_result
102 vmware.vmware_rest.vcenter_vm_info:
103 filter_names:
104 - test_vm1
105
106 - name: Collect information about a specific VM
107 vmware.vmware_rest.vcenter_vm_info:
108 vm: '{{ search_result.value[0].vm }}'
109 register: test_vm1_info
110
111 - name: Retrive vm-tools information
112 vmware.vmware_rest.vcenter_vm_tools:
113 vm: '{{ test_vm1_info.id }}'
114 register: _result
115
116 - name: Change vm-tools upgrade policy to UPGRADE_AT_POWER_CYCLE
117 vmware.vmware_rest.vcenter_vm_tools:
118 vm: '{{ test_vm1_info.id }}'
119 upgrade_policy: UPGRADE_AT_POWER_CYCLE
120 register: _result
121
122 - name: Change vm-tools upgrade policy to MANUAL
123 vmware.vmware_rest.vcenter_vm_tools:
124 vm: '{{ test_vm1_info.id }}'
125 upgrade_policy: MANUAL
126 register: _result
127 """
128 RETURN = r"""
129 # content generated by the update_return_section callback# task: Retrive vm-tools information
130 id:
131 description: moid of the resource
132 returned: On success
133 sample: null
134 type: dict
135 value:
136 description: Retrive vm-tools information
137 returned: On success
138 sample:
139 auto_update_supported: 0
140 install_attempt_count: 0
141 install_type: OPEN_VM_TOOLS
142 run_state: RUNNING
143 upgrade_policy: MANUAL
144 version: '10346'
145 version_number: 10346
146 version_status: UNMANAGED
147 type: dict
148 """
149
150
151 # This structure describes the format of the data expected by the end-points
152 PAYLOAD_FORMAT = {
153 "update": {
154 "query": {},
155 "body": {"upgrade_policy": "upgrade_policy"},
156 "path": {"vm": "vm"},
157 },
158 "upgrade": {
159 "query": {},
160 "body": {"command_line_options": "command_line_options"},
161 "path": {"vm": "vm"},
162 },
163 } # pylint: disable=line-too-long
164
165 from ansible.module_utils.basic import env_fallback
166 import os
167
168 if os.getenv("VMWARE_ENABLE_TURBO", False):
169 try:
170 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
171 AnsibleTurboModule as AnsibleModule,
172 )
173
174 AnsibleModule.collection_name = "vmware.vmware_rest"
175 except ImportError:
176 from ansible.module_utils.basic import AnsibleModule
177 else:
178 from ansible.module_utils.basic import AnsibleModule
179
180 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
181 exists,
182 gen_args,
183 get_subdevice_type,
184 open_session,
185 prepare_payload,
186 session_timeout,
187 update_changed_flag,
188 )
189
190
191 def prepare_argument_spec():
192 argument_spec = {
193 "vcenter_hostname": dict(
194 type="str",
195 required=True,
196 fallback=(env_fallback, ["VMWARE_HOST"]),
197 ),
198 "vcenter_username": dict(
199 type="str",
200 required=True,
201 fallback=(env_fallback, ["VMWARE_USER"]),
202 ),
203 "vcenter_password": dict(
204 type="str",
205 required=True,
206 no_log=True,
207 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
208 ),
209 "vcenter_validate_certs": dict(
210 type="bool",
211 required=False,
212 default=True,
213 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
214 ),
215 "vcenter_rest_log_file": dict(
216 type="str",
217 required=False,
218 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
219 ),
220 "session_timeout": dict(
221 type="float",
222 required=False,
223 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
224 ),
225 }
226
227 argument_spec["command_line_options"] = {"type": "str"}
228 argument_spec["state"] = {
229 "type": "str",
230 "choices": ["present", "upgrade"],
231 "default": "present",
232 }
233 argument_spec["upgrade_policy"] = {
234 "type": "str",
235 "choices": ["MANUAL", "UPGRADE_AT_POWER_CYCLE"],
236 }
237 argument_spec["vm"] = {"required": True, "type": "str"}
238
239 return argument_spec
240
241
242 async def main():
243 required_if = list([])
244
245 module_args = prepare_argument_spec()
246 module = AnsibleModule(
247 argument_spec=module_args, required_if=required_if, supports_check_mode=False
248 )
249 if not module.params["vcenter_hostname"]:
250 module.fail_json("vcenter_hostname cannot be empty")
251 if not module.params["vcenter_username"]:
252 module.fail_json("vcenter_username cannot be empty")
253 if not module.params["vcenter_password"]:
254 module.fail_json("vcenter_password cannot be empty")
255 try:
256 session = await open_session(
257 vcenter_hostname=module.params["vcenter_hostname"],
258 vcenter_username=module.params["vcenter_username"],
259 vcenter_password=module.params["vcenter_password"],
260 validate_certs=module.params["vcenter_validate_certs"],
261 log_file=module.params["vcenter_rest_log_file"],
262 )
263 except Exception as err:
264 if hasattr(err, "get_message"):
265 module.fail_json(err.get_message())
266 else:
267 module.fail_json(str(err))
268 result = await entry_point(module, session)
269 module.exit_json(**result)
270
271
272 # template: default_module.j2
273 def build_url(params):
274 return ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/tools").format(**params)
275
276
277 async def entry_point(module, session):
278
279 if module.params["state"] == "present":
280 if "_create" in globals():
281 operation = "create"
282 else:
283 operation = "update"
284 elif module.params["state"] == "absent":
285 operation = "delete"
286 else:
287 operation = module.params["state"]
288
289 func = globals()["_" + operation]
290
291 return await func(module.params, session)
292
293
294 async def _update(params, session):
295 payload = prepare_payload(params, PAYLOAD_FORMAT["update"])
296 _url = ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/tools").format(**params)
297 async with session.get(_url, **session_timeout(params)) as resp:
298 _json = await resp.json()
299 if "value" in _json:
300 value = _json["value"]
301 else: # 7.0.2 and greater
302 value = _json
303 for k, v in value.items():
304 if k in payload:
305 if isinstance(payload[k], dict) and isinstance(v, dict):
306 to_delete = True
307 for _k in list(payload[k].keys()):
308 if payload[k][_k] != v.get(_k):
309 to_delete = False
310 if to_delete:
311 del payload[k]
312 elif payload[k] == v:
313 del payload[k]
314 elif payload[k] == {}:
315 del payload[k]
316
317 if payload == {} or payload == {"spec": {}}:
318 # Nothing has changed
319 if "value" not in _json: # 7.0.2
320 _json = {"value": _json}
321 _json["id"] = params.get("None")
322 return await update_changed_flag(_json, resp.status, "get")
323 async with session.patch(_url, json=payload, **session_timeout(params)) as resp:
324 try:
325 if resp.headers["Content-Type"] == "application/json":
326 _json = await resp.json()
327 except KeyError:
328 _json = {}
329 if "value" not in _json: # 7.0.2
330 _json = {"value": _json}
331
332 # e.g: content_configuration
333 if not _json and resp.status == 204:
334 async with session.get(_url, **session_timeout(params)) as resp_get:
335 _json_get = await resp_get.json()
336 if _json_get:
337 _json = _json_get
338
339 _json["id"] = params.get("None")
340 return await update_changed_flag(_json, resp.status, "update")
341
342
343 async def _upgrade(params, session):
344 _in_query_parameters = PAYLOAD_FORMAT["upgrade"]["query"].keys()
345 payload = prepare_payload(params, PAYLOAD_FORMAT["upgrade"])
346 subdevice_type = get_subdevice_type("/api/vcenter/vm/{vm}/tools?action=upgrade")
347 if subdevice_type and not params[subdevice_type]:
348 _json = await exists(params, session, build_url(params))
349 if _json:
350 params[subdevice_type] = _json["id"]
351 _url = (
352 "https://{vcenter_hostname}"
353 # aa
354 "/api/vcenter/vm/{vm}/tools?action=upgrade"
355 ).format(**params) + gen_args(params, _in_query_parameters)
356 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
357 try:
358 if resp.headers["Content-Type"] == "application/json":
359 _json = await resp.json()
360 except KeyError:
361 _json = {}
362 if "value" not in _json: # 7.0.2
363 _json = {"value": _json}
364
365 return await update_changed_flag(_json, resp.status, "upgrade")
366
367
368 if __name__ == "__main__":
369 import asyncio
370
371 current_loop = asyncio.new_event_loop()
372 try:
373 asyncio.set_event_loop(current_loop)
374 current_loop.run_until_complete(main())
375 finally:
376 current_loop.close()