| 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_guest_customization |
| 12 |
short_description: Applies a customization specification on the virtual machine |
| 13 |
description: Applies a customization specification on the virtual machine in {@param.name |
| 14 |
vm}. The actual customization happens inside the guest when the virtual machine |
| 15 |
is powered on. If there is a pending customization for the virtual machine and |
| 16 |
a new one is set, then the existing customization setting will be overwritten |
| 17 |
with the new settings. |
| 18 |
deprecated: |
| 19 |
removed_in: 5.0.0 |
| 20 |
why: This module has been moved to the L(new vmware.vmware collection,https://forum.ansible.com/t/5880) |
| 21 |
alternative: Use M(vmware.vmware.vm_apply_customization) instead. |
| 22 |
options: |
| 23 |
configuration_spec: |
| 24 |
description: |
| 25 |
- Settings to be applied to the guest during the customization. This parameter |
| 26 |
is mandatory. |
| 27 |
- 'Valid attributes are:' |
| 28 |
- ' - C(windows_config) (dict): Guest customization specification for a Windows |
| 29 |
guest operating system' |
| 30 |
- If unset, ConfigurationSpec.linux-config or ConfigurationSpec.cloud-config |
| 31 |
must be set. Otherwise, an appropriate fault will be thrown. (['set']) |
| 32 |
- ' - Accepted keys:' |
| 33 |
- ' - reboot (string): This option specifies what should be done to the |
| 34 |
guest after the customization.' |
| 35 |
- 'Accepted value for this field:' |
| 36 |
- ' - C(NO_REBOOT)' |
| 37 |
- ' - C(REBOOT)' |
| 38 |
- ' - C(SHUTDOWN)' |
| 39 |
- ' - sysprep (object): Customization settings like user details, administrator |
| 40 |
details, etc for the windows guest operating system. Exactly one of WindowsConfiguration.sysprep |
| 41 |
or WindowsConfiguration.sysprep-xml must be specified.' |
| 42 |
- If unset, sysprep settings will not be applied to the windows guest operating |
| 43 |
system. |
| 44 |
- ' - sysprep_xml (string): All settings specified in a XML format. This |
| 45 |
is the content of a typical answer.xml file that is used by System administrators |
| 46 |
during the Windows image customization. Check |
| 47 |
https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/update-windows-settings-and-scripts-create-your-own-answer-file-sxs |
| 48 |
Exactly one of WindowsConfiguration.sysprep or WindowsConfiguration.sysprep-xml |
| 49 |
must be specified.' |
| 50 |
- If unset, sysprep settings will not be applied to the windows guest operating |
| 51 |
system. |
| 52 |
- ' - C(linux_config) (dict): Guest customization specification for a linux |
| 53 |
guest operating system' |
| 54 |
- If unset, ConfigurationSpec.windows-config or ConfigurationSpec.cloud-config |
| 55 |
must be set. Otherwise, an appropriate fault will be thrown. (['set']) |
| 56 |
- ' - Accepted keys:' |
| 57 |
- ' - hostname (object): The computer name of the (Windows) virtual machine. |
| 58 |
A computer name may contain letters (A-Z), numbers(0-9) and hyphens (-) |
| 59 |
but no spaces or periods (.). The name may not consist entirely of digits. |
| 60 |
A computer name is restricted to 15 characters in length. If the computer |
| 61 |
name is longer than 15 characters, it will be truncated to 15 characters. |
| 62 |
Check HostnameGenerator for various options.' |
| 63 |
- ' - domain (string): The fully qualified domain name.' |
| 64 |
- ' - time_zone (string): The case-sensitive time zone, such as Europe/Sofia. |
| 65 |
Valid time zone values are based on the tz (time zone) database used by |
| 66 |
Linux. The values are strings (string) in the form "Area/Location," in |
| 67 |
which Area is a continent or ocean name, and Location is the city, island, |
| 68 |
or other regional designation. ' |
| 69 |
- ' See the https://kb.vmware.com/kb/2145518 for a list of supported time |
| 70 |
zones for different versions in Linux.' |
| 71 |
- '' |
| 72 |
- If unset, time zone is not modified inside guest operating system. |
| 73 |
- ' - script_text (string): The script to run before and after Linux guest |
| 74 |
customization.' |
| 75 |
- ' The max size of the script is 65536 bytes. As long as the script (shell, |
| 76 |
perl, python...) has the right "#!" in the header, it is supported. The |
| 77 |
caller should not assume any environment variables when the script is |
| 78 |
run. ' |
| 79 |
- ' The script is invoked by the customization engine using the command line: |
| 80 |
1) with argument "precustomization" before customization, 2) with argument |
| 81 |
"postcustomization" after customization. The script should parse this |
| 82 |
argument and implement pre-customization or post-customization task code |
| 83 |
details in the corresponding block. ' |
| 84 |
- '' |
| 85 |
- ' A Linux shell script example: ' |
| 86 |
- '' |
| 87 |
- ' #!/bin/sh' |
| 88 |
- ' if [ x$1 == x"precustomization" ]; then' |
| 89 |
- ' echo "Do Precustomization tasks"' |
| 90 |
- ' #code for pre-customization actions...' |
| 91 |
- ' elif [ x$1 == x"postcustomization" ]; then' |
| 92 |
- ' echo "Do Postcustomization tasks"' |
| 93 |
- ' #code for post-customization actions...' |
| 94 |
- ' fi' |
| 95 |
- ' ' |
| 96 |
- '' |
| 97 |
- If unset, no script will be executed. |
| 98 |
- ' - C(cloud_config) (dict): Guest customization specification with cloud |
| 99 |
configuration.' |
| 100 |
- If unset, ConfigurationSpec.windows-config or ConfigurationSpec.linux-config |
| 101 |
must be set. Otherwise, an appropriate fault will be thrown. (['set']) |
| 102 |
- ' - Accepted keys:' |
| 103 |
- ' - type (string): This option specifies different types of the cloud |
| 104 |
configuration.' |
| 105 |
- 'Accepted value for this field:' |
| 106 |
- ' - C(CLOUDINIT)' |
| 107 |
- ' - cloudinit (object): cloud-init configuration' |
| 108 |
- This field is optional and it is only relevant when the value of CloudConfiguration.type |
| 109 |
is CLOUDINIT. |
| 110 |
required: true |
| 111 |
type: dict |
| 112 |
global_DNS_settings: |
| 113 |
description: |
| 114 |
- Global DNS settings constitute the DNS settings that are not specific to |
| 115 |
a particular virtual network adapter. This parameter is mandatory. |
| 116 |
- 'Valid attributes are:' |
| 117 |
- ' - C(dns_suffix_list) (list): List of name resolution suffixes for the |
| 118 |
virtual network adapter. This list applies to both Windows and Linux guest |
| 119 |
customization. For Linux, this setting is global, whereas in Windows, |
| 120 |
this setting is listed on a per-adapter basis.' |
| 121 |
- If unset, no DNS suffixes are set. (['set']) |
| 122 |
- ' - C(dns_servers) (list): List of DNS servers, for a virtual network adapter |
| 123 |
with a static IP address. If this list is empty, then the guest operating |
| 124 |
system is expected to use a DHCP server to get its DNS server settings. |
| 125 |
These settings configure the virtual machine to use the specified DNS |
| 126 |
servers. These DNS server settings are listed in the order of preference.' |
| 127 |
- If unset, no DNS servers are set. (['set']) |
| 128 |
required: true |
| 129 |
type: dict |
| 130 |
interfaces: |
| 131 |
description: |
| 132 |
- IP settings that are specific to a particular virtual network adapter. The |
| 133 |
AdapterMapping structure maps a network adapter's MAC address to its IPSettings. |
| 134 |
May be empty if there are no network adapters, else should match number |
| 135 |
of network adapters configured for the VM. This parameter is mandatory. |
| 136 |
- 'Valid attributes are:' |
| 137 |
- ' - C(mac_address) (str): The MAC address of a network adapter being customized. ' |
| 138 |
- ' In vSphere 7.0 series, the MAC addresses must be specified in the ascending |
| 139 |
order of pciSlotNumber, otherwise a MAC address mismatch error will be |
| 140 |
reported. For further details, see the https://kb.vmware.com/s/article/87648 ' |
| 141 |
- '' |
| 142 |
- '' |
| 143 |
- '' |
| 144 |
- If unset, the customization process maps the the settings from the list |
| 145 |
of I(i_p_settings) in the CustomizationSpec.interfaces to the virtual |
| 146 |
machine's network adapters, in PCI slot order. The first virtual network |
| 147 |
adapter on the PCI bus is assigned interfaces[0].IPSettings, the second |
| 148 |
adapter is assigned interfaces[1].IPSettings, and so on. (['set']) |
| 149 |
- ' - C(adapter) (dict): The IP settings for the associated virtual network |
| 150 |
adapter. ([''set''])' |
| 151 |
- ' This key is required with [''set''].' |
| 152 |
- ' - Accepted keys:' |
| 153 |
- ' - ipv4 (object): Specification to configure IPv4 address, subnet mask |
| 154 |
and gateway info for this virtual network adapter.' |
| 155 |
- If unset, no IPv4 addresses are set. |
| 156 |
- ' - ipv6 (object): Specification to configure IPv6 address, subnet mask |
| 157 |
and gateway info for this virtual network adapter.' |
| 158 |
- If unset, no IPv6 addresses are set. |
| 159 |
- ' - windows (object): Windows settings to be configured for this specific |
| 160 |
virtual Network adapter. This is valid only for Windows guest operating |
| 161 |
systems.' |
| 162 |
- If unset, no specific Windows settings are set. |
| 163 |
elements: dict |
| 164 |
required: true |
| 165 |
type: list |
| 166 |
session_timeout: |
| 167 |
description: |
| 168 |
- 'Timeout settings for client session. ' |
| 169 |
- 'The maximal number of seconds for the whole operation including connection |
| 170 |
establishment, request sending and response. ' |
| 171 |
- The default value is 300s. |
| 172 |
type: float |
| 173 |
version_added: 2.1.0 |
| 174 |
state: |
| 175 |
choices: |
| 176 |
- set |
| 177 |
default: set |
| 178 |
description: [] |
| 179 |
type: str |
| 180 |
vcenter_hostname: |
| 181 |
description: |
| 182 |
- The hostname or IP address of the vSphere vCenter |
| 183 |
- If the value is not specified in the task, the value of environment variable |
| 184 |
C(VMWARE_HOST) will be used instead. |
| 185 |
required: true |
| 186 |
type: str |
| 187 |
vcenter_password: |
| 188 |
description: |
| 189 |
- The vSphere vCenter password |
| 190 |
- If the value is not specified in the task, the value of environment variable |
| 191 |
C(VMWARE_PASSWORD) will be used instead. |
| 192 |
required: true |
| 193 |
type: str |
| 194 |
vcenter_rest_log_file: |
| 195 |
description: |
| 196 |
- 'You can use this optional parameter to set the location of a log file. ' |
| 197 |
- 'This file will be used to record the HTTP REST interaction. ' |
| 198 |
- 'The file will be stored on the host that runs the module. ' |
| 199 |
- 'If the value is not specified in the task, the value of ' |
| 200 |
- environment variable C(VMWARE_REST_LOG_FILE) will be used instead. |
| 201 |
type: str |
| 202 |
vcenter_username: |
| 203 |
description: |
| 204 |
- The vSphere vCenter username |
| 205 |
- If the value is not specified in the task, the value of environment variable |
| 206 |
C(VMWARE_USER) will be used instead. |
| 207 |
required: true |
| 208 |
type: str |
| 209 |
vcenter_validate_certs: |
| 210 |
default: true |
| 211 |
description: |
| 212 |
- Allows connection when SSL certificates are not valid. Set to C(false) when |
| 213 |
certificates are not trusted. |
| 214 |
- If the value is not specified in the task, the value of environment variable |
| 215 |
C(VMWARE_VALIDATE_CERTS) will be used instead. |
| 216 |
type: bool |
| 217 |
vm: |
| 218 |
description: |
| 219 |
- The unique identifier of the virtual machine that needs to be customized. |
| 220 |
- The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_info). |
| 221 |
This parameter is mandatory. |
| 222 |
required: true |
| 223 |
type: str |
| 224 |
author: |
| 225 |
- Ansible Cloud Team (@ansible-collections) |
| 226 |
version_added: 0.1.0 |
| 227 |
requirements: |
| 228 |
- vSphere 7.0.3 or greater |
| 229 |
- python >= 3.6 |
| 230 |
- aiohttp |
| 231 |
notes: |
| 232 |
- Tested on vSphere 7.0.3 |
| 233 |
""" |
| 234 |
|
| 235 |
EXAMPLES = r""" |
| 236 |
########## |
| 237 |
# |
| 238 |
# VM customization can be difficult to troubleshoot, since each environment is different. Here are some general tips: |
| 239 |
# |
| 240 |
# 1. Make sure perl is installed on the Linux systems. Make sure cloud-init is installed if using cloud-init |
| 241 |
# 2. Custom script execution is disabled by default. To enable it, you can run as root: vmware-toolbox-cmd config set deployPkg enable-custom-scripts true |
| 242 |
# 3. VMware tools must be installed and recognized by vCenter before you can apply customization. See the example below for one approach to this. |
| 243 |
# 4. On Linux (RHEL specifically), customization script logs can be found at /var/log/vmware-imc/toolsDeployPkg.log |
| 244 |
# 5. Once the VM is started, the pending customization is applied. Even if that fails, the customization is then cleared. Meaning, you need to re-apply |
| 245 |
# the customization spec in order to try again. Simply rebooting the VM will not change anything. |
| 246 |
# |
| 247 |
########## |
| 248 |
|
| 249 |
# |
| 250 |
# Here is the basic workflow for creating a new VM and then customizing it |
| 251 |
# |
| 252 |
- name: Deploy a new VM based on a template |
| 253 |
vmware.vmware_rest.vcenter_vmtemplate_libraryitems: |
| 254 |
name: vm-from-template |
| 255 |
library: "{{ library_id }}" |
| 256 |
template_library_item: "{{ template_id }}" |
| 257 |
placement: |
| 258 |
cluster: "{{ lookup('vmware.vmware_rest.cluster_moid', '/my_dc/host/my_cluster') }}" |
| 259 |
state: deploy |
| 260 |
register: my_new_vm |
| 261 |
|
| 262 |
# If your template already has vmtools installed and vCenter recognizes the installation (you should be able to see the tools version when the template |
| 263 |
# is cloned), then you can skip this block in your workflow. |
| 264 |
- name: Register VMware Tools with vCenter |
| 265 |
block: |
| 266 |
- name: Power on the VM |
| 267 |
vmware.vmware_rest.vcenter_vm_power: |
| 268 |
state: start |
| 269 |
vm: "{{ my_new_vm.id }}" |
| 270 |
- name: Wait until my VMware tools are recognized |
| 271 |
vmware.vmware_rest.vcenter_vm_tools_info: |
| 272 |
vm: "{{ my_new_vm.id }}" |
| 273 |
register: vm_tools_info |
| 274 |
until: |
| 275 |
- vm_tools_info is not failed |
| 276 |
- vm_tools_info.value.run_state == "RUNNING" |
| 277 |
retries: 60 |
| 278 |
delay: 5 |
| 279 |
- name: Power Off VM |
| 280 |
vmware.vmware_rest.vcenter_vm_power: |
| 281 |
state: stop |
| 282 |
vm: "{{ my_new_vm.id }}" |
| 283 |
|
| 284 |
- name: Customize the VM |
| 285 |
vmware.vmware_rest.vcenter_vm_guest_customization: |
| 286 |
vm: "{{ my_new_vm.id }}" |
| 287 |
global_DNS_settings: |
| 288 |
dns_suffix_list: |
| 289 |
- lan |
| 290 |
- foo.internal |
| 291 |
dns_servers: |
| 292 |
- "8.8.8.8" |
| 293 |
interfaces: |
| 294 |
- adapter: |
| 295 |
ipv4: |
| 296 |
type: DHCP |
| 297 |
configuration_spec: |
| 298 |
linux_config: |
| 299 |
domain: test |
| 300 |
hostname: |
| 301 |
fixed_name: myhost |
| 302 |
type: FIXED |
| 303 |
|
| 304 |
- name: Power on the VM |
| 305 |
vmware.vmware_rest.vcenter_vm_power: |
| 306 |
state: start |
| 307 |
vm: "{{ my_new_vm.id }}" |
| 308 |
|
| 309 |
# |
| 310 |
# Here is an example using the Linux script text. The script shebang can be anything (bash, perl, python), so long as the script will actually run |
| 311 |
# There is also size and length limitation on the script text, as described in the module documentation. |
| 312 |
# Finally, note the script is run twice. Once before all of the other customization and once after. |
| 313 |
# |
| 314 |
- name: Customize the VM |
| 315 |
vmware.vmware_rest.vcenter_vm_guest_customization: |
| 316 |
vm: "{{ my_new_vm.id }}" |
| 317 |
global_DNS_settings: |
| 318 |
dns_suffix_list: |
| 319 |
- lan |
| 320 |
- foo.internal |
| 321 |
dns_servers: |
| 322 |
- "8.8.8.8" |
| 323 |
interfaces: |
| 324 |
- adapter: |
| 325 |
ipv4: |
| 326 |
type: DHCP |
| 327 |
configuration_spec: |
| 328 |
linux_config: |
| 329 |
domain: test |
| 330 |
hostname: |
| 331 |
fixed_name: myhost |
| 332 |
type: FIXED |
| 333 |
script_text: | |
| 334 |
#!/bin/sh |
| 335 |
if [ x$1 == x"precustomization" ]; then |
| 336 |
echo "PRE" >> /tmp/vmware_rest_init_script.log |
| 337 |
# add any other pre-customization tasks here |
| 338 |
fi |
| 339 |
|
| 340 |
if [ x$1 == x"postcustomization" ]; then |
| 341 |
echo "POST" >> /tmp/vmware_rest_init_script.log |
| 342 |
# add any other post-customization tasks here |
| 343 |
fi |
| 344 |
|
| 345 |
# |
| 346 |
# Here is a simple example using cloud-init |
| 347 |
# See also: |
| 348 |
# https://developer.broadcom.com/xapis/vsphere-automation-api/latest/vcenter/data-structures/Guest_CloudinitConfiguration/ |
| 349 |
# https://knowledge.broadcom.com/external/article/311895/how-to-customize-virtual-machine-using-c.html |
| 350 |
# https://cloudinit.readthedocs.io/en/latest/reference/examples.html |
| 351 |
# https://cloudinit.readthedocs.io/en/23.4.1/reference/datasources/vmware.html#walkthrough-of-guestinfo-keys-transport |
| 352 |
# |
| 353 |
# cloud-init required: metadata as plain-text JSON/YAML, maximum 512KB file size |
| 354 |
# cloud-init optional: userdata as plain-text in raw cloud-init format with no compression / no base64 encoding, maximum 512KB file size |
| 355 |
# |
| 356 |
- name: Customize the VM |
| 357 |
vmware.vmware_rest.vcenter_vm_guest_customization: |
| 358 |
vm: "{{ my_new_vm.id }}" |
| 359 |
global_DNS_settings: |
| 360 |
dns_suffix_list: [] |
| 361 |
dns_servers: |
| 362 |
- "8.8.8.8" |
| 363 |
interfaces: |
| 364 |
- adapter: |
| 365 |
ipv4: |
| 366 |
type: DHCP |
| 367 |
configuration_spec: |
| 368 |
cloud_config: |
| 369 |
type: CLOUDINIT |
| 370 |
cloudinit: |
| 371 |
metadata: | |
| 372 |
instance-id: cloud-vm-example-1 |
| 373 |
local-hostname: cloud-vm |
| 374 |
network: |
| 375 |
config: disabled |
| 376 |
userdata: | |
| 377 |
#cloud-config |
| 378 |
disable_root: 0 |
| 379 |
write_files: |
| 380 |
- content: | |
| 381 |
This is a test |
| 382 |
path: /root/cloud-init-example |
| 383 |
|
| 384 |
# |
| 385 |
# Here is a more complex cloud-init example |
| 386 |
# |
| 387 |
- name: Set cloud-init variables for customization specification |
| 388 |
ansible.builtin.set_fact: |
| 389 |
metadata_yaml: |
| 390 |
instance-id: "{{ vm_name }}" |
| 391 |
hostname: "{{ vm_name }}" |
| 392 |
local-hostname: "{{ vm_name }}" |
| 393 |
network: |
| 394 |
version: 2 |
| 395 |
ethernets: |
| 396 |
nics: |
| 397 |
match: |
| 398 |
name: e* |
| 399 |
dhcp4: true |
| 400 |
dhcp6: false |
| 401 |
public_ssh_keys: |
| 402 |
- "{{ lookup('ansible.builtin.file', vmware_vm_ssh_public_key_file_path) }}" |
| 403 |
|
| 404 |
userdata_yaml_text: | |
| 405 |
#cloud-config |
| 406 |
hostname: {{ vm_name }} |
| 407 |
fqdn: {{ vm_name }}.{{ vm_domain }} |
| 408 |
|
| 409 |
disable_root: false |
| 410 |
ssh_pwauth: false |
| 411 |
ssh_deletekeys: true |
| 412 |
ssh: |
| 413 |
emit_keys_to_console: false |
| 414 |
no_ssh_fingerprints: false |
| 415 |
ssh_authorized_keys: |
| 416 |
- {{ lookup('ansible.builtin.file', vmware_vm_ssh_public_key_file_path) }} |
| 417 |
|
| 418 |
users: |
| 419 |
- name: root |
| 420 |
ssh_authorized_keys: |
| 421 |
- {{ lookup('ansible.builtin.file', vmware_vm_ssh_public_key_file_path) }} |
| 422 |
lock_passwd: false |
| 423 |
|
| 424 |
write_files: |
| 425 |
- path: /etc/cloud/cloud-init.disabled |
| 426 |
permissions: "0644" |
| 427 |
content: "" |
| 428 |
|
| 429 |
- name: Apply customization specification to the VM in Powered Off state |
| 430 |
vmware.vmware_rest.vcenter_vm_guest_customization: |
| 431 |
vm: "{{ my_new_vm.id }}" |
| 432 |
configuration_spec: |
| 433 |
cloud_config: |
| 434 |
type: CLOUDINIT |
| 435 |
cloudinit: |
| 436 |
metadata: "{{ metadata_yaml | to_json(ensure_ascii=true) }}" |
| 437 |
userdata: "{{ userdata_yaml_text | trim }}" # remove last newline character |
| 438 |
interfaces: [] |
| 439 |
global_DNS_settings: {} |
| 440 |
""" |
| 441 |
|
| 442 |
RETURN = r""" |
| 443 |
# content generated by the update_return_section callback# task: Customize the VM |
| 444 |
value: |
| 445 |
description: Customize the VM |
| 446 |
returned: On success |
| 447 |
sample: {} |
| 448 |
type: dict |
| 449 |
""" |
| 450 |
|
| 451 |
|
| 452 |
# This structure describes the format of the data expected by the end-points |
| 453 |
PAYLOAD_FORMAT = { |
| 454 |
"set": { |
| 455 |
"query": {}, |
| 456 |
"body": { |
| 457 |
"configuration_spec": "spec/configuration_spec", |
| 458 |
"global_DNS_settings": "spec/global_DNS_settings", |
| 459 |
"interfaces": "spec/interfaces", |
| 460 |
}, |
| 461 |
"path": {"vm": "vm"}, |
| 462 |
} |
| 463 |
} # pylint: disable=line-too-long |
| 464 |
|
| 465 |
from ansible.module_utils.basic import env_fallback |
| 466 |
import os |
| 467 |
|
| 468 |
if os.getenv("VMWARE_ENABLE_TURBO", False): |
| 469 |
try: |
| 470 |
from ansible_collections.cloud.common.plugins.module_utils.turbo.module import ( |
| 471 |
AnsibleTurboModule as AnsibleModule, |
| 472 |
) |
| 473 |
|
| 474 |
AnsibleModule.collection_name = "vmware.vmware_rest" |
| 475 |
except ImportError: |
| 476 |
from ansible.module_utils.basic import AnsibleModule |
| 477 |
else: |
| 478 |
from ansible.module_utils.basic import AnsibleModule |
| 479 |
|
| 480 |
from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import ( |
| 481 |
exists, |
| 482 |
gen_args, |
| 483 |
get_subdevice_type, |
| 484 |
open_session, |
| 485 |
prepare_payload, |
| 486 |
session_timeout, |
| 487 |
update_changed_flag, |
| 488 |
) |
| 489 |
|
| 490 |
|
| 491 |
def prepare_argument_spec(): |
| 492 |
argument_spec = { |
| 493 |
"vcenter_hostname": dict( |
| 494 |
type="str", |
| 495 |
required=True, |
| 496 |
fallback=(env_fallback, ["VMWARE_HOST"]), |
| 497 |
), |
| 498 |
"vcenter_username": dict( |
| 499 |
type="str", |
| 500 |
required=True, |
| 501 |
fallback=(env_fallback, ["VMWARE_USER"]), |
| 502 |
), |
| 503 |
"vcenter_password": dict( |
| 504 |
type="str", |
| 505 |
required=True, |
| 506 |
no_log=True, |
| 507 |
fallback=(env_fallback, ["VMWARE_PASSWORD"]), |
| 508 |
), |
| 509 |
"vcenter_validate_certs": dict( |
| 510 |
type="bool", |
| 511 |
required=False, |
| 512 |
default=True, |
| 513 |
fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]), |
| 514 |
), |
| 515 |
"vcenter_rest_log_file": dict( |
| 516 |
type="str", |
| 517 |
required=False, |
| 518 |
fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]), |
| 519 |
), |
| 520 |
"session_timeout": dict( |
| 521 |
type="float", |
| 522 |
required=False, |
| 523 |
fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]), |
| 524 |
), |
| 525 |
} |
| 526 |
|
| 527 |
argument_spec["configuration_spec"] = {"required": True, "type": "dict"} |
| 528 |
argument_spec["global_DNS_settings"] = {"required": True, "type": "dict"} |
| 529 |
argument_spec["interfaces"] = {"required": True, "type": "list", "elements": "dict"} |
| 530 |
argument_spec["state"] = {"type": "str", "choices": ["set"], "default": "set"} |
| 531 |
argument_spec["vm"] = {"required": True, "type": "str"} |
| 532 |
|
| 533 |
return argument_spec |
| 534 |
|
| 535 |
|
| 536 |
async def main(): |
| 537 |
required_if = list([]) |
| 538 |
|
| 539 |
module_args = prepare_argument_spec() |
| 540 |
module = AnsibleModule( |
| 541 |
argument_spec=module_args, required_if=required_if, supports_check_mode=False |
| 542 |
) |
| 543 |
if not module.params["vcenter_hostname"]: |
| 544 |
module.fail_json("vcenter_hostname cannot be empty") |
| 545 |
if not module.params["vcenter_username"]: |
| 546 |
module.fail_json("vcenter_username cannot be empty") |
| 547 |
if not module.params["vcenter_password"]: |
| 548 |
module.fail_json("vcenter_password cannot be empty") |
| 549 |
try: |
| 550 |
session = await open_session( |
| 551 |
vcenter_hostname=module.params["vcenter_hostname"], |
| 552 |
vcenter_username=module.params["vcenter_username"], |
| 553 |
vcenter_password=module.params["vcenter_password"], |
| 554 |
validate_certs=module.params["vcenter_validate_certs"], |
| 555 |
log_file=module.params["vcenter_rest_log_file"], |
| 556 |
) |
| 557 |
except Exception as err: |
| 558 |
if hasattr(err, "get_message"): |
| 559 |
module.fail_json(err.get_message()) |
| 560 |
else: |
| 561 |
module.fail_json(str(err)) |
| 562 |
result = await entry_point(module, session) |
| 563 |
module.exit_json(**result) |
| 564 |
|
| 565 |
|
| 566 |
# template: default_module.j2 |
| 567 |
def build_url(params): |
| 568 |
return ( |
| 569 |
"https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/guest/customization" |
| 570 |
).format(**params) |
| 571 |
|
| 572 |
|
| 573 |
async def entry_point(module, session): |
| 574 |
|
| 575 |
if module.params["state"] == "present": |
| 576 |
if "_create" in globals(): |
| 577 |
operation = "create" |
| 578 |
else: |
| 579 |
operation = "update" |
| 580 |
elif module.params["state"] == "absent": |
| 581 |
operation = "delete" |
| 582 |
else: |
| 583 |
operation = module.params["state"] |
| 584 |
|
| 585 |
func = globals()["_" + operation] |
| 586 |
|
| 587 |
return await func(module.params, session) |
| 588 |
|
| 589 |
|
| 590 |
async def _set(params, session): |
| 591 |
_in_query_parameters = PAYLOAD_FORMAT["set"]["query"].keys() |
| 592 |
payload = prepare_payload(params, PAYLOAD_FORMAT["set"]) |
| 593 |
subdevice_type = get_subdevice_type("/api/vcenter/vm/{vm}/guest/customization") |
| 594 |
if subdevice_type and not params[subdevice_type]: |
| 595 |
_json = await exists(params, session, build_url(params)) |
| 596 |
if _json: |
| 597 |
params[subdevice_type] = _json["id"] |
| 598 |
_url = ( |
| 599 |
"https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/guest/customization" |
| 600 |
).format(**params) + gen_args(params, _in_query_parameters) |
| 601 |
async with session.get(_url, json=payload, **session_timeout(params)) as resp: |
| 602 |
before = await resp.json() |
| 603 |
|
| 604 |
async with session.put(_url, json=payload, **session_timeout(params)) as resp: |
| 605 |
try: |
| 606 |
if resp.headers["Content-Type"] == "application/json": |
| 607 |
_json = await resp.json() |
| 608 |
except KeyError: |
| 609 |
_json = {} |
| 610 |
if "value" not in _json: # 7.0.2 |
| 611 |
_json = {"value": _json} |
| 612 |
|
| 613 |
# The PUT answer does not let us know if the resource has actually been |
| 614 |
# modified |
| 615 |
if resp.status < 300: |
| 616 |
async with session.get( |
| 617 |
_url, json=payload, **session_timeout(params) |
| 618 |
) as resp_get: |
| 619 |
after = await resp_get.json() |
| 620 |
if before == after: |
| 621 |
return await update_changed_flag(after, resp_get.status, "get") |
| 622 |
return await update_changed_flag(_json, resp.status, "set") |
| 623 |
|
| 624 |
|
| 625 |
if __name__ == "__main__": |
| 626 |
import asyncio |
| 627 |
|
| 628 |
current_loop = asyncio.new_event_loop() |
| 629 |
try: |
| 630 |
asyncio.set_event_loop(current_loop) |
| 631 |
current_loop.run_until_complete(main()) |
| 632 |
finally: |
| 633 |
current_loop.close() |