Debian Codegraph @

ansible_collections/community/vmware/plugins/modules/vmware_vm_shell.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2015-16, Ritesh Khadgaray <khadgaray () gmail.com>
5 # Copyright: (c) 2018, Ansible Project
6 # Copyright: (c) 2018, Abhijeet Kasurde <[email protected]>
7 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
8 # SPDX-License-Identifier: GPL-3.0-or-later
9
10 from __future__ import absolute_import, division, print_function
11 __metaclass__ = type
12
13
14 DOCUMENTATION = r'''
15 ---
16 module: vmware_vm_shell
17 short_description: Run commands in a VMware guest operating system
18 description:
19 - Module allows user to run common system administration commands in the guest operating system.
20 author:
21 - Ritesh Khadgaray (@ritzk)
22 - Abhijeet Kasurde (@Akasurde)
23 notes:
24 - Only the first match against vm_id is used, even if there are multiple matches.
25 options:
26 datacenter:
27 description:
28 - The datacenter hosting the virtual machine.
29 - If set, it will help to speed up virtual machine search.
30 type: str
31 cluster:
32 description:
33 - The cluster hosting the virtual machine.
34 - If set, it will help to speed up virtual machine search.
35 type: str
36 folder:
37 description:
38 - Destination folder, absolute or relative path to find an existing guest or create the new guest.
39 - The folder should include the datacenter. ESX's datacenter is ha-datacenter.
40 - 'Examples:'
41 - ' folder: /ha-datacenter/vm'
42 - ' folder: ha-datacenter/vm'
43 - ' folder: /datacenter1/vm'
44 - ' folder: datacenter1/vm'
45 - ' folder: /datacenter1/vm/folder1'
46 - ' folder: datacenter1/vm/folder1'
47 - ' folder: /folder1/datacenter1/vm'
48 - ' folder: folder1/datacenter1/vm'
49 - ' folder: /folder1/datacenter1/vm/folder2'
50 - Required if O(vm_id_type=inventory_path)
51 type: str
52 vm_id:
53 description:
54 - Name of the virtual machine to work with.
55 required: true
56 type: str
57 vm_id_type:
58 description:
59 - The VMware identification method by which the virtual machine will be identified.
60 default: vm_name
61 choices: ['uuid', 'instance_uuid', 'dns_name', 'inventory_path', 'vm_name']
62 type: str
63 vm_username:
64 description:
65 - The user to login-in to the virtual machine.
66 required: true
67 type: str
68 vm_password:
69 description:
70 - The password used to login-in to the virtual machine.
71 required: true
72 type: str
73 vm_shell:
74 description:
75 - The absolute path to the program to start.
76 - On Linux, shell is executed via bash.
77 required: true
78 type: str
79 vm_shell_args:
80 description:
81 - The argument to the program.
82 - The characters which must be escaped to the shell also be escaped on the command line provided.
83 default: " "
84 type: str
85 vm_shell_env:
86 description:
87 - Comma separated list of environment variable, specified in the guest OS notation.
88 type: list
89 elements: str
90 vm_shell_cwd:
91 description:
92 - The current working directory of the application from which it will be run.
93 type: str
94 wait_for_process:
95 description:
96 - If set to V(true), module will wait for process to complete in the given virtual machine.
97 default: false
98 type: bool
99 timeout:
100 description:
101 - Timeout in seconds.
102 - If set to positive integers, then O(wait_for_process=true) will honor this parameter and will exit after this timeout.
103 default: 3600
104 type: int
105 extends_documentation_fragment:
106 - vmware.vmware.base_options
107
108 '''
109
110 EXAMPLES = r'''
111 - name: Run command inside a virtual machine
112 community.vmware.vmware_vm_shell:
113 hostname: "{{ vcenter_hostname }}"
114 username: "{{ vcenter_username }}"
115 password: "{{ vcenter_password }}"
116 datacenter: "{{ datacenter }}"
117 folder: "/{{datacenter}}/vm"
118 vm_id: "{{ vm_name }}"
119 vm_username: root
120 vm_password: superSecret
121 vm_shell: /bin/echo
122 vm_shell_args: " $var >> myFile "
123 vm_shell_env:
124 - "PATH=/bin"
125 - "VAR=test"
126 vm_shell_cwd: "/tmp"
127 delegate_to: localhost
128 register: shell_command_output
129
130 - name: Run command inside a virtual machine with wait and timeout
131 community.vmware.vmware_vm_shell:
132 hostname: "{{ vcenter_hostname }}"
133 username: "{{ vcenter_username }}"
134 password: "{{ vcenter_password }}"
135 datacenter: "{{ datacenter }}"
136 folder: "/{{datacenter}}/vm"
137 vm_id: NameOfVM
138 vm_username: root
139 vm_password: superSecret
140 vm_shell: /bin/sleep
141 vm_shell_args: 100
142 wait_for_process: true
143 timeout: 2000
144 delegate_to: localhost
145 register: shell_command_with_wait_timeout
146
147 - name: Change user password in the guest machine
148 community.vmware.vmware_vm_shell:
149 hostname: "{{ vcenter_hostname }}"
150 username: "{{ vcenter_username }}"
151 password: "{{ vcenter_password }}"
152 datacenter: "{{ datacenter }}"
153 folder: "/{{datacenter}}/vm"
154 vm_id: "{{ vm_name }}"
155 vm_username: sample
156 vm_password: old_password
157 vm_shell: "/bin/echo"
158 vm_shell_args: "-e 'old_password\nnew_password\nnew_password' | passwd sample > /tmp/$$.txt 2>&1"
159 delegate_to: localhost
160
161 - name: Change hostname of guest machine
162 community.vmware.vmware_vm_shell:
163 hostname: "{{ vcenter_hostname }}"
164 username: "{{ vcenter_username }}"
165 password: "{{ vcenter_password }}"
166 datacenter: "{{ datacenter }}"
167 folder: "/{{datacenter}}/vm"
168 vm_id: "{{ vm_name }}"
169 vm_username: testUser
170 vm_password: SuperSecretPassword
171 vm_shell: "/usr/bin/hostnamectl"
172 vm_shell_args: "set-hostname new_hostname > /tmp/$$.txt 2>&1"
173 delegate_to: localhost
174 '''
175
176 RETURN = r'''
177 results:
178 description: metadata about the new process after completion with wait_for_process
179 returned: on success
180 type: dict
181 sample:
182 {
183 "cmd_line": "\"/bin/sleep\" 1",
184 "end_time": "2018-04-26T05:03:21+00:00",
185 "exit_code": 0,
186 "name": "sleep",
187 "owner": "dev1",
188 "start_time": "2018-04-26T05:03:19+00:00",
189 "uuid": "564db1e2-a3ff-3b0e-8b77-49c25570bb66",
190 }
191 '''
192
193 import time
194 try:
195 from pyVmomi import vim, vmodl
196 except ImportError:
197 pass
198
199 from ansible.module_utils.common.text.converters import to_native
200 from ansible.module_utils.basic import AnsibleModule
201 from ansible_collections.community.vmware.plugins.module_utils.vmware import (
202 PyVmomi, find_cluster_by_name, find_datacenter_by_name, find_vm_by_id)
203 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
204
205
206 class VMwareShellManager(PyVmomi):
207 def __init__(self, module):
208 super(VMwareShellManager, self).__init__(module)
209 datacenter_name = module.params['datacenter']
210 cluster_name = module.params['cluster']
211 folder = module.params['folder']
212 try:
213 self.pm = self.content.guestOperationsManager.processManager
214 except vmodl.fault.ManagedObjectNotFound:
215 pass
216 self.timeout = self.params.get('timeout', 3600)
217 self.wait_for_pid = self.params.get('wait_for_process', False)
218
219 datacenter = None
220 if datacenter_name:
221 datacenter = find_datacenter_by_name(self.content, datacenter_name)
222 if not datacenter:
223 module.fail_json(changed=False, msg="Unable to find %(datacenter)s datacenter" % module.params)
224
225 cluster = None
226 if cluster_name:
227 cluster = find_cluster_by_name(self.content, cluster_name, datacenter)
228 if not cluster:
229 module.fail_json(changed=False, msg="Unable to find %(cluster)s cluster" % module.params)
230
231 if module.params['vm_id_type'] == 'inventory_path':
232 vm = find_vm_by_id(self.content,
233 vm_id=module.params['vm_id'],
234 vm_id_type="inventory_path",
235 folder=folder)
236 else:
237 vm = find_vm_by_id(self.content,
238 vm_id=module.params['vm_id'],
239 vm_id_type=module.params['vm_id_type'],
240 datacenter=datacenter,
241 cluster=cluster)
242
243 if not vm:
244 module.fail_json(msg='Unable to find virtual machine.')
245
246 if vm.guest.toolsVersionStatus2 == 'guestToolsNotInstalled':
247 self.module.fail_json(msg="The VMwareTools are not installed. "
248 "VMware Tools are necessary to run this module.")
249 if vm.guest.toolsRunningStatus != 'guestToolsRunning':
250 self.module.fail_json(msg="The VMwareTools are not running ."
251 "VMware Tools are necessary to run this module.")
252
253 try:
254 self.execute_command(vm, module.params)
255 except vmodl.RuntimeFault as runtime_fault:
256 module.fail_json(changed=False, msg=to_native(runtime_fault.msg))
257 except vmodl.MethodFault as method_fault:
258 module.fail_json(changed=False, msg=to_native(method_fault.msg))
259 except Exception as e:
260 module.fail_json(changed=False, msg=to_native(e))
261
262 def execute_command(self, vm, params):
263 # https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/execute_program_in_vm.py
264 vm_username = params['vm_username']
265 vm_password = params['vm_password']
266 program_path = params['vm_shell']
267 args = params['vm_shell_args']
268 env = params['vm_shell_env']
269 cwd = params['vm_shell_cwd']
270
271 credentials = vim.vm.guest.NamePasswordAuthentication(username=vm_username,
272 password=vm_password)
273 cmd_spec = vim.vm.guest.ProcessManager.ProgramSpec(arguments=args,
274 envVariables=env,
275 programPath=program_path,
276 workingDirectory=cwd)
277
278 res = self.pm.StartProgramInGuest(vm=vm, auth=credentials, spec=cmd_spec)
279 if self.wait_for_pid:
280 res_data = self.wait_for_process(vm, res, credentials)
281 results = dict(uuid=vm.summary.config.uuid,
282 owner=res_data.owner,
283 start_time=res_data.startTime.isoformat(),
284 end_time=res_data.endTime.isoformat(),
285 exit_code=res_data.exitCode,
286 name=res_data.name,
287 cmd_line=res_data.cmdLine)
288
289 if res_data.exitCode != 0:
290 results['msg'] = "Failed to execute command"
291 results['changed'] = False
292 results['failed'] = True
293 self.module.fail_json(**results)
294 else:
295 results['changed'] = True
296 results['failed'] = False
297 self.module.exit_json(**results)
298 else:
299 self.module.exit_json(changed=True, uuid=vm.summary.config.uuid, msg=res)
300
301 def process_exists_in_guest(self, vm, pid, creds):
302 res = self.pm.ListProcessesInGuest(vm, creds, pids=[pid])
303 if not res:
304 self.module.fail_json(
305 changed=False, msg='ListProcessesInGuest: None (unexpected)')
306 res = res[0]
307 if res.exitCode is None:
308 return True, None
309 else:
310 return False, res
311
312 def wait_for_process(self, vm, pid, creds):
313 start_time = time.time()
314 while True:
315 current_time = time.time()
316 process_status, res_data = self.process_exists_in_guest(vm, pid, creds)
317 if not process_status:
318 return res_data
319 elif current_time - start_time >= self.timeout:
320 self.module.fail_json(
321 msg="Timeout waiting for process to complete.",
322 vm=vm._moId,
323 pid=pid,
324 start_time=start_time,
325 current_time=current_time,
326 timeout=self.timeout)
327 else:
328 time.sleep(5)
329
330
331 def main():
332 argument_spec = base_argument_spec()
333 argument_spec.update(
334 dict(
335 datacenter=dict(type='str'),
336 cluster=dict(type='str'),
337 folder=dict(type='str'),
338 vm_id=dict(type='str', required=True),
339 vm_id_type=dict(default='vm_name', type='str',
340 choices=['inventory_path',
341 'uuid',
342 'instance_uuid',
343 'dns_name',
344 'vm_name']),
345 vm_username=dict(type='str', required=True),
346 vm_password=dict(type='str', no_log=True, required=True),
347 vm_shell=dict(type='str', required=True),
348 vm_shell_args=dict(default=" ", type='str'),
349 vm_shell_env=dict(type='list', elements='str'),
350 vm_shell_cwd=dict(type='str'),
351 wait_for_process=dict(type='bool', default=False),
352 timeout=dict(type='int', default=3600),
353 )
354 )
355
356 module = AnsibleModule(
357 argument_spec=argument_spec,
358 supports_check_mode=False,
359 required_if=[
360 ['vm_id_type', 'inventory_path', ['folder']]
361 ],
362 )
363
364 VMwareShellManager(module)
365
366
367 if __name__ == '__main__':
368 main()