Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Mike Klebolt <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import (absolute_import, division, print_function)
9 __metaclass__ = type
10
11
12 DOCUMENTATION = r'''
13 ---
14 module: vmware_guest_tools_upgrade
15 short_description: Module to upgrade VMTools
16 description:
17 - This module upgrades the VMware Tools on Windows and Linux guests and reboots them.
18 notes:
19 - "In order to upgrade VMTools, please power on virtual machine before hand - either 'manually' or
20 using module M(community.vmware.vmware_guest_powerstate)."
21 options:
22 name:
23 description:
24 - Name of the virtual machine to work with.
25 - 'This is required if O(uuid) or O(moid) is not supplied.'
26 type: str
27 name_match:
28 description:
29 - If multiple virtual machines matching the name, use the first or last found.
30 default: 'first'
31 choices: ['first', 'last']
32 type: str
33 uuid:
34 description:
35 - "UUID of the instance to manage if known, this is VMware's unique identifier."
36 - This is required if O(name) or O(moid) is not supplied.
37 type: str
38 moid:
39 description:
40 - Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance.
41 - This is required if O(name) or O(uuid) is not supplied.
42 type: str
43 folder:
44 description:
45 - Destination folder, absolute or relative path to find an existing guest.
46 - This is required, if O(name) is supplied.
47 - "The folder should include the datacenter. ESX's datacenter is ha-datacenter"
48 - 'Examples:'
49 - ' folder: /ha-datacenter/vm'
50 - ' folder: ha-datacenter/vm'
51 - ' folder: /datacenter1/vm'
52 - ' folder: datacenter1/vm'
53 - ' folder: /datacenter1/vm/folder1'
54 - ' folder: datacenter1/vm/folder1'
55 - ' folder: /folder1/datacenter1/vm'
56 - ' folder: folder1/datacenter1/vm'
57 - ' folder: /folder1/datacenter1/vm/folder2'
58 type: str
59 datacenter:
60 description:
61 - Destination datacenter where the virtual machine exists.
62 required: true
63 type: str
64 force_upgrade:
65 description:
66 - This flag overrides the guest operating system detection and forcibly upgrade VMware tools or open-vm-tools.
67 - "This is useful when VMware tools is too old and unable to detect the 'guestFamily' value."
68 - 'Using this flag may sometime give unexpected results since module will override the default'
69 - "behaviour of 'guestFamily' detection."
70 default: false
71 type: bool
72 required: false
73 installer_options:
74 version_added: '4.1.0'
75 description:
76 - Command line options passed to the installer to modify the installation procedure for tools.
77 type: str
78 required: false
79 extends_documentation_fragment:
80 - vmware.vmware.base_options
81
82 author:
83 - Mike Klebolt (@MikeKlebolt) <[email protected]>
84 '''
85
86 EXAMPLES = r'''
87 - name: Get VM UUID
88 vmware_guest_facts:
89 hostname: "{{ vcenter_hostname }}"
90 username: "{{ vcenter_username }}"
91 password: "{{ vcenter_password }}"
92 datacenter: "{{ datacenter }}"
93 folder: "/{{datacenter}}/vm"
94 name: "{{ vm_name }}"
95 delegate_to: localhost
96 register: vm_facts
97
98 - name: Upgrade VMware Tools using uuid
99 community.vmware.vmware_guest_tools_upgrade:
100 hostname: "{{ vcenter_hostname }}"
101 username: "{{ vcenter_username }}"
102 password: "{{ vcenter_password }}"
103 datacenter: "{{ datacenter_name }}"
104 uuid: "{{ vm_facts.instance.hw_product_uuid }}"
105 delegate_to: localhost
106
107 - name: Upgrade VMware Tools using MoID
108 community.vmware.vmware_guest_tools_upgrade:
109 hostname: "{{ vcenter_hostname }}"
110 username: "{{ vcenter_username }}"
111 password: "{{ vcenter_password }}"
112 datacenter: "{{ datacenter_name }}"
113 moid: vm-42
114 delegate_to: localhost
115 '''
116
117 RETURN = r''' # '''
118
119
120 from ansible.module_utils.basic import AnsibleModule
121 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi, wait_for_task
122 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
123 from ansible.module_utils.common.text.converters import to_native
124
125
126 class PyVmomiHelper(PyVmomi):
127 def __init__(self, module):
128 super(PyVmomiHelper, self).__init__(module)
129
130 def upgrade_tools(self, vm):
131 result = {'failed': False, 'changed': False, 'msg': ''}
132
133 # Exit if VMware tools is already up to date
134 if vm.guest.toolsVersionStatus2 == "guestToolsCurrent":
135 result.update(
136 msg="VMwareTools are already up to date",
137 )
138 return result
139 elif vm.guest.toolsVersionStatus2 == "guestToolsSupportedNew" or vm.guest.toolsVersionStatus2 == "guestToolsTooNew":
140 result.update(
141 msg="VMwareTools are already newer than the version available on the host",
142 )
143 return result
144
145 # Fail if VM is not powered on
146 elif vm.summary.runtime.powerState != "poweredOn":
147 result.update(
148 failed=True,
149 msg="VM must be powered on to upgrade tools",
150 )
151 return result
152
153 # Fail if VMware tools is either not installed or not running
154 elif vm.guest.toolsVersionStatus2 == 'guestToolsNotInstalled':
155 result.update(
156 failed=True,
157 msg="VMwareTools are not installed."
158 )
159 return result
160 elif vm.guest.toolsRunningStatus != 'guestToolsRunning':
161 result.update(
162 failed=True,
163 msg="VMwareTools are not running."
164 )
165 return result
166
167 # Fail if VMware tools are unmanaged
168 elif vm.guest.toolsVersionStatus2 == "guestToolsUnmanaged":
169 result.update(
170 failed=True,
171 msg="VMwareTools not managed by VMware",
172 )
173 return result
174
175 # If vmware tools is out of date, check major OS family
176 # Upgrade tools on Linux and Windows guests
177 elif vm.guest.toolsVersionStatus2 in ["guestToolsBlacklisted", "guestToolsNeedUpgrade", "guestToolsSupportedOld", "guestToolsTooOld"]:
178 try:
179 force = self.module.params.get('force_upgrade')
180 installer_options = self.module.params.get('installer_options')
181 if force or vm.guest.guestFamily in ["linuxGuest", "windowsGuest"]:
182 if installer_options is not None:
183 task = vm.UpgradeTools(installer_options)
184 else:
185 task = vm.UpgradeTools()
186 changed, err_msg = wait_for_task(task)
187 result.update(changed=changed, msg=to_native(err_msg))
188 else:
189 result.update(msg='Guest Operating System is other than Linux and Windows.')
190 return result
191 except Exception as exc:
192 result.update(
193 failed=True,
194 msg='Error while upgrading VMwareTools %s' % to_native(exc),
195 )
196 return result
197 else:
198 result.update(
199 failed=True,
200 msg="This shouldn't happen, looks like a problem in the module",
201 )
202 return result
203
204
205 def main():
206 argument_spec = base_argument_spec()
207 argument_spec.update(
208 name=dict(type='str'),
209 name_match=dict(type='str', choices=['first', 'last'], default='first'),
210 uuid=dict(type='str'),
211 moid=dict(type='str'),
212 folder=dict(type='str'),
213 datacenter=dict(type='str', required=True),
214 force_upgrade=dict(type='bool', default=False),
215 installer_options=dict(type='str'),
216 )
217 module = AnsibleModule(
218 argument_spec=argument_spec,
219 required_one_of=[
220 ['name', 'uuid', 'moid']
221 ]
222 )
223
224 if module.params['folder']:
225 # FindByInventoryPath() does not require an absolute path
226 # so we should leave the input folder path unmodified
227 module.params['folder'] = module.params['folder'].rstrip('/')
228
229 pyv = PyVmomiHelper(module)
230 # Check if the VM exists before continuing
231 vm = pyv.get_vm()
232
233 # VM already exists
234 if vm:
235 try:
236 result = pyv.upgrade_tools(vm)
237 if result['changed']:
238 module.exit_json(changed=result['changed'])
239 elif result['failed']:
240 module.fail_json(msg=result['msg'])
241 else:
242 module.exit_json(msg=result['msg'], changed=result['changed'])
243 except Exception as exc:
244 module.fail_json(msg='Unknown error: %s' % to_native(exc))
245 else:
246 vm_id = module.params.get('uuid') or module.params.get('name') or module.params.get('moid')
247 module.fail_json(msg='Unable to find VM %s' % vm_id)
248
249
250 if __name__ == '__main__':
251 main()