Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2021, Ansible Project
5 # Copyright: (c) 2021, VMware, Inc. All Rights Reserved.
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import absolute_import, division, print_function
10 __metaclass__ = type
11
12 DOCUMENTATION = r'''
13 ---
14 module: vmware_guest_tpm
15 short_description: Add or remove vTPM device for specified VM.
16 description: >
17 This module is used for adding or removing Virtual Trusted Platform Module(vTPM) device for an existing
18 Virtual Machine. You must create a key provider on vCenter before you can add a vTPM. The ESXi hosts
19 running in your environment must be ESXi 6.7 or later (Windows guest OS), or 7.0 Update 2 (Linux guest OS).
20 author:
21 - Diane Wang (@Tomorrow9) <[email protected]>
22 options:
23 name:
24 description:
25 - Name of the virtual machine.
26 - This is required if parameter O(uuid) or O(moid) is not supplied.
27 type: str
28 uuid:
29 description:
30 - UUID of the instance to manage if known, this is VMware's unique identifier.
31 - This is required if parameter O(name) or O(moid) is not supplied.
32 type: str
33 moid:
34 description:
35 - Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance.
36 - This is required if O(name) or O(uuid) is not supplied.
37 type: str
38 folder:
39 description:
40 - VM folder, absolute or relative path to find an existing VM.
41 - This parameter is not required, only when multiple VMs are found with the same name.
42 - The folder should include the datacenter name.
43 - 'Examples:'
44 - ' folder: /datacenter1/vm'
45 - ' folder: datacenter1/vm'
46 - ' folder: /datacenter1/vm/folder1'
47 - ' folder: datacenter1/vm/folder1'
48 - ' folder: /folder1/datacenter1/vm'
49 - ' folder: folder1/datacenter1/vm'
50 - ' folder: /folder1/datacenter1/vm/folder2'
51 type: str
52 datacenter:
53 description:
54 - The vCenter datacenter name used to get specified cluster or host.
55 type: str
56 required: true
57 state:
58 description:
59 - State of vTPM device.
60 - If set to 'absent', vTPM device will be removed from VM.
61 - If set to 'present', vTPM device will be added if not present.
62 - Virtual machine should be turned off before add or remove vTPM device.
63 - Virtual machine should not contain snapshots before add vTPM device.
64 type: str
65 choices: ['present', 'absent']
66 default: 'present'
67 extends_documentation_fragment:
68 - vmware.vmware.base_options
69 '''
70
71 EXAMPLES = r'''
72 - name: Add vTPM to specified VM
73 community.vmware.vmware_guest_tpm:
74 hostname: "{{ vcenter_hostname }}"
75 username: "{{ vcenter_username }}"
76 password: "{{ vcenter_password }}"
77 datacenter: "{{ datacenter }}"
78 name: "Test_VM"
79 state: present
80 delegate_to: localhost
81
82 - name: Remove vTPM from specified VM
83 community.vmware.vmware_guest_tpm:
84 hostname: "{{ vcenter_hostname }}"
85 username: "{{ vcenter_username }}"
86 password: "{{ vcenter_password }}"
87 datacenter: "{{ datacenter }}"
88 name: "Test_VM"
89 state: absent
90 delegate_to: localhost
91 '''
92
93 RETURN = r'''
94 instance:
95 description: metadata about the VM vTPM device
96 returned: always
97 type: dict
98 sample: None
99 '''
100
101 try:
102 from pyVmomi import vim
103 except ImportError:
104 pass
105
106 from ansible.module_utils.basic import AnsibleModule
107 from ansible.module_utils.common.text.converters import to_native
108 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi, wait_for_task
109 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
110 from ansible_collections.community.vmware.plugins.module_utils.vm_device_helper import PyVmomiDeviceHelper
111
112
113 class PyVmomiHelper(PyVmomi):
114 def __init__(self, module):
115 super(PyVmomiHelper, self).__init__(module)
116 self.device_helper = PyVmomiDeviceHelper(self.module)
117 self.config_spec = vim.vm.ConfigSpec()
118 self.config_spec.deviceChange = []
119 self.vm = None
120 self.vtpm_device = None
121
122 def get_vtpm_info(self, vm_obj=None, vtpm_device=None):
123 vtpm_info = dict()
124 if vm_obj:
125 for device in vm_obj.config.hardware.device:
126 if self.device_helper.is_tpm_device(device):
127 vtpm_device = device
128 if vtpm_device:
129 vtpm_info = dict(
130 key=vtpm_device.key,
131 label=vtpm_device.deviceInfo.label,
132 summary=vtpm_device.deviceInfo.summary,
133 )
134
135 return vtpm_info
136
137 def vtpm_operation(self, vm_obj=None):
138 vtpm_device_spec = None
139 results = {'failed': False, 'changed': False}
140 if not self.is_vcenter():
141 self.module.fail_json(msg="Please connect to vCenter Server to configure vTPM device of virtual machine.")
142
143 self.vm = vm_obj
144 if self.vm.runtime.powerState != vim.VirtualMachinePowerState.poweredOff:
145 self.module.fail_json(msg="Please make sure VM is powered off before configuring vTPM device,"
146 " current state is '%s'" % self.vm.runtime.powerState)
147
148 for device in self.vm.config.hardware.device:
149 if self.device_helper.is_tpm_device(device):
150 self.vtpm_device = device
151
152 if self.module.params['state'] == 'present':
153 if self.module.check_mode:
154 results['desired_operation'] = "add vTPM"
155 else:
156 results['vtpm_operation'] = "add vTPM"
157 if self.vtpm_device:
158 results['vtpm_info'] = self.get_vtpm_info(vtpm_device=self.vtpm_device)
159 results['msg'] = "vTPM device already exist on VM"
160 self.module.exit_json(**results)
161 else:
162 if self.module.check_mode:
163 results['changed'] = True
164 self.module.exit_json(**results)
165 vtpm_device_spec = self.device_helper.create_tpm()
166 if self.module.params['state'] == 'absent':
167 if self.module.check_mode:
168 results['desired_operation'] = "remove vTPM"
169 else:
170 results['vtpm_operation'] = "remove vTPM"
171 if self.vtpm_device is None:
172 results['msg'] = "No vTPM device found on VM"
173 self.module.exit_json(**results)
174 else:
175 if self.module.check_mode:
176 results['changed'] = True
177 self.module.exit_json(**results)
178 vtpm_device_spec = self.device_helper.remove_tpm(self.vtpm_device)
179 self.config_spec.deviceChange.append(vtpm_device_spec)
180
181 try:
182 task = self.vm.ReconfigVM_Task(spec=self.config_spec)
183 wait_for_task(task)
184 except Exception as e:
185 self.module.fail_json(msg="Failed to configure vTPM device on virtual machine due to '%s'" % to_native(e))
186 if task.info.state == 'error':
187 self.module.fail_json(msg='Failed to reconfigure VM with vTPM device', detail=task.info.error.msg)
188 results['changed'] = True
189 results['vtpm_info'] = self.get_vtpm_info(vm_obj=self.vm)
190 self.module.exit_json(**results)
191
192
193 def main():
194 argument_spec = base_argument_spec()
195 argument_spec.update(
196 name=dict(type='str'),
197 uuid=dict(type='str'),
198 moid=dict(type='str'),
199 folder=dict(type='str'),
200 datacenter=dict(type='str', required=True),
201 state=dict(type='str', default='present', choices=['present', 'absent']),
202 )
203 module = AnsibleModule(
204 argument_spec=argument_spec,
205 supports_check_mode=True,
206 required_one_of=[['name', 'uuid', 'moid']],
207 )
208 if module.params['folder']:
209 # FindByInventoryPath() does not require an absolute path
210 # so we should leave the input folder path unmodified
211 module.params['folder'] = module.params['folder'].rstrip('/')
212
213 vm_config_vtpm = PyVmomiHelper(module)
214 vm = vm_config_vtpm.get_vm()
215 if not vm:
216 vm_id = (module.params.get('name') or module.params.get('uuid') or module.params.get('moid'))
217 module.fail_json(msg="Unable to configure vTPM device for non-existing virtual machine '%s'." % vm_id)
218 try:
219 vm_config_vtpm.vtpm_operation(vm_obj=vm)
220 except Exception as e:
221 module.fail_json(msg="Failed to configure vTPM device of virtual machine '%s' with exception : %s"
222 % (vm.name, to_native(e)))
223
224
225 if __name__ == "__main__":
226 main()