Debian Codegraph @

ansible_collections/community/vmware/plugins/connection/vmware_tools.py

raw
1 # Copyright: (c) 2018, Deric Crago <[email protected]>
2 # Copyright: (c) 2018, Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9 DOCUMENTATION = r'''
10 author:
11 - Deric Crago (@dericcrago) <[email protected]>
12 name: vmware_tools
13 short_description: Execute tasks inside a VM via VMware Tools
14 description:
15 - Use VMware tools to run tasks in, or put/fetch files to guest operating systems running in VMware infrastructure.
16 - In case of Windows VMs, set C(ansible_shell_type) to C(powershell).
17 - Does not work with C(become).
18 requirements:
19 - requests (Python library)
20 options:
21 vmware_host:
22 description:
23 - FQDN or IP Address for the connection (vCenter or ESXi Host).
24 env:
25 - name: VI_SERVER
26 - name: VMWARE_HOST
27 vars:
28 - name: ansible_host
29 - name: ansible_vmware_host
30 required: true
31 vmware_user:
32 description:
33 - Username for the connection.
34 - "Requires the following permissions on the VM:
35 - VirtualMachine.GuestOperations.Execute
36 - VirtualMachine.GuestOperations.Modify
37 - VirtualMachine.GuestOperations.Query"
38 env:
39 - name: VI_USERNAME
40 - name: VMWARE_USER
41 vars:
42 - name: ansible_vmware_user
43 required: true
44 vmware_password:
45 description:
46 - Password for the connection.
47 env:
48 - name: VI_PASSWORD
49 - name: VMWARE_PASSWORD
50 vars:
51 - name: ansible_vmware_password
52 required: true
53 vmware_port:
54 description:
55 - Port for the connection.
56 env:
57 - name: VI_PORTNUMBER
58 - name: VMWARE_PORT
59 vars:
60 - name: ansible_port
61 - name: ansible_vmware_port
62 required: false
63 default: 443
64 validate_certs:
65 description:
66 - Verify SSL for the connection.
67 - "Note: This will validate certs for both O(vmware_host) and the ESXi host running the VM."
68 env:
69 - name: VMWARE_VALIDATE_CERTS
70 vars:
71 - name: ansible_vmware_validate_certs
72 default: true
73 type: bool
74 vm_path:
75 description:
76 - Mutually exclusive with O(vm_uuid)
77 - VM path absolute to the connection.
78 - "vCenter Example: V(Datacenter/vm/Discovered virtual machine/testVM)."
79 - "ESXi Host Example: V(ha-datacenter/vm/testVM)."
80 - Must include VM name, appended to 'folder' as would be passed to M(community.vmware.vmware_guest).
81 - Needs to include I(vm) between the Datacenter and the rest of the VM path.
82 - Datacenter default value for ESXi server is C(ha-datacenter).
83 - Folder I(vm) is not visible in the vSphere Web Client but necessary for VMware API to work.
84 vars:
85 - name: ansible_vmware_guest_path
86 required: false
87 vm_uuid:
88 description:
89 - UUID of the virtual machine
90 - Mutually exclusive with O(vm_path)
91 vars:
92 - name: ansible_vmware_guest_uuid
93 required: false
94 vm_user:
95 description:
96 - VM username.
97 - C(ansible_vmware_tools_user) is used for connecting to the VM.
98 - C(ansible_user) is used by Ansible on the VM.
99 vars:
100 - name: ansible_user
101 - name: ansible_vmware_tools_user
102 required: true
103 vm_password:
104 description:
105 - Password for the user in guest operating system.
106 vars:
107 - name: ansible_password
108 - name: ansible_vmware_tools_password
109 required: true
110 exec_command_sleep_interval:
111 description:
112 - Time in seconds to sleep between execution of command.
113 vars:
114 - name: ansible_vmware_tools_exec_command_sleep_interval
115 default: 0.5
116 type: float
117 file_chunk_size:
118 description:
119 - File chunk size.
120 - "(Applicable when writing a file to disk, example: using the M(ansible.builtin.fetch) module.)"
121 vars:
122 - name: ansible_vmware_tools_file_chunk_size
123 default: 128
124 type: integer
125 executable:
126 description:
127 - shell to use for execution inside container
128 default: /bin/sh
129 ini:
130 - section: defaults
131 key: executable
132 env:
133 - name: ANSIBLE_EXECUTABLE
134 vars:
135 - name: ansible_executable
136 - name: ansible_vmware_tools_executable
137 '''
138
139 example = r'''
140 # example vars.yml
141 ---
142 ansible_connection: vmware_tools
143 ansible_user: "{{ ansible_vmware_tools_user }}"
144
145 ansible_vmware_host: vcenter.example.com
146 ansible_vmware_user: [email protected]
147 ansible_vmware_password: Secr3tP4ssw0rd!12
148 ansible_vmware_validate_certs: false # default is true
149
150 # vCenter Connection VM Path Example
151 ansible_vmware_guest_path: DATACENTER/vm/FOLDER/{{ inventory_hostname }}
152 # ESXi Connection VM Path Example
153 ansible_vmware_guest_path: ha-datacenter/vm/{{ inventory_hostname }}
154
155 ansible_vmware_tools_user: root
156 ansible_vmware_tools_password: MyR00tPassw0rD
157
158 # if the target VM guest is Windows set the 'ansible_shell_type' to 'powershell'
159 ansible_shell_type: powershell
160
161
162 # example playbook_linux.yml
163 ---
164 - name: Test VMware Tools Connection Plugin for Linux
165 hosts: linux
166 tasks:
167 - command: whoami
168
169 - ping:
170
171 - copy:
172 src: foo
173 dest: /home/user/foo
174
175 - fetch:
176 src: /home/user/foo
177 dest: linux-foo
178 flat: true
179
180 - file:
181 path: /home/user/foo
182 state: absent
183
184
185 # example playbook_windows.yml
186 ---
187 - name: Test VMware Tools Connection Plugin for Windows
188 hosts: windows
189 tasks:
190 - win_command: whoami
191
192 - win_ping:
193
194 - win_copy:
195 src: foo
196 dest: C:\Users\user\foo
197
198 - fetch:
199 src: C:\Users\user\foo
200 dest: windows-foo
201 flat: true
202
203 - win_file:
204 path: C:\Users\user\foo
205 state: absent
206 '''
207
208 import re
209 from os.path import exists, getsize
210 from socket import gaierror
211 from ssl import SSLError
212 from time import sleep
213 import traceback
214
215 REQUESTS_IMP_ERR = None
216 PYVMOMI_IMP_ERR = None
217 try:
218 import requests
219 HAS_REQUESTS = True
220 except ImportError:
221 REQUESTS_IMP_ERR = traceback.format_exc()
222 HAS_REQUESTS = False
223
224 try:
225 from requests.packages import urllib3
226 HAS_URLLIB3 = True
227 except ImportError:
228 try:
229 import urllib3
230 HAS_URLLIB3 = True
231 except ImportError:
232 HAS_URLLIB3 = False
233
234 from ansible.errors import AnsibleError, AnsibleFileNotFound, AnsibleConnectionFailure
235 from ansible.module_utils.common.text.converters import to_bytes, to_native
236 from ansible.plugins.connection import ConnectionBase
237 from ansible.module_utils.basic import missing_required_lib
238
239 try:
240 from pyVim.connect import Disconnect, SmartConnect
241 from pyVmomi import vim, vmodl
242
243 HAS_PYVMOMI = True
244 except ImportError:
245 HAS_PYVMOMI = False
246 PYVMOMI_IMP_ERR = traceback.format_exc()
247
248
249 class Connection(ConnectionBase):
250 """VMware Tools Connection."""
251
252 transport = 'community.vmware.vmware_tools'
253
254 @property
255 def vmware_host(self):
256 """Read-only property holding the connection address."""
257 return self.get_option("vmware_host")
258
259 @property
260 def validate_certs(self):
261 """Read-only property holding whether the connection should validate certs."""
262 return self.get_option("validate_certs")
263
264 @property
265 def authManager(self):
266 """Guest Authentication Manager."""
267 return self._si.content.guestOperationsManager.authManager
268
269 @property
270 def fileManager(self):
271 """Guest File Manager."""
272 return self._si.content.guestOperationsManager.fileManager
273
274 @property
275 def processManager(self):
276 """Guest Process Manager."""
277 return self._si.content.guestOperationsManager.processManager
278
279 @property
280 def windowsGuest(self):
281 """Return if VM guest family is windows."""
282 return self.vm.guest.guestFamily == "windowsGuest"
283
284 def __init__(self, *args, **kwargs):
285 """init."""
286 super(Connection, self).__init__(*args, **kwargs)
287 if hasattr(self, "_shell") and self._shell.SHELL_FAMILY == "powershell":
288 self.module_implementation_preferences = (".ps1", ".exe", "")
289 self.become_methods = ["runas"]
290 self.allow_executable = False
291 self.has_pipelining = False
292 self.allow_extras = True
293 self._si = None
294
295 def _establish_connection(self):
296 connection_kwargs = {
297 "host": self.vmware_host,
298 "user": self.get_option("vmware_user"),
299 "pwd": self.get_option("vmware_password"),
300 "port": self.get_option("vmware_port"),
301 }
302
303 if not self.validate_certs:
304 if HAS_URLLIB3:
305 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
306 connection_kwargs['disableSslCertValidation'] = True
307
308 try:
309 self._si = SmartConnect(**connection_kwargs)
310 except SSLError:
311 raise AnsibleError("SSL Error: Certificate verification failed.")
312 except (gaierror):
313 raise AnsibleError("Connection Error: Unable to connect to '%s'." % to_native(connection_kwargs["host"]))
314 except vim.fault.InvalidLogin as e:
315 raise AnsibleError("Connection Login Error: %s" % to_native(e.msg))
316
317 def _establish_vm(self, check_vm_credentials=True):
318 searchIndex = self._si.content.searchIndex
319 self.vm = None
320 if self.get_option("vm_path") is not None:
321 self.vm = searchIndex.FindByInventoryPath(self.get_option("vm_path"))
322 if self.vm is None:
323 raise AnsibleError("Unable to find VM by path '%s'" % to_native(self.get_option("vm_path")))
324 elif self.get_option("vm_uuid") is not None:
325 self.vm = searchIndex.FindByUuid(None, self.get_option("vm_uuid"), True)
326 if self.vm is None:
327 raise AnsibleError("Unable to find VM by uuid '%s'" % to_native(self.get_option("vm_uuid")))
328
329 self.vm_auth = vim.NamePasswordAuthentication(
330 username=self.get_option("vm_user"), password=self.get_option("vm_password"), interactiveSession=False
331 )
332
333 try:
334 if check_vm_credentials:
335 self.authManager.ValidateCredentialsInGuest(vm=self.vm, auth=self.vm_auth)
336 except vim.fault.InvalidPowerState as e:
337 raise AnsibleError("VM Power State Error: %s" % to_native(e.msg))
338 except vim.fault.RestrictedVersion as e:
339 raise AnsibleError("Restricted Version Error: %s" % to_native(e.msg))
340 except vim.fault.GuestOperationsUnavailable as e:
341 raise AnsibleError("VM Guest Operations (VMware Tools) Error: %s" % to_native(e.msg))
342 except vim.fault.InvalidGuestLogin as e:
343 raise AnsibleError("VM Login Error: %s" % to_native(e.msg))
344 except vim.fault.NoPermission as e:
345 raise AnsibleConnectionFailure("No Permission Error: %s %s" % (to_native(e.msg), to_native(e.privilegeId)))
346 except vmodl.fault.SystemError as e:
347 if e.reason == 'vix error codes = (3016, 0).\n':
348 raise AnsibleConnectionFailure(
349 "Connection failed, is the vm currently rebooting? Reason: %s" % (
350 to_native(e.reason)
351 )
352 )
353 else:
354 raise AnsibleConnectionFailure("Connection failed. Reason %s" % (to_native(e.reason)))
355 except vim.fault.GuestOperationsUnavailable:
356 raise AnsibleConnectionFailure("Cannot connect to guest. Native error: GuestOperationsUnavailable")
357
358 def _connect(self, check_vm_credentials=True):
359 if not HAS_REQUESTS:
360 raise AnsibleError("%s : %s" % (missing_required_lib('requests'), REQUESTS_IMP_ERR))
361
362 if not HAS_PYVMOMI:
363 raise AnsibleError("%s : %s" % (missing_required_lib('PyVmomi'), PYVMOMI_IMP_ERR))
364
365 super(Connection, self)._connect()
366
367 if not self.connected:
368 self._establish_connection()
369 self._establish_vm(check_vm_credentials=check_vm_credentials)
370 self._connected = True
371
372 def close(self):
373 """Close connection."""
374 super(Connection, self).close()
375
376 Disconnect(self._si)
377 self._connected = False
378
379 def reset(self):
380 """Reset the connection to vcenter."""
381 # TODO: Fix persistent connection implementation currently ansible creates new connections to vcenter for each task
382 # therefore we're currently closing a non existing connection here and establish a connection just for being thrown away
383 # right afterwards.
384 self.close()
385 self._connect(check_vm_credentials=False)
386
387 def create_temporary_file_in_guest(self, prefix="", suffix=""):
388 """Create a temporary file in the VM."""
389 try:
390 return self.fileManager.CreateTemporaryFileInGuest(vm=self.vm, auth=self.vm_auth, prefix=prefix, suffix=suffix)
391 except vim.fault.NoPermission as e:
392 raise AnsibleError("No Permission Error: %s %s" % (to_native(e.msg), to_native(e.privilegeId)))
393 except vmodl.fault.SystemError as e:
394 if e.reason == 'vix error codes = (3016, 0).\n':
395 raise AnsibleConnectionFailure(
396 "Connection failed, is the vm currently rebooting? Reason: %s" % (
397 to_native(e.reason)
398 )
399 )
400 else:
401 raise AnsibleConnectionFailure("Connection failed. Reason %s" % (to_native(e.reason)))
402 except vim.fault.GuestOperationsUnavailable:
403 raise AnsibleConnectionFailure("Cannot connect to guest. Native error: GuestOperationsUnavailable")
404
405 def _get_program_spec_program_path_and_arguments(self, cmd):
406 if self.windowsGuest:
407 '''
408 we need to warp the execution of powershell into a cmd /c because
409 the call otherwise fails with "Authentication or permission failure"
410 #FIXME: Fix the unecessary invocation of cmd and run the command directly
411 '''
412 program_path = "cmd.exe"
413 arguments = "/c %s" % cmd
414 else:
415 program_path = self.get_option("executable")
416 arguments = re.sub(r"^%s\s*" % program_path, "", cmd)
417
418 return program_path, arguments
419
420 def _get_guest_program_spec(self, cmd, stdout, stderr):
421 guest_program_spec = vim.GuestProgramSpec()
422
423 program_path, arguments = self._get_program_spec_program_path_and_arguments(cmd)
424
425 arguments += " 1> %s 2> %s" % (stdout, stderr)
426
427 guest_program_spec.programPath = program_path
428 guest_program_spec.arguments = arguments
429
430 return guest_program_spec
431
432 def _get_pid_info(self, pid):
433 try:
434 processes = self.processManager.ListProcessesInGuest(vm=self.vm, auth=self.vm_auth, pids=[pid])
435 except vim.fault.NoPermission as e:
436 raise AnsibleError("No Permission Error: %s %s" % (to_native(e.msg), to_native(e.privilegeId)))
437 except vmodl.fault.SystemError as e:
438 # https://pubs.vmware.com/vsphere-6-5/index.jsp?topic=%2Fcom.vmware.wssdk.smssdk.doc%2Fvmodl.fault.SystemError.html
439 # https://github.com/ansible/ansible/issues/57607
440 if e.reason == 'vix error codes = (1, 0).\n':
441 raise AnsibleConnectionFailure(
442 "Connection failed, Netlogon service stopped or dcpromo in progress. Reason: %s" % (
443 to_native(e.reason)
444 )
445 )
446 else:
447 raise AnsibleConnectionFailure("Connection plugin failed. Reason: %s" % (to_native(e.reason)))
448 except vim.fault.GuestOperationsUnavailable:
449 raise AnsibleConnectionFailure("Cannot connect to guest. Native error: GuestOperationsUnavailable")
450 except vim.fault.InvalidGuestLogin:
451 raise AnsibleConnectionFailure("Guest login failed. Native error: InvalidGuestLogin")
452
453 return processes[0]
454
455 def _fix_url_for_hosts(self, url):
456 """
457 Fix url if connection is a host.
458
459 The host part of the URL is returned as '*' if the hostname to be used is the name of the server to which the call was made. For example, if the call is
460 made to esx-svr-1.domain1.com and port 443, and the file is available for download from http://esx-svr-1.domain1.com:443/guestFile?id=1&token=1234,
461 the URL returned may be http://*:443/guestFile?id=1&token=1234.
462 The client replaces the asterisk with the server name on which it invoked the call and 443 with the port number.
463
464 https://code.vmware.com/apis/358/vsphere#/doc/vim.vm.guest.FileManager.FileTransferInformation.html
465 """
466 return url.replace("*", self.vmware_host).replace("443", str(self.get_option("vmware_port")))
467
468 def _fetch_file_from_vm(self, guestFilePath):
469 try:
470 fileTransferInformation = self.fileManager.InitiateFileTransferFromGuest(vm=self.vm, auth=self.vm_auth, guestFilePath=guestFilePath)
471 except vim.fault.NoPermission as e:
472 raise AnsibleError("No Permission Error: %s %s" % (to_native(e.msg), to_native(e.privilegeId)))
473 except vmodl.fault.SystemError as e:
474 if e.reason == 'vix error codes = (3016, 0).\n':
475 raise AnsibleConnectionFailure(
476 "Connection failed, is the vm currently rebooting? Reason: %s" % (
477 to_native(e.reason)
478 )
479 )
480 else:
481 raise AnsibleConnectionFailure("Connection failed. Reason %s" % (to_native(e.reason)))
482 except vim.fault.GuestOperationsUnavailable:
483 raise AnsibleConnectionFailure("Cannot connect to guest. Native error: GuestOperationsUnavailable")
484
485 url = self._fix_url_for_hosts(fileTransferInformation.url)
486 response = requests.get(url, verify=self.validate_certs, stream=True)
487
488 if response.status_code != 200:
489 raise AnsibleError("Failed to fetch file")
490
491 return response
492
493 def delete_file_in_guest(self, filePath):
494 """Delete file from VM."""
495 try:
496 self.fileManager.DeleteFileInGuest(vm=self.vm, auth=self.vm_auth, filePath=filePath)
497 except vim.fault.NoPermission as e:
498 raise AnsibleError("No Permission Error: %s %s" % (to_native(e.msg), to_native(e.privilegeId)))
499 except vmodl.fault.SystemError as e:
500 if e.reason == 'vix error codes = (3016, 0).\n':
501 raise AnsibleConnectionFailure(
502 "Connection failed, is the vm currently rebooting? Reason: %s" % (
503 to_native(e.reason)
504 )
505 )
506 else:
507 raise AnsibleConnectionFailure("Connection failed. Reason %s" % (to_native(e.reason)))
508 except vim.fault.GuestOperationsUnavailable:
509 raise AnsibleConnectionFailure("Cannot connect to guest. Native error: GuestOperationsUnavailable")
510
511 def exec_command(self, cmd, in_data=None, sudoable=True):
512 """Execute command."""
513 super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
514
515 stdout = self.create_temporary_file_in_guest(suffix=".stdout")
516 stderr = self.create_temporary_file_in_guest(suffix=".stderr")
517
518 guest_program_spec = self._get_guest_program_spec(cmd, stdout, stderr)
519
520 try:
521 pid = self.processManager.StartProgramInGuest(vm=self.vm, auth=self.vm_auth, spec=guest_program_spec)
522 except vim.fault.NoPermission as e:
523 raise AnsibleError("No Permission Error: %s %s" % (to_native(e.msg), to_native(e.privilegeId)))
524 except vim.fault.FileNotFound as e:
525 raise AnsibleError("StartProgramInGuest Error: %s" % to_native(e.msg))
526 except vmodl.fault.SystemError as e:
527 if e.reason == 'vix error codes = (3016, 0).\n':
528 raise AnsibleConnectionFailure(
529 "Connection failed, is the vm currently rebooting? Reason: %s" % (
530 to_native(e.reason)
531 )
532 )
533 else:
534 raise AnsibleConnectionFailure("Connection failed. Reason %s" % (to_native(e.reason)))
535 except vim.fault.GuestOperationsUnavailable:
536 raise AnsibleConnectionFailure("Cannot connect to guest. Native error: GuestOperationsUnavailable")
537
538 pid_info = self._get_pid_info(pid)
539
540 while pid_info.endTime is None:
541 sleep(self.get_option("exec_command_sleep_interval"))
542 pid_info = self._get_pid_info(pid)
543
544 stdout_response = self._fetch_file_from_vm(stdout)
545 self.delete_file_in_guest(stdout)
546
547 stderr_response = self._fetch_file_from_vm(stderr)
548 self.delete_file_in_guest(stderr)
549
550 return pid_info.exitCode, stdout_response.text, stderr_response.text
551
552 def fetch_file(self, in_path, out_path):
553 """Fetch file."""
554 super(Connection, self).fetch_file(in_path, out_path)
555
556 in_path_response = self._fetch_file_from_vm(in_path)
557
558 with open(out_path, "wb") as fd:
559 for chunk in in_path_response.iter_content(chunk_size=self.get_option("file_chunk_size")):
560 fd.write(chunk)
561
562 def put_file(self, in_path, out_path):
563 """Put file."""
564 super(Connection, self).put_file(in_path, out_path)
565
566 if not exists(to_bytes(in_path, errors="surrogate_or_strict")):
567 raise AnsibleFileNotFound("file or module does not exist: '%s'" % to_native(in_path))
568
569 try:
570 put_url = self.fileManager.InitiateFileTransferToGuest(
571 vm=self.vm, auth=self.vm_auth, guestFilePath=out_path, fileAttributes=vim.GuestFileAttributes(), fileSize=getsize(in_path), overwrite=True
572 )
573 except vim.fault.NoPermission as e:
574 raise AnsibleError("No Permission Error: %s %s" % (to_native(e.msg), to_native(e.privilegeId)))
575 except vmodl.fault.SystemError as e:
576 if e.reason == 'vix error codes = (3016, 0).\n':
577 raise AnsibleConnectionFailure(
578 "Connection failed, is the vm currently rebooting? Reason: %s" % (
579 to_native(e.reason)
580 )
581 )
582 else:
583 raise AnsibleConnectionFailure("Connection failed. Reason %s" % (to_native(e.reason)))
584 except vim.fault.GuestOperationsUnavailable:
585 raise AnsibleConnectionFailure("Cannot connect to guest. Native error: GuestOperationsUnavailable")
586
587 url = self._fix_url_for_hosts(put_url)
588
589 # file size of 'in_path' must be greater than 0
590 with open(in_path, "rb") as fd:
591 response = requests.put(url, verify=self.validate_certs, data=fd)
592
593 if response.status_code != 200:
594 raise AnsibleError("File transfer failed")