Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_virtualmachine.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2016 Matt Davis, <[email protected]>
4 # Chris Houseknecht, <[email protected]>
5 # Copyright (c) 2018 James E. King, III (@jeking3) <[email protected]>
6 #
7 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
8
9 from __future__ import absolute_import, division, print_function
10 __metaclass__ = type
11
12
13 DOCUMENTATION = '''
14 ---
15 module: azure_rm_virtualmachine
16
17 version_added: "0.1.2"
18
19 short_description: Manage Azure virtual machines
20
21 description:
22 - Manage and configure virtual machines (VMs) and associated resources on Azure.
23 - Requires a resource group containing at least one virtual network with at least one subnet.
24 - Supports images from the Azure Marketplace, which can be discovered with M(azure.azcollection.azure_rm_virtualmachineimage_info).
25 - Supports custom images since Ansible 2.5.
26 - To use I(custom_data) on a Linux image, the image must have cloud-init enabled. If cloud-init is not enabled, I(custom_data) is ignored.
27
28 options:
29 resource_group:
30 description:
31 - Name of the resource group containing the VM.
32 required: true
33 type: str
34 name:
35 description:
36 - Name of the VM.
37 required: true
38 type: str
39 custom_data:
40 description:
41 - Data made available to the VM and used by C(cloud-init).
42 - Only used on Linux images with C(cloud-init) enabled.
43 - Consult U(https://docs.microsoft.com/en-us/azure/virtual-machines/linux/using-cloud-init#cloud-init-overview) for cloud-init ready images.
44 - To enable cloud-init on a Linux image, follow U(https://docs.microsoft.com/en-us/azure/virtual-machines/linux/cloudinit-prepare-custom-image).
45 type: str
46 state:
47 description:
48 - State of the VM.
49 - Set to C(present) to create a VM with the configuration specified by other options, or to update the configuration of an existing VM.
50 - Set to C(absent) to remove a VM.
51 - Does not affect power state. Use I(started)/I(allocated)/I(restarted) parameters to change the power state of a VM.
52 default: present
53 type: str
54 choices:
55 - absent
56 - present
57 started:
58 description:
59 - Whether the VM is started or stopped.
60 - Set to C(true) with I(state=present) to start the VM.
61 - Set to C(false) to stop the VM.
62 type: bool
63 force:
64 description:
65 - Use more force during stop of VM
66 - Set to C(true) with I(started=false) to stop the VM forcefully (hard poweroff -- skip_shutdown)
67 - Set to C(false) to power off gracefully
68 default: false
69 type: bool
70 allocated:
71 description:
72 - Whether the VM is allocated or deallocated, only useful with I(state=present).
73 default: True
74 type: bool
75 generalized:
76 description:
77 - Whether the VM is generalized or not.
78 - Set to C(true) with I(state=present) to generalize the VM.
79 - Generalizing a VM is irreversible.
80 type: bool
81 default: False
82 restarted:
83 description:
84 - Set to C(true) with I(state=present) to restart a running VM.
85 default: False
86 type: bool
87 location:
88 description:
89 - Valid Azure location for the VM. Defaults to location of the resource group.
90 type: str
91 short_hostname:
92 description:
93 - Name assigned internally to the host. On a Linux VM this is the name returned by the C(hostname) command.
94 - When creating a VM, short_hostname defaults to I(name).
95 type: str
96 vm_size:
97 description:
98 - A valid Azure VM size value. For example, C(Standard_D4).
99 - Choices vary depending on the subscription and location. Check your subscription for available choices.
100 - Required when creating a VM.
101 type: str
102 priority:
103 description:
104 - Priority of the VM.
105 - C(None) is the equivalent of Regular VM.
106 type: str
107 choices:
108 - None
109 - Spot
110 eviction_policy:
111 description:
112 - Specifies the eviction policy for the Azure Spot virtual machine.
113 - Requires priority to be set to Spot.
114 type: str
115 choices:
116 - Deallocate
117 - Delete
118 max_price:
119 description:
120 - Specifies the maximum price you are willing to pay for a Azure Spot VM/VMSS.
121 - This price is in US Dollars.
122 - C(-1) indicates default price to be up-to on-demand.
123 - Requires priority to be set to Spot.
124 type: float
125 default: -1
126 admin_username:
127 description:
128 - Admin username used to access the VM after it is created.
129 - Required when creating a VM.
130 type: str
131 admin_password:
132 description:
133 - Password for the admin username.
134 - Not required if the I(os_type=Linux) and SSH password authentication is disabled by setting I(ssh_password_enabled=false).
135 type: str
136 ssh_password_enabled:
137 description:
138 - Whether to enable or disable SSH passwords.
139 - When I(os_type=Linux), set to C(false) to disable SSH password authentication and require use of SSH keys.
140 default: true
141 type: bool
142 ssh_public_keys:
143 description:
144 - For I(os_type=Linux) provide a list of SSH keys.
145 - Accepts a list of dicts where each dictionary contains two keys, I(path) and I(key_data).
146 - Set I(path) to the default location of the authorized_keys files. For example, I(path=/home/<admin username>/.ssh/authorized_keys).
147 - Set I(key_data) to the actual value of the public key.
148 type: list
149 elements: dict
150 image:
151 description:
152 - The image used to build the VM.
153 - For custom images, the name of the image. To narrow the search to a specific resource group, a dict with the keys I(name) and I(resource_group).
154 - For community images, a dict with the keys I(community_gallery_image_id). Specified the community gallery image unique id for vm demployment.
155 - The I(community_gallery_image_id) can be fetched from shared gallery image GET call.
156 - For Marketplace images, a dict with the keys I(publisher), I(offer), I(sku), and I(version).
157 - Set I(version=latest) to get the most recent version of a given image.
158 - For share gallery image, a dict with the keys I(shared_gallery_image_id). Specified the shared gallery image unique id for vm deployment.
159 This can be fetched from shared gallery image GET call.
160 - Required when creating.
161 type: raw
162 availability_set:
163 description:
164 - Name or ID of an existing availability set to add the VM to. The I(availability_set) should be in the same resource group as VM.
165 type: str
166 capacity_reservation_group:
167 description:
168 - The name or ID of the capacity reservation group to be associated with.
169 type: dict
170 suboptions:
171 id:
172 description:
173 - The ID of the capacity reservation group to be associated with.
174 type: str
175 name:
176 description:
177 - The Name of the capacity reservation group to be associated with.
178 type: str
179 resource_group:
180 description:
181 - The resource group of capcacity reservation group to be associated with.
182 type: str
183 proximity_placement_group:
184 description:
185 - The name or ID of the proximity placement group to be associated with.
186 type: dict
187 suboptions:
188 id:
189 description:
190 - The ID of the proximity placement group to be associated with.
191 type: str
192 name:
193 description:
194 - The Name of the proximity placement group to be associated with.
195 type: str
196 resource_group:
197 description:
198 - The resource group of the proximity placement group to be associated with.
199 type: str
200 storage_account_name:
201 description:
202 - Name of a storage account that supports creation of VHD blobs.
203 - If not specified for a new VM, a new storage account named <vm name>01 will be created using storage type C(Standard_LRS).
204 type: str
205 aliases:
206 - storage_account
207 storage_container_name:
208 description:
209 - Name of the container to use within the storage account to store VHD blobs.
210 - If not specified, a default container will be created.
211 default: vhds
212 type: str
213 aliases:
214 - storage_container
215 storage_blob_name:
216 description:
217 - Name of the storage blob used to hold the OS disk image of the VM.
218 - Must end with '.vhd'.
219 - If not specified, defaults to the VM name + '.vhd'.
220 type: str
221 aliases:
222 - storage_blob
223 managed_disk_type:
224 description:
225 - Managed OS disk type.
226 - Create OS disk with managed disk if defined.
227 - If not defined, the OS disk will be created with virtual hard disk (VHD).
228 type: str
229 choices:
230 - Standard_LRS
231 - StandardSSD_LRS
232 - StandardSSD_ZRS
233 - Premium_LRS
234 - Premium_ZRS
235 - UltraSSD_LRS
236 os_disk_name:
237 description:
238 - OS disk name.
239 type: str
240 os_disk_caching:
241 description:
242 - Type of OS disk caching.
243 type: str
244 choices:
245 - None
246 - ReadOnly
247 - ReadWrite
248 aliases:
249 - disk_caching
250 os_disk_size_gb:
251 description:
252 - Size of OS disk in GB.
253 type: int
254 os_disk_encryption_set:
255 description:
256 - ID of disk encryption set for OS disk.
257 type: str
258 os_type:
259 description:
260 - Base type of operating system.
261 type: str
262 choices:
263 - Windows
264 - Linux
265 - windows
266 - linux
267 default: Linux
268 ephemeral_os_disk:
269 description:
270 - Parameters of ephemeral disk settings that can be specified for operating system disk.
271 - Ephemeral OS disk is only supported for VMS Instances using Managed Disk.
272 - If the VM gets deleted, the ephemeral OS disk will be deleted and cannot be detached.
273 type: bool
274 data_disks:
275 description:
276 - Describes list of data disks.
277 - Use M(azure.azcollection.azure_rm_manageddisk) to manage the specific disk.
278 type: list
279 elements: dict
280 suboptions:
281 lun:
282 description:
283 - The logical unit number for data disk.
284 - This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM.
285 required: true
286 type: int
287 name:
288 description:
289 - The disk name.
290 type: str
291 disk_size_gb:
292 description:
293 - The initial disk size in GB for blank data disks.
294 - This value cannot be larger than C(1023) GB.
295 - Size can be changed only when the virtual machine is deallocated.
296 - Not sure when I(managed_disk_id) defined.
297 type: int
298 disk_encryption_set:
299 description:
300 - ID of disk encryption set for data disk.
301 type: str
302 managed_disk_id:
303 description:
304 - The ID of the existing data disk.
305 - If specified, attach mode will be chosen.
306 type: str
307 managed_disk_type:
308 description:
309 - Managed data disk type.
310 - Only used when OS disk created with managed disk.
311 type: str
312 choices:
313 - Standard_LRS
314 - StandardSSD_LRS
315 - StandardSSD_ZRS
316 - Premium_LRS
317 - Premium_ZRS
318 - UltraSSD_LRS
319 storage_account_name:
320 description:
321 - Name of an existing storage account that supports creation of VHD blobs.
322 - If not specified for a new VM, a new storage account started with I(name) will be created using storage type C(Standard_LRS).
323 - Only used when OS disk created with virtual hard disk (VHD).
324 - Used when I(managed_disk_type) not defined.
325 - Cannot be updated unless I(lun) updated.
326 type: str
327 storage_container_name:
328 description:
329 - Name of the container to use within the storage account to store VHD blobs.
330 - If no name is specified a default container named 'vhds' will created.
331 - Only used when OS disk created with virtual hard disk (VHD).
332 - Used when I(managed_disk_type) not defined.
333 - Cannot be updated unless I(lun) updated.
334 type: str
335 default: vhds
336 storage_blob_name:
337 description:
338 - Name of the storage blob used to hold the OS disk image of the VM.
339 - Must end with '.vhd'.
340 - Default to the I(name) + timestamp + I(lun) + '.vhd'.
341 - Only used when OS disk created with virtual hard disk (VHD).
342 - Used when I(managed_disk_type) not defined.
343 - Cannot be updated unless I(lun) updated.
344 type: str
345 caching:
346 description:
347 - Type of data disk caching.
348 type: str
349 choices:
350 - None
351 - ReadOnly
352 - ReadWrite
353 create_option:
354 description:
355 - Specifies how the data disk should be created.
356 - Use C(Empty) to create a new blank data disk.
357 - Use C(FromImage) to create the data disk from a custom image that includes data disks at the matching LUN.
358 - When set to C(FromImage), you can combine with I(managed_disk_type) to override the disk type defined in the image.
359 - Not used when I(managed_disk_id) is specified (attach mode is chosen automatically).
360 type: str
361 default: Empty
362 choices:
363 - Empty
364 - FromImage
365 delete_option:
366 description:
367 - Specifies the delete behavior for the data disk when deleting the VM.
368 - Azure default to Detach if no specified.
369 - When set to C(Delete), the data disk is removed during VM deletion.
370 - When set to C(Detach), the data disk is preserved.
371 type: str
372 choices:
373 - Delete
374 - Detach
375 public_ip_allocation_method:
376 description:
377 - Allocation method for the public IP of the VM.
378 - Used only if a network interface is not specified.
379 - When set to C(Dynamic), the public IP address may change any time the VM is rebooted or power cycled.
380 - The C(Disabled) choice was added in Ansible 2.6.
381 type: str
382 choices:
383 - Dynamic
384 - Static
385 - Disabled
386 default: Static
387 aliases:
388 - public_ip_allocation
389 open_ports:
390 description:
391 - List of ports to open in the security group for the VM, when a security group and network interface are created with a VM.
392 - For Linux hosts, defaults to allowing inbound TCP connections to port 22.
393 - For Windows hosts, defaults to opening ports 3389 and 5986.
394 type: list
395 elements: str
396 network_interface_names:
397 description:
398 - Network interface names to add to the VM.
399 - Can be a string of name or resource ID of the network interface.
400 - Can be a dict containing I(resource_group) and I(name) of the network interface.
401 - If a network interface name is not provided when the VM is created, a default network interface and public IP address will be created.
402 - If the VM gets deleted, the default network interface and default public IP address will be deleted as well.
403 - To create a new network interface, at least one Virtual Network with one Subnet must exist.
404 type: list
405 elements: raw
406 aliases:
407 - network_interfaces
408 virtual_network_resource_group:
409 description:
410 - The resource group to use when creating a VM with another resource group's virtual network.
411 type: str
412 virtual_network_name:
413 description:
414 - The virtual network to use when creating a VM.
415 - If not specified, a new network interface will be created and assigned to the first virtual network found in the resource group.
416 - Use with I(virtual_network_resource_group) to place the virtual network in another resource group.
417 type: str
418 aliases:
419 - virtual_network
420 subnet_name:
421 description:
422 - Subnet for the VM.
423 - Defaults to the first subnet found in the virtual network or the subnet of the I(network_interface_name), if provided.
424 - If the subnet is in another resource group, specify the resource group with I(virtual_network_resource_group).
425 type: str
426 aliases:
427 - subnet
428 created_nsg:
429 description:
430 - Whether network security group created and attached to network interface or not.
431 type: bool
432 default: True
433 version_added: '1.16.0'
434 remove_on_absent:
435 description:
436 - Associated resources to remove when removing a VM using I(state=absent).
437 - To remove all resources related to the VM being removed, including auto-created resources, set to C(all).
438 - To remove only resources that were automatically created while provisioning the VM being removed, set to C(all_autocreated).
439 - To remove only specific resources, set to C(network_interfaces), C(virtual_storage) or C(public_ips).
440 - Any other input will be ignored.
441 type: list
442 elements: str
443 default: ['all']
444 plan:
445 description:
446 - Third-party billing plan for the VM.
447 type: dict
448 suboptions:
449 name:
450 description:
451 - Billing plan name.
452 required: true
453 type: str
454 product:
455 description:
456 - Product name.
457 required: true
458 type: str
459 publisher:
460 description:
461 - Publisher offering the plan.
462 required: true
463 type: str
464 promotion_code:
465 description:
466 - Optional promotion code.
467 type: str
468 accept_terms:
469 description:
470 - Accept terms for Marketplace images that require it.
471 - Only Azure service admin/account admin users can purchase images from the Marketplace.
472 - Only valid when a I(plan) is specified.
473 type: bool
474 default: false
475 zones:
476 description:
477 - A list of Availability Zones for your VM.
478 - A maximum of one zone can be configured.
479 type: list
480 elements: str
481 license_type:
482 description:
483 - On-premise license for the image or disk.
484 - Only used for images that contain the Windows Server operating system.
485 - To remove all license type settings, set to the string C(None).
486 type: str
487 choices:
488 - Windows_Server
489 - Windows_Client
490 - RHEL_BYOS
491 - SLES_BYOS
492 vm_identity:
493 description:
494 - Identity for the VM.
495 type: dict
496 suboptions:
497 type:
498 description:
499 - Type of the managed identity
500 required: true
501 choices:
502 - SystemAssigned
503 - UserAssigned
504 - SystemAssigned, UserAssigned
505 - None
506 type: str
507 user_assigned_identities:
508 description:
509 - User Assigned Managed Identities and its options
510 required: false
511 type: dict
512 default: {}
513 suboptions:
514 id:
515 description:
516 - List of the user assigned identities IDs associated to the VM
517 required: false
518 type: list
519 elements: str
520 default: []
521 append:
522 description:
523 - If the list of identities has to be appended to current identities (true) or if it has to replace current identities (false)
524 required: false
525 type: bool
526 default: True
527 winrm:
528 description:
529 - List of Windows Remote Management configurations of the VM.
530 type: list
531 elements: dict
532 suboptions:
533 protocol:
534 description:
535 - The protocol of the winrm listener.
536 required: true
537 type: str
538 choices:
539 - http
540 - https
541 source_vault:
542 description:
543 - The relative URL of the Key Vault containing the certificate.
544 type: str
545 certificate_url:
546 description:
547 - The URL of a certificate that has been uploaded to Key Vault as a secret.
548 type: str
549 certificate_store:
550 description:
551 - The certificate store on the VM to which the certificate should be added.
552 - The specified certificate store is implicitly in the LocalMachine account.
553 type: str
554 boot_diagnostics:
555 type: dict
556 description:
557 - Manage boot diagnostics settings for a VM.
558 - Boot diagnostics includes a serial console and remote console screenshots.
559 suboptions:
560 enabled:
561 description:
562 - Flag indicating if boot diagnostics are enabled.
563 type: bool
564 type:
565 description:
566 - Should the storage account be managed by azure or a custom storage account
567 - It is mutually exclusive with suboption I(storage_account) and I(resource_group)
568 required: false
569 type: str
570 choices:
571 - managed
572 storage_account:
573 description:
574 - The name of an existing storage account to use for boot diagnostics.
575 - If not specified, uses I(storage_account_name) defined one level up.
576 - If storage account is not specified anywhere, and C(enabled) is C(true), a default storage account is created for boot diagnostics data.
577 - It is mutually exclusive with I(type)
578 type: str
579 required: false
580 resource_group:
581 description:
582 - Resource group where the storage account is located.
583 - It is mutually exclusive with I(type)
584 type: str
585 linux_config:
586 description:
587 - Specifies the Linux operating system settings on the virtual machine.
588 type: dict
589 suboptions:
590 disable_password_authentication:
591 description:
592 - Specifies whether password authentication should be disabled.
593 type: bool
594 windows_config:
595 description:
596 - Specifies Windows operating system settings on the virtual machine.
597 type: dict
598 suboptions:
599 provision_vm_agent:
600 description:
601 - Indicates whether virtual machine agent should be provisioned on the virtual machine.
602 type: bool
603 required: True
604 enable_automatic_updates:
605 description:
606 - Indicates whether Automatic Updates is enabled for the Windows virtual machine.
607 type: bool
608 required: True
609 security_profile:
610 description:
611 - Specifies the Security related profile settings for the virtual machine.
612 type: dict
613 suboptions:
614 encryption_at_host:
615 description:
616 - This property can be used by user in the request to enable or disable the Host Encryption for the virtual machine.
617 - This will enable the encryption for all the disks including Resource/Temp disk at host itself.
618 type: bool
619 security_type:
620 description:
621 - Specifies the SecurityType of the virtual machine.
622 - It is set as TrustedLaunch to enable UefiSettings.
623 type: str
624 choices:
625 - TrustedLaunch
626 uefi_settings:
627 description:
628 - Specifies the security settings like secure boot and vTPM used while creating the virtual machine.
629 type: dict
630 suboptions:
631 secure_boot_enabled:
632 description:
633 - Specifies whether secure boot should be enabled on the virtual machine.
634 type: bool
635 v_tpm_enabled:
636 description:
637 - Specifies whether vTPM should be enabled on the virtual machine.
638 type: bool
639 swap_os_disk:
640 description:
641 - The swap OS disk parameters.
642 type: dict
643 suboptions:
644 os_disk_id:
645 description:
646 - The swap OS disk's ID.
647 type: str
648 os_disk_name:
649 description:
650 - The swap OS disk's name.
651 type: str
652 os_disk_resource_group:
653 description:
654 - The swap OS disk's resource group.
655 type: str
656 additional_capabilities:
657 description:
658 - Enables or disables a capability on the virtual machine.
659 type: dict
660 suboptions:
661 ultra_ssd_enabled:
662 description:
663 - The flag that enables or disables a capability to have one or more managed data disks with UltraSSD_LRS storage account type on the VM.
664 - Managed disks with storage account type UltraSSD_LRS can be added to a virtual machine set only if this property is enabled.
665 type: bool
666 user_data:
667 description:
668 - UserData for the VM, which must be base-64 encoded.
669 - Customer should notpass any secrets in here. Minimum api-version '2021-03-01'.
670 type: str
671 os_disk_delete_option:
672 description:
673 - Specifies the delete behavior for the VM's OS disk when VM is deleted.
674 - Azure default to Detach if no specified.
675 - When set to C(Delete), the OS disk will be removed automatically during VM deletion.
676 - When set to C(Detach), the OS disk will be preserved.
677 type: str
678 choices:
679 - Delete
680 - Detach
681
682 extends_documentation_fragment:
683 - azure.azcollection.azure
684 - azure.azcollection.azure_tags
685
686 author:
687 - Chris Houseknecht (@chouseknecht)
688 - Matt Davis (@nitzmahone)
689 - Christopher Perrin (@cperrin88)
690 - James E. King III (@jeking3)
691 '''
692
693 EXAMPLES = '''
694
695 - name: Create VM with defaults
696 azure_rm_virtualmachine:
697 resource_group: myResourceGroup
698 name: testvm10
699 admin_username: "{{ username }}"
700 admin_password: "{{ password }}"
701 image:
702 offer: CentOS
703 publisher: OpenLogic
704 sku: '7.1'
705 version: latest
706
707 - name: Create an availability set for managed disk vm
708 azure_rm_availabilityset:
709 name: avs-managed-disk
710 resource_group: myResourceGroup
711 platform_update_domain_count: 5
712 platform_fault_domain_count: 2
713 sku: Aligned
714
715 - name: Create a VM with managed disk
716 azure_rm_virtualmachine:
717 resource_group: myResourceGroup
718 name: vm-managed-disk
719 admin_username: "{{ username }}"
720 availability_set: avs-managed-disk
721 managed_disk_type: Standard_LRS
722 image:
723 offer: 0001-com-ubuntu-server-focal
724 publisher: canonical
725 sku: 20_04-lts-gen2
726 version: latest
727 vm_size: Standard_D4
728
729 - name: Create a VM with existing storage account and NIC
730 azure_rm_virtualmachine:
731 resource_group: myResourceGroup
732 name: testvm002
733 vm_size: Standard_D4
734 storage_account: testaccount001
735 admin_username: "{{ username }}"
736 ssh_public_keys:
737 - path: /home/adminUser/.ssh/authorized_keys
738 key_data: < insert your ssh public key here... >
739 network_interfaces: testvm001
740 image:
741 offer: CentOS
742 publisher: OpenLogic
743 sku: '7.1'
744 version: latest
745
746 - name: Create a VM with OS and multiple data managed disks
747 azure_rm_virtualmachine:
748 resource_group: myResourceGroup
749 name: testvm001
750 vm_size: Standard_D4
751 managed_disk_type: Standard_LRS
752 admin_username: "{{ username }}"
753 ssh_public_keys:
754 - path: /home/adminUser/.ssh/authorized_keys
755 key_data: < insert your ssh public key here... >
756 image:
757 offer: 0001-com-ubuntu-server-focal
758 publisher: canonical
759 sku: 20_04-lts-gen2
760 version: latest
761 data_disks:
762 - lun: 0
763 managed_disk_id: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/myDisk"
764 - lun: 1
765 name: newdisk
766 disk_size_gb: 128
767 managed_disk_type: Premium_LRS
768
769 - name: Create a VM with OS and multiple data storage accounts
770 azure_rm_virtualmachine:
771 resource_group: myResourceGroup
772 name: testvm001
773 vm_size: Standard_DS1_v2
774 admin_username: "{{ username }}"
775 ssh_password_enabled: false
776 ssh_public_keys:
777 - path: /home/adminUser/.ssh/authorized_keys
778 key_data: < insert your ssh public key here... >
779 network_interfaces: testvm001
780 storage_container: osdisk
781 storage_blob: osdisk.vhd
782 boot_diagnostics:
783 enabled: true
784 type: managed
785 image:
786 offer: 0001-com-ubuntu-server-focal
787 publisher: canonical
788 sku: 20_04-lts-gen2
789 version: latest
790 data_disks:
791 - lun: 0
792 disk_size_gb: 64
793 storage_container_name: datadisk1
794 storage_blob_name: datadisk1.vhd
795 - lun: 1
796 disk_size_gb: 128
797 storage_container_name: datadisk2
798 storage_blob_name: datadisk2.vhd
799
800 - name: Create a VM with a custom image
801 azure_rm_virtualmachine:
802 resource_group: myResourceGroup
803 name: testvm001
804 vm_size: Standard_DS1_v2
805 admin_username: "{{ username }}"
806 admin_password: "{{ password }}"
807 image: customimage001
808
809 - name: Create a VM with a custom image from a particular resource group
810 azure_rm_virtualmachine:
811 resource_group: myResourceGroup
812 name: testvm001
813 vm_size: Standard_DS1_v2
814 admin_username: "{{ username }}"
815 admin_password: "{{ password }}"
816 image:
817 name: customimage001
818 resource_group: myResourceGroup
819
820 - name: Create a VM with an image id
821 azure_rm_virtualmachine:
822 resource_group: myResourceGroup
823 name: testvm001
824 vm_size: Standard_DS1_v2
825 admin_username: "{{ username }}"
826 admin_password: "{{ password }}"
827 image:
828 id: '{{image_id}}'
829
830 - name: Create a VM from a custom image and override data disk types
831 azure_rm_virtualmachine:
832 resource_group: myResourceGroup
833 name: testvm001
834 vm_size: Standard_DS1_v2
835 admin_username: "{{ username }}"
836 admin_password: "{{ password }}"
837 managed_disk_type: StandardSSD_LRS
838 image:
839 id: '{{ image_id }}'
840 data_disks:
841 - lun: 0
842 create_option: FromImage
843 managed_disk_type: StandardSSD_LRS
844 - lun: 1
845 create_option: FromImage
846 managed_disk_type: StandardSSD_LRS
847
848 - name: Create a VM with spcified OS disk size
849 azure_rm_virtualmachine:
850 resource_group: myResourceGroup
851 name: big-os-disk
852 admin_username: "{{ username }}"
853 admin_password: "{{ password }}"
854 os_disk_size_gb: 512
855 image:
856 offer: CentOS
857 publisher: OpenLogic
858 sku: '7.1'
859 version: latest
860
861 - name: Create a VM with OS and Plan, accepting the terms
862 azure_rm_virtualmachine:
863 resource_group: myResourceGroup
864 name: f5-nva
865 admin_username: "{{ username }}"
866 admin_password: "{{ password }}"
867 image:
868 publisher: f5-networks
869 offer: f5-big-ip-best
870 sku: f5-bigip-virtual-edition-200m-best-hourly
871 version: latest
872 plan:
873 name: f5-bigip-virtual-edition-200m-best-hourly
874 product: f5-big-ip-best
875 publisher: f5-networks
876
877 - name: Create a VM with Spot Instance
878 azure_rm_virtualmachine:
879 resource_group: myResourceGroup
880 name: testvm10
881 vm_size: Standard_D4
882 priority: Spot
883 eviction_policy: Deallocate
884 admin_username: "{{ username }}"
885 admin_password: "{{ password }}"
886 image:
887 offer: CentOS
888 publisher: OpenLogic
889 sku: '7.1'
890 version: latest
891
892 - name: Update VM to swap OS disk
893 azure_rm_virtualmachine:
894 resource_group: "{{ resource_group }}"
895 name: "vmforimage{{ rpfx }}"
896 admin_username: testuser
897 ssh_password_enabled: false
898 managed_disk_type: Premium_LRS
899 ssh_public_keys:
900 - path: /home/testuser/.ssh/authorized_keys
901 key_data: "ssh-rsa *******************@qq.com"
902 vm_size: Standard_D4s_v3
903 swap_os_disk:
904 os_disk_name: "{{ os_disk_name }}"
905 os_disk_resource_group: "{{ os_disk_resource_group }}"
906 image:
907 offer: 0001-com-ubuntu-server-focal
908 publisher: Canonical
909 sku: 20_04-lts
910 version: latest
911
912 - name: Create VM with cummunity gallery image ID
913 azure_rm_virtualmachine:
914 resource_group: "{{ resource_group }}"
915 name: "communit-image-vm"
916 admin_username: testuser
917 ssh_password_enabled: false
918 managed_disk_type: Premium_LRS
919 open_ports:
920 - 33
921 ssh_public_keys:
922 - path: /home/testuser/.ssh/authorized_keys
923 key_data: "ssh-rsa ************* @qq.com"
924 vm_size: Standard_B1ms
925 image:
926 community_gallery_image_id: "/CommunityGalleries/yellowbrick-fc7e81f1-87dd-4989-9ca8-03743762e873/Images/Ubuntu-5.15.0-1035-azure_22.04"
927
928 - name: Power Off
929 azure_rm_virtualmachine:
930 resource_group: myResourceGroup
931 name: testvm002
932 started: false
933
934 - name: Deallocate
935 azure_rm_virtualmachine:
936 resource_group: myResourceGroup
937 name: testvm002
938 allocated: false
939
940 - name: Power On
941 azure_rm_virtualmachine:
942 resource_group: myResourceGroup
943 name: testvm002
944
945 - name: Restart
946 azure_rm_virtualmachine:
947 resource_group: myResourceGroup
948 name: testvm002
949 restarted: true
950
951 - name: Create a VM with an Availability Zone
952 azure_rm_virtualmachine:
953 resource_group: myResourceGroup
954 name: testvm001
955 vm_size: Standard_DS1_v2
956 admin_username: "{{ username }}"
957 admin_password: "{{ password }}"
958 image: customimage001
959 zones: [1]
960
961 - name: Create a VM with security profile
962 azure_rm_virtualmachine:
963 resource_group: "{{ resource_group }}"
964 name: "{{ vm_name }}"
965 vm_size: Standard_D4s_v3
966 managed_disk_type: Standard_LRS
967 admin_username: "{{ username }}"
968 admin_password: "{{ password }}"
969 security_profile:
970 uefi_settings:
971 secure_boot_enabled: true
972 v_tpm_enabled: true
973 encryption_at_host: true
974 security_type: TrustedLaunch
975 ssh_public_keys:
976 - path: /home/azureuser/.ssh/authorized_keys
977 key_data: "ssh-rsa *****"
978 image:
979 offer: 0001-com-ubuntu-server-jammy
980 publisher: Canonical
981 sku: 22_04-lts-gen2
982 version: latest
983
984 - name: Create a VM and enable deleteOption on OS disk and data disk
985 azure_rm_virtualmachine:
986 resource_group: "{{ resource_group }}"
987 name: "{{ vm_name }}"
988 vm_size: Standard_D4s_v3
989 managed_disk_type: Standard_LRS
990 admin_username: "{{ username }}"
991 admin_password: "{{ password }}"
992 image:
993 offer: 0001-com-ubuntu-server-jammy
994 publisher: Canonical
995 sku: 22_04-lts-gen2
996 version: latest
997 os_disk_delete_option: Delete
998 data_disks:
999 - lun: 0
1000 disk_size_gb: 64
1001 storage_container_name: datadisk1
1002 storage_blob_name: datadisk1.vhd
1003 delete_option: Delete
1004
1005 - name: Remove a VM and all resources that were autocreated
1006 azure_rm_virtualmachine:
1007 resource_group: myResourceGroup
1008 name: testvm002
1009 remove_on_absent: all_autocreated
1010 state: absent
1011 '''
1012
1013 RETURN = '''
1014 powerstate:
1015 description:
1016 - Indicates if the state is C(running), C(stopped), C(deallocated), C(generalized).
1017 returned: always
1018 type: str
1019 sample: running
1020 deleted_vhd_uris:
1021 description:
1022 - List of deleted Virtual Hard Disk URIs.
1023 returned: 'on delete'
1024 type: list
1025 sample: ["https://testvm104519.blob.core.windows.net/vhds/testvm10.vhd"]
1026 deleted_network_interfaces:
1027 description:
1028 - List of deleted NICs.
1029 returned: 'on delete'
1030 type: list
1031 sample: ["testvm1001"]
1032 deleted_public_ips:
1033 description:
1034 - List of deleted public IP address names.
1035 returned: 'on delete'
1036 type: list
1037 sample: ["testvm1001"]
1038 azure_vm:
1039 description:
1040 - Facts about the current state of the object. Note that facts are not part of the registered output but available directly.
1041 returned: always
1042 type: dict
1043 sample: {
1044 "properties": {
1045 "additional_capabilities": {
1046 "ultra_ssd_enabled": false
1047 },
1048 "availabilitySet": {
1049 "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Compute/availabilitySets/MYAVAILABILITYSET"
1050 },
1051 "proximityPlacementGroup": {
1052 "id": "/subscriptions/xxx/resourceGroups/xxx/providers/Microsoft.Compute/proximityPlacementGroups/testid13"
1053 },
1054 "CapacityReservation": {},
1055 "UserData": Null,
1056 "hardwareProfile": {
1057 "vmSize": "Standard_D1"
1058 },
1059 "instanceView": {
1060 "disks": [
1061 {
1062 "name": "testvm10.vhd",
1063 "statuses": [
1064 {
1065 "code": "ProvisioningState/succeeded",
1066 "displayStatus": "Provisioning succeeded",
1067 "level": "Info",
1068 "time": "2016-03-30T07:11:16.187272Z"
1069 }
1070 ]
1071 }
1072 ],
1073 "statuses": [
1074 {
1075 "code": "ProvisioningState/succeeded",
1076 "displayStatus": "Provisioning succeeded",
1077 "level": "Info",
1078 "time": "2016-03-30T20:33:38.946916Z"
1079 },
1080 {
1081 "code": "PowerState/running",
1082 "displayStatus": "VM running",
1083 "level": "Info"
1084 }
1085 ],
1086 "vmAgent": {
1087 "extensionHandlers": [],
1088 "statuses": [
1089 {
1090 "code": "ProvisioningState/succeeded",
1091 "displayStatus": "Ready",
1092 "level": "Info",
1093 "message": "GuestAgent is running and accepting new configurations.",
1094 "time": "2016-03-30T20:31:16.000Z"
1095 }
1096 ],
1097 "vmAgentVersion": "WALinuxAgent-2.0.16"
1098 }
1099 },
1100 "networkProfile": {
1101 "networkInterfaces": [
1102 {
1103 "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkInterfaces/testvm10_NIC01",
1104 "name": "testvm10_NIC01",
1105 "properties": {
1106 "dnsSettings": {
1107 "appliedDnsServers": [],
1108 "dnsServers": []
1109 },
1110 "enableIPForwarding": false,
1111 "ipConfigurations": [
1112 {
1113 "etag": 'W/"041c8c2a-d5dd-4cd7-8465-9125cfbe2cf8"',
1114 "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkInterfaces/testvm10_NIC01/ipConfigurations/default",
1115 "name": "default",
1116 "properties": {
1117 "privateIPAddress": "10.10.0.5",
1118 "privateIPAllocationMethod": "Dynamic",
1119 "provisioningState": "Succeeded",
1120 "publicIPAddress": {
1121 "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/publicIPAddresses/testvm10_PIP01",
1122 "name": "testvm10_PIP01",
1123 "properties": {
1124 "idleTimeoutInMinutes": 4,
1125 "ipAddress": "13.92.246.197",
1126 "ipConfiguration": {
1127 "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkInterfaces/testvm10_NIC01/ipConfigurations/default"
1128 },
1129 "provisioningState": "Succeeded",
1130 "publicIPAllocationMethod": "Static",
1131 "resourceGuid": "3447d987-ca0d-4eca-818b-5dddc0625b42"
1132 }
1133 }
1134 }
1135 }
1136 ],
1137 "macAddress": "00-0D-3A-12-AA-14",
1138 "primary": true,
1139 "provisioningState": "Succeeded",
1140 "resourceGuid": "10979e12-ccf9-42ee-9f6d-ff2cc63b3844",
1141 "virtualMachine": {
1142 "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Compute/virtualMachines/testvm10"
1143 }
1144 }
1145 }
1146 ]
1147 },
1148 "osProfile": {
1149 "adminUsername": "chouseknecht",
1150 "computerName": "test10",
1151 "linuxConfiguration": {
1152 "disable_password_authentication": false
1153 },
1154 "secrets": []
1155 },
1156 "provisioningState": "Succeeded",
1157 "storageProfile": {
1158 "dataDisks": [
1159 {
1160 "caching": "ReadWrite",
1161 "createOption": "empty",
1162 "diskSizeGB": 64,
1163 "lun": 0,
1164 "name": "datadisk1.vhd",
1165 "vhd": {
1166 "uri": "https://testvm10sa1.blob.core.windows.net/datadisk/datadisk1.vhd"
1167 }
1168 }
1169 ],
1170 "imageReference": {
1171 "offer": "CentOS",
1172 "publisher": "OpenLogic",
1173 "sku": "7.1",
1174 "version": "7.1.20160308"
1175 },
1176 "osDisk": {
1177 "caching": "ReadOnly",
1178 "createOption": "fromImage",
1179 "name": "testvm10.vhd",
1180 "osType": "Linux",
1181 "vhd": {
1182 "uri": "https://testvm10sa1.blob.core.windows.net/vhds/testvm10.vhd"
1183 }
1184 }
1185 }
1186 },
1187 "type": "Microsoft.Compute/virtualMachines"
1188 }
1189 ''' # NOQA
1190
1191 import base64
1192 import random
1193 import re
1194 import time
1195
1196 try:
1197 from azure.core.exceptions import ResourceNotFoundError
1198 from azure.core.polling import LROPoller
1199 from azure.mgmt.core.tools import parse_resource_id
1200 from datetime import datetime
1201 except ImportError:
1202 # This is handled in azure_rm_common
1203 pass
1204
1205 from ansible.module_utils.basic import to_native, to_bytes
1206 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import (AzureRMModuleBase,
1207 azure_id_to_dict,
1208 normalize_location_name,
1209 format_resource_id
1210 )
1211
1212
1213 AZURE_OBJECT_CLASS = 'VirtualMachine'
1214
1215 AZURE_ENUM_MODULES = ['azure.mgmt.compute.models']
1216
1217
1218 def extract_names_from_blob_uri(blob_uri, storage_suffix):
1219 # HACK: ditch this once python SDK supports get by URI
1220 m = re.match(r'^https://(?P<accountname>[^.]+)\.blob\.{0}/'
1221 r'(?P<containername>[^/]+)/(?P<blobname>.+)$'.format(storage_suffix), blob_uri)
1222 if not m:
1223 raise Exception("unable to parse blob uri '%s'" % blob_uri)
1224 extracted_names = m.groupdict()
1225 return extracted_names
1226
1227
1228 capacity_reservation_group_spec = dict(
1229 id=dict(type='str'),
1230 name=dict(type='str'),
1231 resource_group=dict(type='str')
1232 )
1233
1234
1235 proximity_placement_group_spec = dict(
1236 id=dict(type='str'),
1237 name=dict(type='str'),
1238 resource_group=dict(type='str')
1239 )
1240
1241
1242 windows_configuration_spec = dict(
1243 enable_automatic_updates=dict(type='bool', required=True),
1244 provision_vm_agent=dict(type='bool', required=True),
1245 )
1246
1247
1248 linux_configuration_spec = dict(
1249 disable_password_authentication=dict(type='bool')
1250 )
1251
1252 user_assigned_identities_spec = dict(
1253 id=dict(type='list', default=[], elements='str'),
1254 append=dict(type='bool', default=True)
1255 )
1256
1257 managed_identity_spec = dict(
1258 type=dict(type='str', choices=['SystemAssigned', 'UserAssigned', 'SystemAssigned, UserAssigned', 'None'], required=True),
1259 user_assigned_identities=dict(type='dict', options=user_assigned_identities_spec, default={}),
1260 )
1261
1262
1263 class AzureRMVirtualMachine(AzureRMModuleBase):
1264
1265 def __init__(self):
1266
1267 self.module_arg_spec = dict(
1268 resource_group=dict(type='str', required=True),
1269 name=dict(type='str', required=True),
1270 custom_data=dict(type='str'),
1271 state=dict(choices=['present', 'absent'], default='present', type='str'),
1272 location=dict(type='str'),
1273 short_hostname=dict(type='str'),
1274 vm_size=dict(type='str'),
1275 priority=dict(type='str', choices=['None', 'Spot']),
1276 eviction_policy=dict(type='str', choices=['Deallocate', 'Delete']),
1277 max_price=dict(type='float', default=-1),
1278 admin_username=dict(type='str'),
1279 admin_password=dict(type='str', no_log=True),
1280 ssh_password_enabled=dict(type='bool', default=True, no_log=False),
1281 ssh_public_keys=dict(type='list', elements='dict'),
1282 image=dict(type='raw'),
1283 availability_set=dict(type='str'),
1284 storage_account_name=dict(type='str', aliases=['storage_account']),
1285 storage_container_name=dict(type='str', aliases=['storage_container'], default='vhds'),
1286 storage_blob_name=dict(type='str', aliases=['storage_blob']),
1287 os_disk_caching=dict(type='str', aliases=['disk_caching'], choices=['None', 'ReadOnly', 'ReadWrite']),
1288 os_disk_size_gb=dict(type='int'),
1289 os_disk_encryption_set=dict(type='str'),
1290 managed_disk_type=dict(type='str', choices=['Standard_LRS', 'StandardSSD_LRS', 'StandardSSD_ZRS', 'Premium_LRS', 'Premium_ZRS', 'UltraSSD_LRS']),
1291 os_disk_name=dict(type='str'),
1292 proximity_placement_group=dict(type='dict', options=proximity_placement_group_spec),
1293 capacity_reservation_group=dict(type='dict', options=capacity_reservation_group_spec),
1294 os_type=dict(type='str', choices=['Linux', 'Windows', 'linux', 'windows'], default='Linux'),
1295 public_ip_allocation_method=dict(type='str', choices=['Dynamic', 'Static', 'Disabled'], default='Static',
1296 aliases=['public_ip_allocation']),
1297 open_ports=dict(type='list', elements='str'),
1298 network_interface_names=dict(type='list', aliases=['network_interfaces'], elements='raw'),
1299 remove_on_absent=dict(type='list', default=['all'], elements='str'),
1300 virtual_network_resource_group=dict(type='str'),
1301 virtual_network_name=dict(type='str', aliases=['virtual_network']),
1302 subnet_name=dict(type='str', aliases=['subnet']),
1303 created_nsg=dict(type='bool', default=True),
1304 allocated=dict(type='bool', default=True),
1305 restarted=dict(type='bool', default=False),
1306 started=dict(type='bool'),
1307 force=dict(type='bool', default=False),
1308 generalized=dict(type='bool', default=False),
1309 swap_os_disk=dict(
1310 type='dict',
1311 options=dict(
1312 os_disk_resource_group=dict(type='str'),
1313 os_disk_name=dict(type='str'),
1314 os_disk_id=dict(type='str')
1315 )
1316 ),
1317 data_disks=dict(
1318 type='list',
1319 elements='dict',
1320 options=dict(
1321 lun=dict(type='int', required=True),
1322 name=dict(type='str'),
1323 disk_size_gb=dict(type='int'),
1324 disk_encryption_set=dict(type='str'),
1325 managed_disk_id=dict(type='str'),
1326 managed_disk_type=dict(type='str', choices=['Standard_LRS', 'StandardSSD_LRS',
1327 'StandardSSD_ZRS', 'Premium_LRS', 'Premium_ZRS', 'UltraSSD_LRS']),
1328 storage_account_name=dict(type='str'),
1329 storage_container_name=dict(type='str', default='vhds'),
1330 storage_blob_name=dict(type='str'),
1331 caching=dict(type='str', choices=['None', 'ReadOnly', 'ReadWrite']),
1332 create_option=dict(type='str', choices=['Empty', 'FromImage'], default='Empty'),
1333 delete_option=dict(type='str', choices=['Delete', 'Detach'])
1334 )
1335 ),
1336 plan=dict(type='dict'),
1337 zones=dict(type='list', elements='str'),
1338 accept_terms=dict(type='bool', default=False),
1339 license_type=dict(type='str', choices=['Windows_Server', 'Windows_Client', 'RHEL_BYOS', 'SLES_BYOS']),
1340 vm_identity=dict(type='dict', options=managed_identity_spec),
1341 winrm=dict(
1342 type='list',
1343 elements='dict',
1344 options=dict(
1345 protocol=dict(type='str', required=True, choices=['http', 'https']),
1346 source_vault=dict(type='str'),
1347 certificate_url=dict(type='str'),
1348 certificate_store=dict(type='str')
1349 )
1350 ),
1351 boot_diagnostics=dict(
1352 type='dict',
1353 options=dict(
1354 enabled=dict(type='bool'),
1355 type=dict(type='str', choices=['managed']),
1356 storage_account=dict(type='str'),
1357 resource_group=dict(type='str'),
1358 ),
1359 mutually_exclusive=[('type', 'storage_account'), ('type', 'resource_group')],
1360 ),
1361 ephemeral_os_disk=dict(type='bool'),
1362 windows_config=dict(type='dict', options=windows_configuration_spec),
1363 linux_config=dict(type='dict', options=linux_configuration_spec),
1364 security_profile=dict(type='dict'),
1365 additional_capabilities=dict(
1366 type='dict',
1367 options=dict(
1368 ultra_ssd_enabled=dict(type='bool')
1369 )
1370 ),
1371 user_data=dict(type='str'),
1372 os_disk_delete_option=dict(type='str', choices=['Delete', 'Detach'])
1373 )
1374
1375 self.resource_group = None
1376 self.name = None
1377 self.custom_data = None
1378 self.state = None
1379 self.location = None
1380 self.short_hostname = None
1381 self.vm_size = None
1382 self.priority = None
1383 self.eviction_policy = None
1384 self.admin_username = None
1385 self.admin_password = None
1386 self.ssh_password_enabled = None
1387 self.ssh_public_keys = None
1388 self.image = None
1389 self.availability_set = None
1390 self.storage_account_name = None
1391 self.storage_container_name = None
1392 self.storage_blob_name = None
1393 self.os_type = None
1394 self.os_disk_caching = None
1395 self.os_disk_size_gb = None
1396 self.os_disk_encryption_set = None
1397 self.os_disk_delete_option = None
1398 self.managed_disk_type = None
1399 self.os_disk_name = None
1400 self.proximity_placement_group = None
1401 self.capacity_reservation_group = None
1402 self.network_interface_names = None
1403 self.remove_on_absent = set()
1404 self.tags = None
1405 self.force = None
1406 self.public_ip_allocation_method = None
1407 self.open_ports = None
1408 self.virtual_network_resource_group = None
1409 self.virtual_network_name = None
1410 self.subnet_name = None
1411 self.created_nsg = None
1412 self.allocated = None
1413 self.restarted = None
1414 self.started = None
1415 self.generalized = None
1416 self.differences = None
1417 self.data_disks = None
1418 self.plan = None
1419 self.accept_terms = None
1420 self.zones = None
1421 self.license_type = None
1422 self.vm_identity = None
1423 self.boot_diagnostics = None
1424 self.ephemeral_os_disk = None
1425 self.linux_config = None
1426 self.windows_config = None
1427 self.security_profile = None
1428 self.additional_capabilities = None
1429 self.swap_os_disk = None
1430 self.user_data = None
1431
1432 self.results = dict(
1433 changed=False,
1434 actions=[],
1435 powerstate_change=None,
1436 ansible_facts=dict(azure_vm=None)
1437 )
1438
1439 required_by = {'os_disk_encryption_set': 'managed_disk_type'}
1440
1441 super(AzureRMVirtualMachine, self).__init__(derived_arg_spec=self.module_arg_spec,
1442 supports_check_mode=True, required_by=required_by)
1443
1444 @property
1445 def boot_diagnostics_present(self):
1446 return self.boot_diagnostics is not None and self.boot_diagnostics.get('enabled') is not None
1447
1448 def get_boot_diagnostics_storage_account(self, limited=False, vm_dict=None):
1449 """
1450 Get the boot diagnostics storage account.
1451
1452 Arguments:
1453 - limited - if true, limit the logic to the boot_diagnostics storage account
1454 this is used if initial creation of the VM has a stanza with
1455 boot_diagnostics disabled, so we only create a storage account
1456 if the user specifies a storage account name inside the boot_diagnostics
1457 schema
1458 - vm_dict - if invoked on an update, this is the current state of the vm including
1459 tags, like the default storage group tag '_own_sa_'.
1460
1461 Normal behavior:
1462 - try the self.boot_diagnostics.storage_account field
1463 - if not there, try the self.storage_account_name field
1464 - if not there, use the default storage account
1465
1466 If limited is True:
1467 - try the self.boot_diagnostics.storage_account field
1468 - if not there, None
1469 """
1470 bsa = None
1471 if self.boot_diagnostics is not None and self.boot_diagnostics.get('storage_account') is not None:
1472 if self.boot_diagnostics.get('resource_group') is not None:
1473 bsa = self.get_storage_account(self.boot_diagnostics['resource_group'], self.boot_diagnostics['storage_account'])
1474 else:
1475 bsa = self.get_storage_account(self.resource_group, self.boot_diagnostics['storage_account'])
1476 elif limited:
1477 return None
1478 elif self.storage_account_name:
1479 bsa = self.get_storage_account(self.resource_group, self.storage_account_name)
1480 else:
1481 bsa = self.create_default_storage_account(vm_dict=vm_dict)
1482 self.log("boot diagnostics storage account:")
1483 self.log(self.serialize_obj(bsa, 'StorageAccount'), pretty_print=True)
1484 return bsa
1485
1486 def exec_module(self, **kwargs):
1487
1488 for key in list(self.module_arg_spec.keys()) + ['tags']:
1489 setattr(self, key, kwargs[key])
1490
1491 # make sure options are lower case
1492 self.remove_on_absent = set([resource.lower() for resource in self.remove_on_absent])
1493
1494 # convert elements to ints
1495 self.zones = [int(i) for i in self.zones] if self.zones else None
1496
1497 changed = False
1498 powerstate_change = None
1499 results = dict()
1500 vm = None
1501 network_interfaces = []
1502 requested_storage_uri = None
1503 requested_vhd_uri = None
1504 data_disk_requested_vhd_uri = None
1505 disable_ssh_password = None
1506 vm_dict = None
1507 image_reference = None
1508 custom_image = False
1509 swap_os_disk_flag = False
1510
1511 resource_group = self.get_resource_group(self.resource_group)
1512 if not self.location:
1513 # Set default location
1514 self.location = resource_group.location
1515
1516 if self.swap_os_disk is not None:
1517 swap_os_disk = self.get_os_disk(self.swap_os_disk)
1518
1519 self.location = normalize_location_name(self.location)
1520
1521 if self.state == 'present':
1522 # Verify parameters and resolve any defaults
1523
1524 if self.vm_size and not self.vm_size_is_valid():
1525 self.fail("Parameter error: vm_size {0} is not valid for your subscription and location.".format(
1526 self.vm_size
1527 ))
1528
1529 if self.network_interface_names:
1530 for nic_name in self.network_interface_names:
1531 nic = self.parse_network_interface(nic_name)
1532 network_interfaces.append(nic)
1533
1534 if self.ssh_public_keys:
1535 msg = "Parameter error: expecting ssh_public_keys to be a list of type dict where " \
1536 "each dict contains keys: path, key_data."
1537 for key in self.ssh_public_keys:
1538 if not isinstance(key, dict):
1539 self.fail(msg)
1540 if not key.get('path') or not key.get('key_data'):
1541 self.fail(msg)
1542
1543 if self.image and isinstance(self.image, dict):
1544 if all(key in self.image for key in ('publisher', 'offer', 'sku', 'version')):
1545 marketplace_image = self.get_marketplace_image_version()
1546
1547 if self.image['version'] == 'latest':
1548 self.image['version'] = marketplace_image.name
1549 self.log("Using image version {0}".format(self.image['version']))
1550
1551 image_reference = self.compute_models.ImageReference(
1552 publisher=self.image['publisher'],
1553 offer=self.image['offer'],
1554 sku=self.image['sku'],
1555 version=self.image['version']
1556 )
1557 elif self.image.get('community_gallery_image_id') is not None:
1558 image_reference = self.compute_models.ImageReference(community_gallery_image_id=self.image['community_gallery_image_id'])
1559 elif self.image.get('shared_gallery_image_id') is not None:
1560 image_reference = self.compute_models.ImageReference(shared_gallery_image_id=self.image['shared_gallery_image_id'])
1561 elif self.image.get('name'):
1562 custom_image = True
1563 image_reference = self.get_custom_image_reference(
1564 self.image.get('name'),
1565 self.image.get('resource_group'))
1566 elif self.image.get('id'):
1567 try:
1568 image_reference = self.compute_models.ImageReference(id=self.image['id'])
1569 except Exception:
1570 self.fail("id Error: Cannot get image from the reference id - {0}".format(self.image['id']))
1571 else:
1572 self.fail("parameter error: expecting image to contain [publisher, offer, sku, version], [name, resource_group] or [id]")
1573 elif self.image and isinstance(self.image, str):
1574 custom_image = True
1575 image_reference = self.get_custom_image_reference(self.image)
1576 elif self.image:
1577 self.fail("parameter error: expecting image to be a string or dict not {0}".format(type(self.image).__name__))
1578
1579 if self.plan:
1580 if not self.plan.get('name') or not self.plan.get('product') or not self.plan.get('publisher'):
1581 self.fail("parameter error: plan must include name, product, and publisher")
1582
1583 if not self.storage_blob_name and not self.managed_disk_type:
1584 self.storage_blob_name = self.name + '.vhd'
1585 elif self.managed_disk_type:
1586 self.storage_blob_name = self.name
1587
1588 if self.storage_account_name and not self.managed_disk_type:
1589 properties = self.get_storage_account(self.resource_group, self.storage_account_name)
1590
1591 requested_storage_uri = properties.primary_endpoints.blob
1592 requested_vhd_uri = '{0}{1}/{2}'.format(requested_storage_uri,
1593 self.storage_container_name,
1594 self.storage_blob_name)
1595
1596 disable_ssh_password = not self.ssh_password_enabled
1597
1598 # Ephemeral OS disk: deleteOption must be 'Delete' and cannot be changed
1599 if self.ephemeral_os_disk:
1600 if self.os_disk_delete_option and self.os_disk_delete_option != 'Delete':
1601 self.fail('Ephemeral OS disk requires os_disk_delete_option to be set to Delete.')
1602 self.os_disk_delete_option = 'Delete'
1603
1604 try:
1605 self.log("Fetching virtual machine {0}".format(self.name))
1606 vm = self.compute_client.virtual_machines.get(self.resource_group, self.name, expand='instanceview')
1607 retry_count = 0
1608 while True:
1609 if retry_count == 10:
1610 self.fail("Error {0} has a provisioning state of Updating. Expecting state to be Successed.".format(self.name))
1611
1612 if vm.provisioning_state == 'Updating':
1613 retry_count = retry_count + 1
1614 time.sleep(300)
1615 vm = self.compute_client.virtual_machines.get(self.resource_group, self.name, expand='instanceview')
1616 else:
1617 break
1618
1619 vm_dict = self.serialize_vm(vm)
1620
1621 if self.state == 'present':
1622 differences = []
1623 current_nics = []
1624 results = vm_dict
1625 current_osdisk = vm_dict['storage_profile']['os_disk']
1626 current_ephemeral = current_osdisk.get('diff_disk_settings', None)
1627 current_properties = vm_dict
1628
1629 if self.priority and self.priority != current_properties.get('priority', 'None'):
1630 self.fail('VM Priority is not updatable: requested virtual machine priority is {0}'.format(self.priority))
1631 if self.eviction_policy and \
1632 self.eviction_policy != current_properties.get('eviction_policy', None):
1633 self.fail('VM Eviction Policy is not updatable: requested virtual machine eviction policy is {0}'.format(self.eviction_policy))
1634 if self.max_price and \
1635 vm_dict.get('billing_profile', None) and \
1636 self.max_price != vm_dict['billing_profile'].get('max_price', None):
1637 self.fail('VM Maximum Price is not updatable: requested virtual machine maximum price is {0}'.format(self.max_price))
1638
1639 if self.ephemeral_os_disk and current_ephemeral is None:
1640 self.fail('Ephemeral OS disk not updatable: virtual machine ephemeral OS disk is {0}'.format(self.ephemeral_os_disk))
1641 elif not self.ephemeral_os_disk and current_ephemeral is not None:
1642 self.fail('Ephemeral OS disk not updatable: virtual machine ephemeral OS disk is {0}'.format(self.ephemeral_os_disk))
1643
1644 # Try to determine if the VM needs to be updated
1645 if self.network_interface_names:
1646 for nic in vm_dict['network_profile']['network_interfaces']:
1647 current_nics.append(nic['id'])
1648
1649 if set(current_nics) != set(network_interfaces):
1650 self.log('CHANGED: virtual machine {0} - network interfaces are different.'.format(self.name))
1651 differences.append('Network Interfaces')
1652 updated_nics = [dict(id=id, primary=(i == 0))
1653 for i, id in enumerate(network_interfaces)]
1654 vm_dict['network_profile']['network_interfaces'] = updated_nics
1655 changed = True
1656
1657 if self.swap_os_disk is not None and swap_os_disk.get('name') != vm_dict['storage_profile']['os_disk']['name']:
1658 self.log('CHANGED: Swap virtual machine {0} - OS disk name'.format(self.name))
1659 differences.append('Swap OS Disk')
1660 changed = True
1661 swap_os_disk_flag = True
1662
1663 if self.os_disk_caching and \
1664 self.os_disk_caching != vm_dict['storage_profile']['os_disk']['caching']:
1665 self.log('CHANGED: virtual machine {0} - OS disk caching'.format(self.name))
1666 differences.append('OS Disk caching')
1667 changed = True
1668 vm_dict['storage_profile']['os_disk']['caching'] = self.os_disk_caching
1669
1670 if self.os_disk_name and \
1671 self.os_disk_name != vm_dict['storage_profile']['os_disk']['name']:
1672 self.log('CHANGED: virtual machine {0} - OS disk name'.format(self.name))
1673 differences.append('OS Disk name')
1674 changed = True
1675 vm_dict['storage_profile']['os_disk']['name'] = self.os_disk_name
1676
1677 if self.os_disk_size_gb and \
1678 self.os_disk_size_gb != vm_dict['storage_profile']['os_disk'].get('disk_size_gb'):
1679 self.log('CHANGED: virtual machine {0} - OS disk size '.format(self.name))
1680 differences.append('OS Disk size')
1681 changed = True
1682 vm_dict['storage_profile']['os_disk']['disk_size_gb'] = self.os_disk_size_gb
1683
1684 if self.os_disk_delete_option:
1685 cur_os_del = vm_dict['storage_profile']['os_disk'].get('delete_option')
1686 if cur_os_del is None:
1687 self.log("CHANGED: OS disk delete_option missing on remote, requested {}".format(self.os_disk_delete_option))
1688 differences.append('OS Disk delete_option')
1689 changed = True
1690
1691 else:
1692 cur_os_del = str(cur_os_del)
1693 if cur_os_del != self.os_disk_delete_option:
1694 self.log("CHANGED: OS disk delete_option differs ({} -> {})".format(cur_os_del, self.os_disk_delete_option))
1695 differences.append('OS Disk delete_option')
1696 changed = True
1697
1698 if self.vm_size and \
1699 self.vm_size != vm_dict['hardware_profile']['vm_size']:
1700 self.log('CHANGED: virtual machine {0} - size '.format(self.name))
1701 differences.append('VM size')
1702 changed = True
1703 vm_dict['hardware_profile']['vm_size'] = self.vm_size
1704
1705 update_tags, vm_dict['tags'] = self.update_tags(vm_dict.get('tags', dict()))
1706 if update_tags:
1707 differences.append('Tags')
1708 changed = True
1709
1710 if self.short_hostname and self.short_hostname != vm_dict['os_profile']['computer_name']:
1711 self.log('CHANGED: virtual machine {0} - short hostname'.format(self.name))
1712 differences.append('Short Hostname')
1713 changed = True
1714 vm_dict['os_profile']['computer_name'] = self.short_hostname
1715
1716 if self.started and vm_dict['powerstate'] not in ['starting', 'running'] and self.allocated:
1717 self.log("CHANGED: virtual machine {0} not running and requested state 'running'".format(self.name))
1718 changed = True
1719 powerstate_change = 'poweron'
1720 elif self.state == 'present' and vm_dict['powerstate'] == 'running' and self.restarted:
1721 self.log("CHANGED: virtual machine {0} {1} and requested state 'restarted'"
1722 .format(self.name, vm_dict['powerstate']))
1723 changed = True
1724 powerstate_change = 'restarted'
1725 elif self.state == 'present' and not self.allocated and vm_dict['powerstate'] not in ['deallocated', 'deallocating']:
1726 self.log("CHANGED: virtual machine {0} {1} and requested state 'deallocated'"
1727 .format(self.name, vm_dict['powerstate']))
1728 changed = True
1729 powerstate_change = 'deallocated'
1730 elif self.started is not None and not self.started and vm_dict['powerstate'] == 'running':
1731 self.log("CHANGED: virtual machine {0} running and requested state 'stopped'".format(self.name))
1732 changed = True
1733 powerstate_change = 'poweroff'
1734 elif self.generalized and vm_dict['powerstate'] != 'generalized':
1735 self.log("CHANGED: virtual machine {0} requested to be 'generalized'".format(self.name))
1736 changed = True
1737 powerstate_change = 'generalized'
1738
1739 vm_dict['zones'] = [int(i) for i in vm_dict['zones']] if 'zones' in vm_dict and vm_dict['zones'] else None
1740 if self.zones is not None and self.zones != vm_dict['zones']:
1741 self.log("CHANGED: virtual machine {0} zones".format(self.name))
1742 differences.append('Zones')
1743 changed = True
1744
1745 if self.license_type is not None and vm_dict.get('license_type') != self.license_type:
1746 differences.append('License Type')
1747 changed = True
1748
1749 if self.vm_identity:
1750 update_vm_identity = False
1751 # If type set to None, and VM has no current identities, nothing to do
1752 if 'None' in self.vm_identity.get('type') and 'identity' not in vm_dict:
1753 pass
1754 # If type different to None, and VM has no current identities, update identities
1755 elif 'identity' not in vm_dict:
1756 update_vm_identity = True
1757 # If type in module args different from type of vm_dict, update identities
1758 elif vm_dict['identity']['type'] != self.vm_identity.get('type'):
1759 update_vm_identity = True
1760 # If type in module args contains 'UserAssigned'
1761 elif 'UserAssigned' in self.vm_identity.get('type'):
1762 # Create sets with current user identities and module args identities
1763 new_managed_identities = set(self.vm_identity.get('user_assigned_identities', {}).get('id', []))
1764 current_managed_identities = set(vm_dict['identity']['user_assigned_identities'].keys())
1765 # If new identities have to be appended to VM
1766 if self.vm_identity.get('user_assigned_identities', {}).get('append', False) is True:
1767 # and the union of identities is longer
1768 if len(current_managed_identities) != len(new_managed_identities.union(current_managed_identities)):
1769 # update identities
1770 update_vm_identity = True
1771 # If new identities have to overwrite current identities
1772 else:
1773 # Check if module args identities are different as current ones
1774 if current_managed_identities.difference(new_managed_identities) != set():
1775 update_vm_identity = True
1776 if update_vm_identity:
1777 differences.append('Managed Identities')
1778 changed = True
1779
1780 if self.security_profile is not None:
1781 update_security_profile = False
1782 if 'security_profile' not in vm_dict.keys():
1783 update_security_profile = True
1784 differences.append('security_profile')
1785 else:
1786 if self.security_profile.get('encryption_at_host') is not None:
1787 if bool(self.security_profile.get('encryption_at_host')) != bool(vm_dict['security_profile']['encryption_at_host']):
1788 update_security_profile = True
1789 else:
1790 self.security_profile['encryption_at_host'] = vm_dict['security_profile']['encryption_at_host']
1791 if self.security_profile.get('security_type') is not None:
1792 if self.security_profile.get('security_type') != vm_dict['security_profile']['security_type']:
1793 update_security_profile = True
1794 if self.security_profile.get('uefi_settings') is not None:
1795 if self.security_profile['uefi_settings'].get('secure_boot_enabled') is not None:
1796 if bool(self.security_profile['uefi_settings']['secure_boot_enabled']) != \
1797 bool(vm_dict['security_profile']['uefi_settings']['secure_boot_enabled']):
1798 update_security_profile = True
1799 else:
1800 self.security_profile['uefi_settings']['secure_boot_enabled'] = \
1801 vm_dict['security_profile']['uefi_settings']['secure_soot_enabled']
1802 if self.security_profile['uefi_settings'].get('v_tpm_enabled') is not None:
1803 if bool(self.security_profile['uefi_settings']['v_tpm_enabled']) != \
1804 bool(vm_dict['security_profile']['uefi_settings']['v_tpm_enabled']):
1805 update_security_profile = True
1806 else:
1807 self.security_profile['uefi_settings']['v_tpm_enabled'] = \
1808 vm_dict['security_profile']['uefi_settings']['v_tpm_enabled']
1809 if update_security_profile:
1810 changed = True
1811 differences.append('security_profile')
1812
1813 if self.additional_capabilities is not None:
1814 if 'additional_capabilities' not in vm_dict.keys() or\
1815 bool(self.additional_capabilities['ultra_ssd_enabled']) != bool(vm_dict['additional_capabilities']['ultra_ssd_enabled']):
1816 changed = True
1817 differences.append('additional_capabilities')
1818
1819 if self.windows_config is not None and vm_dict['os_profile'].get('windows_configuration') is not None:
1820 if self.windows_config['enable_automatic_updates'] != vm_dict['os_profile']['windows_configuration']['enable_automatic_updates']:
1821 self.fail("(PropertyChangeNotAllowed) Changing property 'windowsConfiguration.enableAutomaticUpdates' is not allowed.")
1822
1823 if self.windows_config['provision_vm_agent'] != vm_dict['os_profile']['windows_configuration']['provision_vm_agent']:
1824 self.fail("(PropertyChangeNotAllowed) Changing property 'windowsConfiguration.provisionVMAgent' is not allowed.")
1825
1826 if self.linux_config is not None and vm_dict['os_profile'].get('linux_configuration') is not None:
1827 if self.linux_config['disable_password_authentication'] != \
1828 vm_dict['os_profile']['linux_configuration']['disable_password_authentication']:
1829 self.fail("(PropertyChangeNotAllowed) Changing property 'linuxConfiguration.disablePasswordAuthentication' is not allowed.")
1830
1831 current_os_des_id = vm_dict['storage_profile'].get('os_disk', {}).get('managed_disk', {}).get('disk_encryption_set', {}).get('id', None)
1832 if self.os_disk_encryption_set is not None and current_os_des_id is not None:
1833 if self.os_disk_encryption_set != current_os_des_id:
1834 self.fail("(PropertyChangeNotAllowed) Changing property 'storage_profile.os_disk.managed_disk.disk_encryption_set' is not allowed.")
1835
1836 # Defaults for boot diagnostics
1837 if 'diagnostics_profile' not in vm_dict:
1838 vm_dict['diagnostics_profile'] = {}
1839 if 'boot_diagnostics' not in vm_dict['diagnostics_profile']:
1840 vm_dict['diagnostics_profile']['boot_diagnostics'] = {
1841 'enabled': False,
1842 'storageUri': None
1843 }
1844 if self.boot_diagnostics_present:
1845 current_boot_diagnostics = vm_dict['diagnostics_profile']['boot_diagnostics']
1846 boot_diagnostics_changed = False
1847
1848 if self.boot_diagnostics['enabled'] != current_boot_diagnostics['enabled']:
1849 current_boot_diagnostics['enabled'] = self.boot_diagnostics['enabled']
1850 boot_diagnostics_changed = True
1851
1852 if self.boot_diagnostics.get('type') is not None and self.boot_diagnostics['type'] == 'managed':
1853 boot_diagnostics_blob = None
1854 else:
1855 boot_diagnostics_storage_account = self.get_boot_diagnostics_storage_account(
1856 limited=not self.boot_diagnostics['enabled'], vm_dict=vm_dict)
1857 boot_diagnostics_blob = boot_diagnostics_storage_account.primary_endpoints.blob if boot_diagnostics_storage_account else None
1858 if current_boot_diagnostics.get('storageUri') != boot_diagnostics_blob:
1859 current_boot_diagnostics['storageUri'] = boot_diagnostics_blob
1860 boot_diagnostics_changed = True
1861
1862 if boot_diagnostics_changed:
1863 differences.append('Boot Diagnostics')
1864 changed = True
1865
1866 # Adding boot diagnostics can create a default storage account after initial creation
1867 # this means we might also need to update the _own_sa_ tag
1868 own_sa = (self.tags or {}).get('_own_sa_', None)
1869 cur_sa = vm_dict.get('tags', {}).get('_own_sa_', None)
1870 if own_sa and own_sa != cur_sa:
1871 if 'Tags' not in differences:
1872 differences.append('Tags')
1873 if 'tags' not in vm_dict:
1874 vm_dict['tags'] = {}
1875 vm_dict['tags']['_own_sa_'] = own_sa
1876 changed = True
1877
1878 if self.proximity_placement_group is not None:
1879 if vm_dict.get('proximity_placement_group') is None:
1880 changed = True
1881 differences.append('proximity_placement_group')
1882 if self.proximity_placement_group.get('name') is not None and self.proximity_placement_group.get('resource_group') is not None:
1883 proximity_placement_group = self.get_proximity_placement_group(self.proximity_placement_group.get('resource_group'),
1884 self.proximity_placement_group.get('name'))
1885 self.proximity_placement_group['id'] = proximity_placement_group.id
1886
1887 elif self.proximity_placement_group.get('id') is not None:
1888 if vm_dict['proximity_placement_group'].get('id', "").lower() != self.proximity_placement_group['id'].lower():
1889 changed = True
1890 differences.append('proximity_placement_group')
1891 elif self.proximity_placement_group.get('name') is not None and self.proximity_placement_group.get('resource_group') is not None:
1892 proximity_placement_group = self.get_proximity_placement_group(self.proximity_placement_group.get('resource_group'),
1893 self.proximity_placement_group.get('name'))
1894 if vm_dict['proximity_placement_group'].get('id', "").lower() != proximity_placement_group.id.lower():
1895 changed = True
1896 differences.append('proximity_placement_group')
1897 self.proximity_placement_group['id'] = proximity_placement_group.id
1898 else:
1899 self.fail("Parameter error: Please recheck your proximity placement group ")
1900
1901 if self.capacity_reservation_group is not None:
1902 if vm_dict.get('capacity_reservation') is None:
1903 changed = True
1904 differences.append('capacity_reservation_group')
1905 if self.capacity_reservation_group.get('name') is not None and self.capacity_reservation_group.get('resource_group') is not None:
1906 capacity_reservation_group = self.get_capacity_reservation_group(self.capacity_reservation_group.get('resource_group'),
1907 self.capacity_reservation_group.get('name'))
1908 self.capacity_reservation_group['id'] = capacity_reservation_group.id
1909
1910 elif self.capacity_reservation_group.get('id') is not None:
1911 if vm_dict['capacity_reservation'].get('id', "").lower() != self.capacity_reservation_group['id'].lower():
1912 changed = True
1913 differences.append('capacity_reservation_group')
1914 elif self.capacity_reservation_group.get('name') is not None and self.capacity_reservation_group.get('resource_group') is not None:
1915 capacity_reservation_group = self.get_capacity_reservation_group(self.capacity_reservation_group.get('resource_group'),
1916 self.capacity_reservation_group.get('name'))
1917 if vm_dict['capacity_reservation'].get('id', "").lower() != capacity_reservation_group.id.lower():
1918 changed = True
1919 differences.append('capacity_reservation_group')
1920 self.capacity_reservation_group['id'] = capacity_reservation_group.id
1921 else:
1922 self.fail("Parameter error: Please recheck your capacity reservation group ")
1923
1924 if self.data_disks and vm_dict.get('storage_profile', {}).get('data_disks'):
1925 for dd_req in self.data_disks:
1926 if dd_req.get('delete_option') is None:
1927 continue
1928
1929 req_lun = int(dd_req['lun'])
1930 req_del = dd_req['delete_option']
1931
1932 cur = next((d for d in vm_dict['storage_profile']['data_disks']
1933 if int(d.get('lun', -1)) == req_lun), None)
1934
1935 cur_del = None
1936 if cur:
1937 cur_del = cur.get('delete_option')
1938 if cur_del is not None:
1939 cur_del = str(cur_del)
1940
1941 if cur_del is None:
1942 self.log("CHANGED: Data disk LUN {0} delete_option missing on remote, requested {1}.".format(req_lun, req_del))
1943 differences.append("DataDisk delete_option LUN {0}".format(req_lun))
1944 changed = True
1945
1946 elif req_del != cur_del:
1947 self.log("CHANGED: Data disk LUN {0} delete_option differs ({1} -> {2}).".format(req_lun, cur_del, req_del))
1948 differences.append("DataDisk delete_option LUN {0}".format(req_lun))
1949 changed = True
1950
1951 self.differences = differences
1952
1953 elif self.state == 'absent':
1954 self.log("CHANGED: virtual machine {0} exists and requested state is 'absent'".format(self.name))
1955 results = dict()
1956 changed = True
1957
1958 except ResourceNotFoundError:
1959 self.log('Virtual machine {0} does not exist'.format(self.name))
1960 if self.state == 'present':
1961 self.log("CHANGED: virtual machine {0} does not exist but state is 'present'.".format(self.name))
1962 changed = True
1963
1964 self.results['changed'] = changed
1965 self.results['ansible_facts']['azure_vm'] = results
1966 self.results['powerstate_change'] = powerstate_change
1967
1968 if self.check_mode:
1969 return self.results
1970
1971 if changed:
1972 if self.state == 'present':
1973 if not vm:
1974 # Create the VM
1975 self.log("Create virtual machine {0}".format(self.name))
1976 self.results['actions'].append('Created VM {0}'.format(self.name))
1977
1978 # Validate parameters
1979 if not self.admin_username and not self.swap_os_disk:
1980 self.fail("Parameter error: admin_username required when creating a virtual machine.")
1981
1982 if self.os_type == 'Linux' or self.os_type == 'linux':
1983 if disable_ssh_password and not self.ssh_public_keys and not self.swap_os_disk:
1984 self.fail("Parameter error: ssh_public_keys required when disabling SSH password.")
1985
1986 availability_set_resource = None
1987 if self.availability_set:
1988 parsed_availability_set = parse_resource_id(self.availability_set)
1989 availability_set = self.get_availability_set(parsed_availability_set.get('resource_group', self.resource_group),
1990 parsed_availability_set.get('name'))
1991 availability_set_resource = self.compute_models.SubResource(id=availability_set.id)
1992
1993 if self.zones:
1994 self.fail("Parameter error: you can't use Availability Set and Availability Zones at the same time")
1995
1996 proximity_placement_group_resource = None
1997 if self.proximity_placement_group is not None:
1998 if self.proximity_placement_group.get('id') is not None:
1999 proximity_placement_group_resource = self.compute_models.SubResource(id=self.proximity_placement_group['id'])
2000 elif self.proximity_placement_group.get('name') is not None and self.proximity_placement_group.get('resource_group') is not None:
2001 proximity_placement_group = self.get_proximity_placement_group(self.proximity_placement_group.get('resource_group'),
2002 self.proximity_placement_group.get('name'))
2003 proximity_placement_group_resource = self.compute_models.SubResource(id=proximity_placement_group.id)
2004 else:
2005 self.fail("Parameter error: Please recheck your proximity placement group ")
2006
2007 capacity_reservation_group_resource = None
2008 if self.capacity_reservation_group is not None:
2009 if self.capacity_reservation_group.get('id') is not None:
2010 capacity_reservation_group_resource = self.compute_models.SubResource(id=self.capacity_reservation_group['id'])
2011 elif self.capacity_reservation_group.get('name') is not None and self.capacity_reservation_group.get('resource_group') is not None:
2012 capacity_reservation_group = self.get_capacity_reservation_group(self.capacity_reservation_group.get('resource_group'),
2013 self.capacity_reservation_group.get('name'))
2014 capacity_reservation_group_resource = self.compute_models.SubResource(id=capacity_reservation_group.id)
2015 else:
2016 self.fail("Parameter error: Please recheck your capacity reservation group ")
2017
2018 # Get defaults
2019 if not self.network_interface_names:
2020 default_nic = self.create_default_nic()
2021 self.log("network interface:")
2022 self.log(self.serialize_obj(default_nic, 'NetworkInterface'), pretty_print=True)
2023 network_interfaces = [default_nic.id]
2024
2025 # os disk
2026 if not self.storage_account_name and not self.managed_disk_type:
2027 storage_account = self.create_default_storage_account()
2028 self.log("os disk storage account:")
2029 self.log(self.serialize_obj(storage_account, 'StorageAccount'), pretty_print=True)
2030 requested_storage_uri = 'https://{0}.blob.{1}/'.format(
2031 storage_account.name,
2032 self._cloud_environment.suffixes.storage_endpoint)
2033 requested_vhd_uri = '{0}{1}/{2}'.format(
2034 requested_storage_uri,
2035 self.storage_container_name,
2036 self.storage_blob_name)
2037 # disk caching
2038 if not self.os_disk_caching:
2039 self.os_disk_caching = 'ReadOnly'
2040
2041 if not self.short_hostname:
2042 self.short_hostname = self.name
2043
2044 nics = []
2045 for i, id in enumerate(network_interfaces):
2046 if not self.network_interface_names:
2047 # default NIC → delete with VM
2048 nics.append(
2049 self.compute_models.NetworkInterfaceReference(
2050 id=id,
2051 primary=(i == 0),
2052 delete_option='Delete'
2053 )
2054 )
2055 else:
2056 # user-supplied NIC → detach by default
2057 nics.append(
2058 self.compute_models.NetworkInterfaceReference(
2059 id=id,
2060 primary=(i == 0)
2061 )
2062 )
2063
2064 # os disk
2065 if self.managed_disk_type:
2066 vhd = None
2067 managed_disk = self.compute_models.ManagedDiskParameters(storage_account_type=self.managed_disk_type)
2068 elif custom_image:
2069 vhd = None
2070 managed_disk = None
2071 else:
2072 vhd = self.compute_models.VirtualHardDisk(uri=requested_vhd_uri)
2073 managed_disk = None
2074
2075 if managed_disk and self.os_disk_encryption_set:
2076 managed_disk.disk_encryption_set = self.compute_models.DiskEncryptionSetParameters(
2077 id=self.os_disk_encryption_set
2078 )
2079
2080 plan = None
2081 if self.plan:
2082 plan = self.compute_models.Plan(name=self.plan.get('name'), product=self.plan.get('product'),
2083 publisher=self.plan.get('publisher'),
2084 promotion_code=self.plan.get('promotion_code'))
2085
2086 # do this before creating vm_resource as it can modify tags
2087 if self.boot_diagnostics_present and self.boot_diagnostics['enabled'] and self.boot_diagnostics.get('type') != 'managed':
2088 boot_diag_storage_account = self.get_boot_diagnostics_storage_account()
2089
2090 vm_resource = self.compute_models.VirtualMachine(
2091 location=self.location,
2092 tags=self.tags,
2093 hardware_profile=self.compute_models.HardwareProfile(
2094 vm_size=self.vm_size
2095 ),
2096 network_profile=self.compute_models.NetworkProfile(
2097 network_interfaces=nics
2098 ),
2099 availability_set=availability_set_resource,
2100 proximity_placement_group=proximity_placement_group_resource,
2101 capacity_reservation=self.compute_models.CapacityReservationProfile(capacity_reservation_group=capacity_reservation_group_resource),
2102 plan=plan,
2103 zones=self.zones,
2104 user_data=to_native(base64.b64encode(to_bytes(self.user_data)))
2105 )
2106
2107 if self.swap_os_disk is not None:
2108 storage_profile = self.compute_models.StorageProfile(
2109 os_disk=self.compute_models.OSDisk(
2110 name=swap_os_disk.get('name'),
2111 managed_disk=swap_os_disk.get('managed_disk'),
2112 os_type=self.os_type,
2113 create_option='attach',
2114 ),
2115 image_reference=image_reference
2116 )
2117 os_profile = None
2118 else:
2119 storage_profile = self.compute_models.StorageProfile(
2120 os_disk=self.compute_models.OSDisk(
2121 name=self.os_disk_name if self.os_disk_name else self.storage_blob_name,
2122 vhd=vhd,
2123 managed_disk=managed_disk,
2124 create_option=self.compute_models.DiskCreateOptionTypes.from_image,
2125 caching=self.os_disk_caching,
2126 disk_size_gb=self.os_disk_size_gb,
2127 diff_disk_settings=self.compute_models.DiffDiskSettings(option='Local') if self.ephemeral_os_disk else None,
2128 delete_option=self.os_disk_delete_option
2129 ),
2130 image_reference=image_reference
2131 )
2132 os_profile = self.compute_models.OSProfile(
2133 admin_username=self.admin_username,
2134 computer_name=self.short_hostname,
2135 )
2136
2137 vm_resource.storage_profile = storage_profile
2138 vm_resource.os_profile = os_profile
2139
2140 if self.priority == 'Spot':
2141 vm_resource.priority = self.priority
2142 vm_resource.eviction_policy = self.eviction_policy
2143 vm_resource.billing_profile = self.compute_models.BillingProfile(
2144 max_price=self.max_price
2145 )
2146
2147 if self.license_type is not None:
2148 vm_resource.license_type = self.license_type
2149
2150 if self.vm_identity:
2151 # If UserAssigned in module args and ids specified
2152 if 'UserAssigned' in self.vm_identity.get('type') and len(self.vm_identity.get('user_assigned_identities', {}).get('id', [])) != 0:
2153 user_assigned_identities_dict = {uami: dict() for uami in self.vm_identity.get('user_assigned_identities').get('id')}
2154 # Append identities to the model
2155 vm_resource.identity = self.compute_models.VirtualMachineIdentity(
2156 type=self.vm_identity.get('type'),
2157 user_assigned_identities=user_assigned_identities_dict
2158 )
2159 # If UserAssigned in module args, but ids are not specified
2160 elif 'UserAssigned' in self.vm_identity.get('type') and len(self.vm_identity.get('user_assigned_identities', {}).get('id', [])) == 0:
2161 self.fail("UserAssigned specified but no User Identity IDs provided")
2162 # In any other case ('SystemAssigned' or 'None') apply the configuration to the model
2163 else:
2164 vm_resource.identity = self.compute_models.VirtualMachineIdentity(
2165 type=self.vm_identity.get('type')
2166 )
2167
2168 if self.winrm and vm_resource.os_profile is not None:
2169 winrm_listeners = list()
2170 for winrm_listener in self.winrm:
2171 winrm_listeners.append(self.compute_models.WinRMListener(
2172 protocol=winrm_listener.get('protocol'),
2173 certificate_url=winrm_listener.get('certificate_url')
2174 ))
2175 if winrm_listener.get('source_vault'):
2176 if not vm_resource.os_profile.secrets:
2177 vm_resource.os_profile.secrets = list()
2178
2179 vm_resource.os_profile.secrets.append(self.compute_models.VaultSecretGroup(
2180 source_vault=self.compute_models.SubResource(
2181 id=winrm_listener.get('source_vault')
2182 ),
2183 vault_certificates=[
2184 self.compute_models.VaultCertificate(
2185 certificate_url=winrm_listener.get('certificate_url'),
2186 certificate_store=winrm_listener.get('certificate_store')
2187 ),
2188 ]
2189 ))
2190
2191 self.winrm = self.compute_models.WinRMConfiguration(
2192 listeners=winrm_listeners
2193 )
2194
2195 if (self.os_type == 'Windows' or self.os_type == 'windows') and vm_resource.os_profile is not None:
2196 vm_resource.os_profile.windows_configuration = self.compute_models.WindowsConfiguration(
2197 win_rm=self.winrm,
2198 provision_vm_agent=self.windows_config['provision_vm_agent'] if self.windows_config is not None else True,
2199 enable_automatic_updates=self.windows_config['enable_automatic_updates'] if self.windows_config is not None else True,
2200 )
2201
2202 if self.boot_diagnostics_present:
2203 if self.boot_diagnostics['enabled'] and self.boot_diagnostics.get('type') != 'managed':
2204 storage_uri = boot_diag_storage_account.primary_endpoints.blob
2205 else:
2206 storage_uri = None
2207 vm_resource.diagnostics_profile = self.compute_models.DiagnosticsProfile(
2208 boot_diagnostics=self.compute_models.BootDiagnostics(
2209 enabled=self.boot_diagnostics['enabled'],
2210 storage_uri=storage_uri))
2211
2212 if self.admin_password and vm_resource.os_profile is not None:
2213 vm_resource.os_profile.admin_password = self.admin_password
2214
2215 if self.custom_data and vm_resource.os_profile is not None:
2216 # Azure SDK (erroneously?) wants native string type for this
2217 vm_resource.os_profile.custom_data = to_native(base64.b64encode(to_bytes(self.custom_data)))
2218
2219 if (self.os_type == 'Linux' or self.os_type == 'linux') and vm_resource.os_profile is not None:
2220 vm_resource.os_profile.linux_configuration = self.compute_models.LinuxConfiguration(
2221 disable_password_authentication=self.linux_config['disable_password_authentication'] if self.linux_config else disable_ssh_password
2222 )
2223 if self.ssh_public_keys and vm_resource.os_profile is not None:
2224 ssh_config = self.compute_models.SshConfiguration()
2225 ssh_config.public_keys = \
2226 [self.compute_models.SshPublicKey(path=key['path'], key_data=key['key_data']) for key in self.ssh_public_keys]
2227 vm_resource.os_profile.linux_configuration.ssh = ssh_config
2228
2229 # data disk
2230 if self.data_disks:
2231 data_disks = []
2232 count = 0
2233
2234 for data_disk in self.data_disks:
2235 data_disk_vhd = None
2236 disk_name = None
2237
2238 if data_disk.get('managed_disk_id'):
2239 create_option = self.compute_models.DiskCreateOptionTypes.attach
2240 data_disk_managed_disk = self.compute_models.ManagedDiskParameters(id=data_disk.get('managed_disk_id'))
2241 elif data_disk.get('create_option') == 'FromImage':
2242 create_option = self.compute_models.DiskCreateOptionTypes.from_image
2243 if data_disk.get('managed_disk_type'):
2244 data_disk_managed_disk = self.compute_models.ManagedDiskParameters(storage_account_type=data_disk['managed_disk_type'])
2245 if data_disk.get('disk_encryption_set'):
2246 data_disk_managed_disk.disk_encryption_set = self.compute_models.DiskEncryptionSetParameters(
2247 id=data_disk['disk_encryption_set']
2248 )
2249 else:
2250 data_disk_managed_disk = None
2251 disk_name = self.name + "-datadisk-" + str(count)
2252 count += 1
2253 else:
2254 create_option = self.compute_models.DiskCreateOptionTypes.empty
2255
2256 if not data_disk.get('managed_disk_type'):
2257 if not data_disk.get('storage_blob_name'):
2258 data_disk['storage_blob_name'] = self.name + '-data-' + str(count) + '.vhd'
2259 count += 1
2260
2261 if data_disk.get('storage_account_name'):
2262 data_disk_storage_account = self.get_storage_account(self.resource_group, data_disk['storage_account_name'])
2263 else:
2264 data_disk_storage_account = self.create_default_storage_account()
2265 self.log("data disk storage account:")
2266 self.log(self.serialize_obj(data_disk_storage_account, 'StorageAccount'), pretty_print=True)
2267
2268 if not data_disk.get('storage_container_name'):
2269 data_disk['storage_container_name'] = 'vhds'
2270
2271 data_disk_requested_vhd_uri = 'https://{0}.blob.{1}/{2}/{3}'.format(
2272 data_disk_storage_account.name,
2273 self._cloud_environment.suffixes.storage_endpoint,
2274 data_disk['storage_container_name'],
2275 data_disk['storage_blob_name']
2276 )
2277
2278 if not data_disk.get('managed_disk_type'):
2279 data_disk_managed_disk = None
2280 disk_name = data_disk['storage_blob_name']
2281 data_disk_vhd = self.compute_models.VirtualHardDisk(uri=data_disk_requested_vhd_uri)
2282 else:
2283 data_disk_managed_disk = self.compute_models.ManagedDiskParameters(storage_account_type=data_disk['managed_disk_type'])
2284 if data_disk.get('disk_encryption_set'):
2285 data_disk_managed_disk.disk_encryption_set = self.compute_models.DiskEncryptionSetParameters(
2286 id=data_disk['disk_encryption_set']
2287 )
2288 disk_name = self.name + "-datadisk-" + str(count)
2289 count += 1
2290
2291 data_disk['caching'] = data_disk.get(
2292 'caching', 'ReadOnly'
2293 )
2294
2295 data_disks.append(self.compute_models.DataDisk(
2296 lun=data_disk['lun'],
2297 name=data_disk.get('name') if data_disk.get('name') is not None else disk_name,
2298 vhd=data_disk_vhd,
2299 caching=data_disk['caching'],
2300 create_option=create_option,
2301 disk_size_gb=data_disk['disk_size_gb'],
2302 managed_disk=data_disk_managed_disk,
2303 delete_option=data_disk.get('delete_option')
2304 ))
2305
2306 vm_resource.storage_profile.data_disks = data_disks
2307
2308 # Before creating VM accept terms of plan if `accept_terms` is True
2309 if self.accept_terms is True:
2310 if not self.plan or not all([self.plan.get('name'), self.plan.get('product'), self.plan.get('publisher')]):
2311 self.fail("parameter error: plan must be specified and include name, product, and publisher")
2312 try:
2313 plan_name = self.plan.get('name')
2314 plan_product = self.plan.get('product')
2315 plan_publisher = self.plan.get('publisher')
2316 term = self.marketplace_client.marketplace_agreements.get(
2317 offer_type='virtualmachine', publisher_id=plan_publisher, offer_id=plan_product, plan_id=plan_name)
2318 term.accepted = True
2319 self.marketplace_client.marketplace_agreements.create(
2320 offer_type='virtualmachine', publisher_id=plan_publisher, offer_id=plan_product, plan_id=plan_name, parameters=term)
2321 except Exception as exc:
2322 self.fail(("Error accepting terms for virtual machine {0} with plan {1}. " +
2323 "Only service admin/account admin users can purchase images " +
2324 "from the marketplace. - {2}").format(self.name, self.plan, str(exc)))
2325
2326 if self.security_profile is not None:
2327 uefi_settings_spec = None
2328 if self.security_profile.get('uefi_settings') is not None:
2329 uefi_settings_spec = self.compute_models.UefiSettings(
2330 secure_boot_enabled=self.security_profile['uefi_settings'].get('secure_boot_enabled'),
2331 v_tpm_enabled=self.security_profile['uefi_settings'].get('v_tpm_enabled'),
2332 )
2333 security_profile = self.compute_models.SecurityProfile(
2334 uefi_settings=uefi_settings_spec,
2335 encryption_at_host=self.security_profile.get('encryption_at_host'),
2336 security_type=self.security_profile.get('security_type'),
2337 )
2338 vm_resource.security_profile = security_profile
2339
2340 if self.additional_capabilities is not None:
2341 additional_capabilities = self.compute_models.AdditionalCapabilities(
2342 ultra_ssd_enabled=self.additional_capabilities.get('ultra_ssd_enabled')
2343 )
2344 vm_resource.additional_capabilities = additional_capabilities
2345
2346 self.log("Create virtual machine with parameters:")
2347 self.create_or_update_vm(vm_resource, 'all_autocreated' in self.remove_on_absent)
2348
2349 elif self.differences and len(self.differences) > 0:
2350 # Update the VM based on detected config differences
2351
2352 self.log("Update virtual machine {0}".format(self.name))
2353 self.results['actions'].append('Updated VM {0}'.format(self.name))
2354 nics = [self.compute_models.NetworkInterfaceReference(id=interface['id'], primary=(i == 0))
2355 for i, interface in enumerate(vm_dict['network_profile']['network_interfaces'])]
2356
2357 # os disk
2358 if not vm_dict['storage_profile']['os_disk'].get('managedDisk'):
2359 managed_disk = None
2360 vhd = self.compute_models.VirtualHardDisk(uri=vm_dict['storage_profile']['os_disk'].get('vhd', {}).get('uri'))
2361 else:
2362 vhd = None
2363 managed_disk = self.compute_models.ManagedDiskParameters(
2364 storage_account_type=vm_dict['storage_profile']['os_disk']['managed_disk'].get('storage_account_type')
2365 )
2366
2367 proximity_placement_group_resource = None
2368 if self.proximity_placement_group is not None:
2369 try:
2370 proximity_placement_group_resource = self.compute_models.SubResource(id=self.proximity_placement_group.get('id'))
2371 except Exception:
2372 # pass if the proximity Placement Group
2373 pass
2374 else:
2375 try:
2376 proximity_placement_group_resource = self.compute_models.SubResource(id=vm_dict['proximity_placement_group'].get('id'))
2377 except Exception:
2378 # pass if the proximity Placement Group
2379 pass
2380
2381 capacity_reservation_group_resource = None
2382 if self.capacity_reservation_group is not None:
2383 try:
2384 capacity_reservation_group_resource = self.compute_models.SubResource(id=self.capacity_reservation_group.get('id'))
2385 except Exception:
2386 # pass if the proximity Placement Group
2387 pass
2388 else:
2389 try:
2390 capacity_reservation_group_resource = self.compute_models.SubResource(id=vm_dict['capacity_reservation_group'].get('id'))
2391 except Exception:
2392 # pass if the proximity Placement Group
2393 pass
2394
2395 availability_set_resource = None
2396 try:
2397 availability_set_resource = self.compute_models.SubResource(id=vm_dict['availability_set'].get('id'))
2398 except Exception:
2399 # pass if the availability set is not set
2400 pass
2401
2402 if 'image_reference' in vm_dict['storage_profile'].keys():
2403 if 'id' in vm_dict['storage_profile']['image_reference'].keys():
2404 image_reference = self.compute_models.ImageReference(
2405 id=vm_dict['storage_profile']['image_reference']['id']
2406 )
2407 elif 'shared_gallery_image_id' in vm_dict['storage_profile'].keys():
2408 image_reference = self.compute_models.ImageReference(
2409 shared_gallery_image_id=vm_dict['storage_profile']['image_reference']['shared_gallery_image_id']
2410 )
2411 elif 'community_gallery_image_id' in vm_dict['storage_profile'].keys():
2412 image_reference = self.compute_models.ImageReference(
2413 community_gallery_image_id=vm_dict['storage_profile']['image_reference']['community_gallery_image_id']
2414 )
2415 else:
2416 image_reference = self.compute_models.ImageReference(
2417 publisher=vm_dict['storage_profile']['image_reference'].get('publisher'),
2418 offer=vm_dict['storage_profile']['image_reference'].get('offer'),
2419 sku=vm_dict['storage_profile']['image_reference'].get('sku'),
2420 version=vm_dict['storage_profile']['image_reference'].get('version')
2421 )
2422 else:
2423 image_reference = None
2424
2425 # You can't change a vm zone
2426 if self.zones is not None and vm_dict['zones'] != self.zones:
2427 self.fail("You can't change the Availability Zone of a virtual machine (have: {0}, want: {1})".format(vm_dict['zones'], self.zones))
2428
2429 if 'os_profile' in vm_dict:
2430 os_profile = self.compute_models.OSProfile(
2431 admin_username=vm_dict.get('os_profile', {}).get('admin_username'),
2432 computer_name=vm_dict.get('os_profile', {}).get('computer_name')
2433 )
2434 else:
2435 os_profile = None
2436
2437 vm_resource = self.compute_models.VirtualMachine(
2438 location=vm_dict['location'],
2439 os_profile=os_profile,
2440 hardware_profile=self.compute_models.HardwareProfile(
2441 vm_size=vm_dict['hardware_profile'].get('vm_size')
2442 ),
2443 availability_set=availability_set_resource,
2444 proximity_placement_group=proximity_placement_group_resource,
2445 capacity_reservation=self.compute_models.CapacityReservationProfile(capacity_reservation_group=capacity_reservation_group_resource),
2446 network_profile=self.compute_models.NetworkProfile(
2447 network_interfaces=nics
2448 ),
2449 user_data=to_native(base64.b64encode(to_bytes(self.user_data)))
2450 )
2451
2452 if swap_os_disk_flag:
2453 storage_profile = self.compute_models.StorageProfile(
2454 os_disk=self.compute_models.OSDisk(
2455 name=swap_os_disk.get('name'),
2456 managed_disk=swap_os_disk.get('managed_disk'),
2457 create_option=vm_dict['storage_profile']['os_disk'].get('create_option'),
2458 ),
2459 image_reference=image_reference
2460 )
2461 else:
2462 delete_opt = self.os_disk_delete_option
2463 if delete_opt is None:
2464 delete_opt = vm_dict['storage_profile']['os_disk'].get('delete_option')
2465 os_disk_obj = self.compute_models.OSDisk(
2466 name=vm_dict['storage_profile']['os_disk'].get('name'),
2467 vhd=vhd,
2468 managed_disk=managed_disk,
2469 create_option=vm_dict['storage_profile']['os_disk'].get('create_option'),
2470 os_type=vm_dict['storage_profile']['os_disk'].get('os_type'),
2471 caching=vm_dict['storage_profile']['os_disk'].get('caching'),
2472 disk_size_gb=vm_dict['storage_profile']['os_disk'].get('disk_size_gb')
2473 )
2474 if delete_opt is not None:
2475 os_disk_obj.delete_option = delete_opt
2476 storage_profile = self.compute_models.StorageProfile(
2477 os_disk=os_disk_obj,
2478 image_reference=image_reference
2479 )
2480
2481 vm_resource.storage_profile = storage_profile
2482
2483 if self.license_type is not None:
2484 vm_resource.license_type = self.license_type
2485
2486 if self.vm_identity is not None:
2487 current_user_assigned_identities_dict = {}
2488 # If 'append' is set to True save current user assigned managed identities to use later
2489 if (self.vm_identity.get('user_assigned_identities', {}) is not None
2490 and self.vm_identity.get('user_assigned_identities', {}).get('append', False) is True):
2491 if 'identity' in vm_dict and 'user_assigned_identities' in vm_dict['identity']:
2492 current_user_assigned_identities_dict = {uami: dict() for uami in vm_dict['identity']['user_assigned_identities'].keys()}
2493 vm_identity_user_assigned_append = True
2494 else:
2495 # Nothing to append to
2496 vm_identity_user_assigned_append = False
2497 else:
2498 # 'append' is False or unset
2499 vm_identity_user_assigned_append = False
2500 # If there are identities in 'id' and 'UserAssigned' in type
2501 if 'UserAssigned' in self.vm_identity.get('type') and len(self.vm_identity.get('user_assigned_identities', {}).get('id', [])) != 0:
2502 user_assigned_identities_dict = {uami: dict() for uami in self.vm_identity.get('user_assigned_identities').get('id')}
2503 # If there are identities to append, merge the dicts
2504 if vm_identity_user_assigned_append:
2505 user_assigned_identities_dict = {**user_assigned_identities_dict, **current_user_assigned_identities_dict}
2506 # Save the identity
2507 vm_resource.identity = self.compute_models.VirtualMachineIdentity(
2508 type=self.vm_identity.get('type'),
2509 user_assigned_identities=user_assigned_identities_dict
2510 )
2511 # If there are no identities in 'id' and 'UserAssigned' in type
2512 elif 'UserAssigned' in self.vm_identity.get('type') and len(self.vm_identity.get('user_assigned_identities', {}).get('id', [])) == 0:
2513 # Fail if append is False
2514 if vm_identity_user_assigned_append is False:
2515 self.fail("UserAssigned specified but no User Assigned IDs provided" +
2516 " and no UserAssigned identities are currently assigned to the VM")
2517 # If append is true, user is changing from 'UserAssigned' to 'SystemAssigned, UserAssigned'
2518 # and wants to keep current UserAssigned identities
2519 else:
2520 # Save current identities
2521 vm_resource.identity = self.compute_models.VirtualMachineIdentity(
2522 type=self.vm_identity.get('type'),
2523 user_assigned_identities=current_user_assigned_identities_dict
2524 )
2525 # Set 'SystemAssigned' or 'None'
2526 else:
2527 vm_resource.identity = self.compute_models.VirtualMachineIdentity(
2528 type=self.vm_identity.get('type')
2529 )
2530
2531 if self.boot_diagnostics is not None:
2532 storage_uri = None
2533 # storageUri is undefined if boot diagnostics is disabled
2534 if 'storageUri' in vm_dict['diagnostics_profile']['boot_diagnostics']:
2535 storage_uri = vm_dict['diagnostics_profile']['boot_diagnostics']['storageUri']
2536 vm_resource.diagnostics_profile = self.compute_models.DiagnosticsProfile(
2537 boot_diagnostics=self.compute_models.BootDiagnostics(
2538 enabled=vm_dict['diagnostics_profile']['boot_diagnostics']['enabled'],
2539 storage_uri=storage_uri))
2540
2541 if vm_dict.get('tags'):
2542 vm_resource.tags = vm_dict['tags']
2543
2544 # Add custom_data, if provided
2545 if vm_dict.get('os_profile', {}).get('custom_data'):
2546 custom_data = vm_dict['os_profile']['custom_data']
2547 # Azure SDK (erroneously?) wants native string type for this
2548 vm_resource.os_profile.custom_data = to_native(base64.b64encode(to_bytes(custom_data)))
2549
2550 # Add admin password, if one provided
2551 if vm_dict.get('os_profile', {}).get('admin_password'):
2552 vm_resource.os_profile.admin_password = vm_dict['os_profile']['admin_password']
2553
2554 # Add Windows configuration, if applicable
2555 windows_config = vm_dict.get('os_profile', {}).get('windows_configuration')
2556 if windows_config:
2557 if self.windows_config is not None:
2558 vm_resource.os_profile.windows_configuration = self.compute_models.WindowsConfiguration(
2559 provision_vm_agent=self.windows_config['provision_vm_agent'],
2560 enable_automatic_updates=self.windows_config['enable_automatic_updates']
2561 )
2562 else:
2563 vm_resource.os_profile.windows_configuration = self.compute_models.WindowsConfiguration(
2564 provision_vm_agent=windows_config.get('provision_vm_agent', True),
2565 enable_automatic_updates=windows_config.get('enable_automatic_updates', True)
2566 )
2567
2568 # Add linux configuration, if applicable
2569 linux_config = vm_dict.get('os_profile', {}).get('linux_configuration')
2570 if linux_config:
2571 if self.linux_config is not None:
2572 vm_resource.os_profile.linux_configuration = self.compute_models.LinuxConfiguration(
2573 disable_password_authentication=self.linux_config['disable_password_authentication']
2574 )
2575 else:
2576 vm_resource.os_profile.linux_configuration = self.compute_models.LinuxConfiguration(
2577 disable_password_authentication=linux_config.get('disable_password_authentication', False)
2578 )
2579 ssh_config = linux_config.get('ssh', None)
2580 if ssh_config:
2581 public_keys = ssh_config.get('public_keys')
2582 if public_keys:
2583 vm_resource.os_profile.linux_configuration.ssh = self.compute_models.SshConfiguration(public_keys=[])
2584 for key in public_keys:
2585 vm_resource.os_profile.linux_configuration.ssh.public_keys.append(
2586 self.compute_models.SshPublicKey(path=key['path'], key_data=key['key_data'])
2587 )
2588
2589 # data disk
2590 if vm_dict['storage_profile'].get('data_disks'):
2591 data_disks = []
2592
2593 requested_dd_delete = {}
2594 if self.data_disks:
2595 for dd in self.data_disks:
2596 if dd.get('delete_option') is not None:
2597 requested_dd_delete[int(dd['lun'])] = dd['delete_option']
2598
2599 for data_disk in vm_dict['storage_profile']['data_disks']:
2600 if data_disk.get('managed_disk'):
2601 managed_disk_type = data_disk['managed_disk'].get('storage_account_type')
2602 data_disk_managed_disk = self.compute_models.ManagedDiskParameters(storage_account_type=managed_disk_type)
2603 if data_disk.get('disk_encryption_set'):
2604 data_disk_managed_disk.disk_encryption_set = self.compute_models.DiskEncryptionSetParameters(
2605 id=data_disk['disk_encryption_set']
2606 )
2607 data_disk_vhd = None
2608 else:
2609 data_disk_vhd = data_disk['vhd']['uri']
2610 data_disk_managed_disk = None
2611
2612 lun = int(data_disk['lun'])
2613 delete_opt = requested_dd_delete.get(lun)
2614 if delete_opt is None:
2615 delete_opt = data_disk.get('delete_option')
2616
2617 dd_obj = self.compute_models.DataDisk(
2618 lun=lun,
2619 name=data_disk.get('name'),
2620 vhd=data_disk_vhd,
2621 caching=data_disk.get('caching'),
2622 create_option=data_disk.get('create_option'),
2623 disk_size_gb=int(data_disk.get('disk_size_gb', 0)) or None,
2624 managed_disk=data_disk_managed_disk,
2625 )
2626 if delete_opt is not None:
2627 dd_obj.delete_option = delete_opt
2628 data_disks.append(dd_obj)
2629 vm_resource.storage_profile.data_disks = data_disks
2630
2631 if self.security_profile is not None:
2632 uefi_settings_spec = None
2633 if self.security_profile.get('uefi_settings') is not None:
2634 uefi_settings_spec = self.compute_models.UefiSettings(
2635 secure_boot_enabled=self.security_profile['uefi_settings'].get('secure_boot_enabled'),
2636 v_tpm_enabled=self.security_profile['uefi_settings'].get('v_tpm_enabled'),
2637 )
2638 security_profile = self.compute_models.SecurityProfile(
2639 uefi_settings=uefi_settings_spec,
2640 encryption_at_host=self.security_profile.get('encryption_at_host'),
2641 security_type=self.security_profile.get('security_type'),
2642 )
2643 vm_resource.security_profile = security_profile
2644
2645 if self.additional_capabilities is not None:
2646 additional_capabilities = self.compute_models.AdditionalCapabilities(
2647 ultra_ssd_enabled=self.additional_capabilities.get('ultra_ssd_enabled')
2648 )
2649 vm_resource.additional_capabilities = additional_capabilities
2650
2651 self.log("Update virtual machine with parameters:")
2652 self.create_or_update_vm(vm_resource, False)
2653
2654 # Make sure we leave the machine in requested power state
2655 if (powerstate_change == 'poweron' and
2656 self.results['ansible_facts']['azure_vm']['powerstate'] != 'running'):
2657 # Attempt to power on the machine
2658 self.power_on_vm()
2659
2660 elif (powerstate_change == 'poweroff' and
2661 self.results['ansible_facts']['azure_vm']['powerstate'] == 'running'):
2662 # Attempt to power off the machine
2663 self.power_off_vm()
2664
2665 elif powerstate_change == 'restarted':
2666 self.restart_vm()
2667
2668 elif powerstate_change == 'deallocated':
2669 self.deallocate_vm()
2670 elif powerstate_change == 'generalized':
2671 current_powerstate = self.results['ansible_facts']['azure_vm']['powerstate']
2672 if current_powerstate != 'deallocated':
2673 self.deallocate_vm()
2674 self.generalize_vm()
2675
2676 self.results['ansible_facts']['azure_vm'] = self.serialize_vm(self.get_vm())
2677
2678 elif self.state == 'absent':
2679 # delete the VM
2680 self.log("Delete virtual machine {0}".format(self.name))
2681 self.results['ansible_facts']['azure_vm'] = None
2682 self.delete_vm(vm)
2683
2684 # until we sort out how we want to do this globally
2685 del self.results['actions']
2686
2687 return self.results
2688
2689 def get_os_disk(self, os_disk):
2690 resource_group_name = None
2691 os_disk_name = None
2692 if os_disk.get('os_disk_id') is not None:
2693 os_disk_dict = self.parse_resource_to_dict(os_disk.get('os_disk_id'))
2694 os_disk_name = os_disk_dict.get('name')
2695 resource_group_name = os_disk_dict.get('resource_group')
2696 elif os_disk.get('os_disk_resource_group') is not None and os_disk.get('os_disk_name') is not None:
2697 os_disk_name = os_disk.get('os_disk_name')
2698 resource_group_name = os_disk.get('os_disk_resource_group')
2699 elif os_disk.get('os_disk_name') is not None:
2700 os_disk_name = os_disk.get('name')
2701 resource_group_name = self.resource_group
2702 else:
2703 self.fail("The swap_os_disk must contain one of 'os_disk_name' and 'os_disk_id'")
2704
2705 try:
2706 os_disk = {}
2707 response = self.disk_client.disks.get(resource_group_name, os_disk_name)
2708 os_disk['name'] = response.name
2709 os_disk['managed_disk'] = dict(id=response.id)
2710 os_disk['create_option'] = response.creation_data.create_option
2711 return os_disk
2712 except Exception:
2713 self.fail('Could not find os disk {0} in resource group {1}'.format(os_disk_name, resource_group_name))
2714
2715 def get_vm(self):
2716 '''
2717 Get the VM with expanded instanceView
2718
2719 :return: VirtualMachine object
2720 '''
2721 try:
2722 retry_count = 0
2723 vm = self.compute_client.virtual_machines.get(self.resource_group, self.name, expand='instanceview')
2724 while True:
2725 if retry_count == 20:
2726 self.fail("Error {0} has a provisioning state of Updating. Expecting state to be Successed.".format(self.name))
2727
2728 if vm.provisioning_state != 'Succeeded':
2729 retry_count = retry_count + 1
2730 time.sleep(150)
2731 vm = self.compute_client.virtual_machines.get(self.resource_group, self.name, expand='instanceview')
2732 else:
2733 p_state = None
2734 for s in vm.instance_view.statuses:
2735 if s.code.startswith('PowerState'):
2736 p_state = s.code
2737 if p_state is not None:
2738 break
2739 return vm
2740 except Exception as exc:
2741 self.fail("Error getting virtual machine {0} - {1}".format(self.name, str(exc)))
2742
2743 def serialize_vm(self, vm):
2744 '''
2745 Convert a VirtualMachine object to dict.
2746
2747 :param vm: VirtualMachine object
2748 :return: dict
2749 '''
2750
2751 result = self.serialize_obj(vm, AZURE_OBJECT_CLASS, enum_modules=AZURE_ENUM_MODULES)
2752 result['id'] = vm.id
2753 result['name'] = vm.name
2754 result['type'] = vm.type
2755 result['location'] = vm.location
2756 result['tags'] = vm.tags
2757
2758 result['powerstate'] = dict()
2759 if vm.instance_view:
2760 result['powerstate'] = next((s.code.replace('PowerState/', '')
2761 for s in vm.instance_view.statuses if s.code.startswith('PowerState')), None)
2762 for s in vm.instance_view.statuses:
2763 if s.code.lower() == "osstate/generalized":
2764 result['powerstate'] = 'generalized'
2765
2766 # Expand network interfaces to include config properties
2767 for interface in vm.network_profile.network_interfaces:
2768 int_dict = azure_id_to_dict(interface.id)
2769 nic = self.get_network_interface(int_dict['resourceGroups'], int_dict['networkInterfaces'])
2770 for interface_dict in result['network_profile']['network_interfaces']:
2771 if interface_dict['id'] == interface.id:
2772 nic_dict = self.serialize_obj(nic, 'NetworkInterface')
2773 interface_dict['name'] = int_dict['networkInterfaces']
2774 interface_dict['properties'] = nic_dict
2775 # Expand public IPs to include config properties
2776 for interface in result['network_profile']['network_interfaces']:
2777 for config in interface['properties']['ip_configurations']:
2778 if config.get('public_ip_address'):
2779 pipid_dict = azure_id_to_dict(config['public_ip_address']['id'])
2780 try:
2781 pip = self.network_client.public_ip_addresses.get(pipid_dict['resourceGroups'],
2782 pipid_dict['publicIPAddresses'])
2783 except Exception as exc:
2784 self.fail("Error fetching public ip {0} - {1}".format(pipid_dict['publicIPAddresses'],
2785 str(exc)))
2786 pip_dict = self.serialize_obj(pip, 'PublicIPAddress')
2787 config['public_ip_address']['name'] = pipid_dict['publicIPAddresses']
2788 config['public_ip_address']['properties'] = pip_dict['ip_configuration']
2789
2790 self.log(result, pretty_print=True)
2791 if self.state != 'absent' and not result['powerstate']:
2792 self.fail("Failed to determine PowerState of virtual machine {0}".format(self.name))
2793 return result
2794
2795 def power_off_vm(self):
2796 self.log("Powered off virtual machine {0} - Skip_Shutdown {1}".format(self.name, self.force))
2797 self.results['actions'].append("Powered off virtual machine {0} - Skip_Shutdown {1}".format(self.name, self.force))
2798 try:
2799 poller = self.compute_client.virtual_machines.begin_power_off(self.resource_group, self.name, skip_shutdown=self.force)
2800 self.get_poller_result(poller)
2801 except Exception as exc:
2802 self.fail("Error powering off virtual machine {0} - {1}".format(self.name, str(exc)))
2803 return True
2804
2805 def power_on_vm(self):
2806 self.results['actions'].append("Powered on virtual machine {0}".format(self.name))
2807 self.log("Power on virtual machine {0}".format(self.name))
2808 try:
2809 poller = self.compute_client.virtual_machines.begin_start(self.resource_group, self.name)
2810 self.get_poller_result(poller)
2811 except Exception as exc:
2812 self.fail("Error powering on virtual machine {0} - {1}".format(self.name, str(exc)))
2813 return True
2814
2815 def restart_vm(self):
2816 self.results['actions'].append("Restarted virtual machine {0}".format(self.name))
2817 self.log("Restart virtual machine {0}".format(self.name))
2818 try:
2819 poller = self.compute_client.virtual_machines.begin_restart(self.resource_group, self.name)
2820 self.get_poller_result(poller)
2821 except Exception as exc:
2822 self.fail("Error restarting virtual machine {0} - {1}".format(self.name, str(exc)))
2823 return True
2824
2825 def deallocate_vm(self):
2826 self.results['actions'].append("Deallocated virtual machine {0}".format(self.name))
2827 self.log("Deallocate virtual machine {0}".format(self.name))
2828 try:
2829 poller = self.compute_client.virtual_machines.begin_deallocate(self.resource_group, self.name)
2830 self.get_poller_result(poller)
2831 except Exception as exc:
2832 self.fail("Error deallocating virtual machine {0} - {1}".format(self.name, str(exc)))
2833 return True
2834
2835 def generalize_vm(self):
2836 self.results['actions'].append("Generalize virtual machine {0}".format(self.name))
2837 self.log("Generalize virtual machine {0}".format(self.name))
2838 try:
2839 response = self.compute_client.virtual_machines.generalize(self.resource_group, self.name)
2840 if isinstance(response, LROPoller):
2841 self.get_poller_result(response)
2842 except Exception as exc:
2843 self.fail("Error generalizing virtual machine {0} - {1}".format(self.name, str(exc)))
2844 return True
2845
2846 def remove_autocreated_resources(self, tags):
2847 if tags:
2848 sa_name = tags.get('_own_sa_')
2849 nic_name = tags.get('_own_nic_')
2850 pip_name = tags.get('_own_pip_')
2851 nsg_name = tags.get('_own_nsg_')
2852 if sa_name:
2853 self.delete_storage_account(self.resource_group, sa_name)
2854 if nic_name:
2855 self.delete_nic(self.resource_group, nic_name)
2856 if pip_name:
2857 self.delete_pip(self.resource_group, pip_name)
2858 if nsg_name:
2859 self.delete_nsg(self.resource_group, nsg_name)
2860
2861 def delete_vm(self, vm):
2862 vhd_uris = []
2863 managed_disk_ids = []
2864 nic_names = []
2865 pip_names = []
2866
2867 if 'all_autocreated' not in self.remove_on_absent:
2868 if self.remove_on_absent.intersection(set(['all', 'virtual_storage'])):
2869 # store the attached vhd info so we can nuke it after the VM is gone
2870 if (vm.storage_profile.os_disk.managed_disk):
2871 self.log('Storing managed disk ID for deletion')
2872 managed_disk_ids.append(vm.storage_profile.os_disk.managed_disk.id)
2873 elif (vm.storage_profile.os_disk.vhd):
2874 self.log('Storing VHD URI for deletion')
2875 vhd_uris.append(vm.storage_profile.os_disk.vhd.uri)
2876
2877 data_disks = vm.storage_profile.data_disks
2878 for data_disk in data_disks:
2879 if data_disk is not None:
2880 if (data_disk.vhd):
2881 vhd_uris.append(data_disk.vhd.uri)
2882 elif (data_disk.managed_disk):
2883 managed_disk_ids.append(data_disk.managed_disk.id)
2884
2885 # FUTURE enable diff mode, move these there...
2886 self.log("VHD URIs to delete: {0}".format(', '.join(vhd_uris)))
2887 self.results['deleted_vhd_uris'] = vhd_uris
2888 self.log("Managed disk IDs to delete: {0}".format(', '.join(managed_disk_ids)))
2889 self.results['deleted_managed_disk_ids'] = managed_disk_ids
2890
2891 if self.remove_on_absent.intersection(set(['all', 'network_interfaces'])):
2892 # store the attached nic info so we can nuke them after the VM is gone
2893 self.log('Storing NIC names for deletion.')
2894 for interface in vm.network_profile.network_interfaces:
2895 id_dict = azure_id_to_dict(interface.id)
2896 nic_names.append(dict(name=id_dict['networkInterfaces'], resource_group=id_dict['resourceGroups']))
2897 self.log('NIC names to delete {0}'.format(str(nic_names)))
2898 self.results['deleted_network_interfaces'] = nic_names
2899 if self.remove_on_absent.intersection(set(['all', 'public_ips'])):
2900 # also store each nic's attached public IPs and delete after the NIC is gone
2901 for nic_dict in nic_names:
2902 nic = self.get_network_interface(nic_dict['resource_group'], nic_dict['name'])
2903 for ipc in nic.ip_configurations:
2904 if ipc.public_ip_address:
2905 pip_dict = azure_id_to_dict(ipc.public_ip_address.id)
2906 pip_names.append(dict(name=pip_dict['publicIPAddresses'], resource_group=pip_dict['resourceGroups']))
2907 self.log('Public IPs to delete are {0}'.format(str(pip_names)))
2908 self.results['deleted_public_ips'] = pip_names
2909
2910 self.log("Deleting virtual machine {0}".format(self.name))
2911 self.results['actions'].append("Deleted virtual machine {0}".format(self.name))
2912 try:
2913 poller = self.compute_client.virtual_machines.begin_delete(self.resource_group, self.name)
2914 # wait for the poller to finish
2915 self.get_poller_result(poller)
2916 except Exception as exc:
2917 self.fail("Error deleting virtual machine {0} - {1}".format(self.name, str(exc)))
2918
2919 # TODO: parallelize nic, vhd, and public ip deletions with begin_deleting
2920 # TODO: best-effort to keep deleting other linked resources if we encounter an error
2921 if self.remove_on_absent.intersection(set(['all', 'virtual_storage'])):
2922 self.log('Deleting VHDs')
2923 self.delete_vm_storage(vhd_uris)
2924 self.log('Deleting managed disks')
2925 self.delete_managed_disks(managed_disk_ids)
2926
2927 if 'all' in self.remove_on_absent or 'all_autocreated' in self.remove_on_absent:
2928 self.remove_autocreated_resources(vm.tags)
2929
2930 if self.remove_on_absent.intersection(set(['all', 'network_interfaces'])):
2931 self.log('Deleting network interfaces')
2932 for nic_dict in nic_names:
2933 self.delete_nic(nic_dict['resource_group'], nic_dict['name'])
2934
2935 if self.remove_on_absent.intersection(set(['all', 'public_ips'])):
2936 self.log('Deleting public IPs')
2937 for pip_dict in pip_names:
2938 self.delete_pip(pip_dict['resource_group'], pip_dict['name'])
2939
2940 if 'all' in self.remove_on_absent or 'all_autocreated' in self.remove_on_absent:
2941 self.remove_autocreated_resources(vm.tags)
2942
2943 return True
2944
2945 def get_network_interface(self, resource_group, name):
2946 try:
2947 nic = self.network_client.network_interfaces.get(resource_group, name)
2948 return nic
2949 except ResourceNotFoundError as exc:
2950 self.fail("Error fetching network interface {0} - {1}".format(name, str(exc)))
2951 return True
2952
2953 def delete_nic(self, resource_group, name):
2954 self.log("Deleting network interface {0}".format(name))
2955 self.results['actions'].append("Deleted network interface {0}".format(name))
2956 try:
2957 poller = self.network_client.network_interfaces.begin_delete(resource_group, name)
2958 except Exception as exc:
2959 self.fail("Error deleting network interface {0} - {1}".format(name, str(exc)))
2960 self.get_poller_result(poller)
2961 # Delete doesn't return anything. If we get this far, assume success
2962 return True
2963
2964 def delete_pip(self, resource_group, name):
2965 self.results['actions'].append("Deleted public IP {0}".format(name))
2966 try:
2967 poller = self.network_client.public_ip_addresses.begin_delete(resource_group, name)
2968 self.get_poller_result(poller)
2969 except Exception as exc:
2970 self.fail("Error deleting {0} - {1}".format(name, str(exc)))
2971 # Delete returns nada. If we get here, assume that all is well.
2972 return True
2973
2974 def delete_nsg(self, resource_group, name):
2975 self.results['actions'].append("Deleted NSG {0}".format(name))
2976 try:
2977 poller = self.network_client.network_security_groups.begin_delete(resource_group, name)
2978 self.get_poller_result(poller)
2979 except Exception as exc:
2980 self.fail("Error deleting {0} - {1}".format(name, str(exc)))
2981 return True
2982
2983 def delete_managed_disks(self, managed_disk_ids):
2984 for mdi in managed_disk_ids:
2985 try:
2986 poller = self.rm_client.resources.begin_delete_by_id(mdi, '2017-03-30')
2987 self.get_poller_result(poller)
2988 except Exception as exc:
2989 self.fail("Error deleting managed disk {0} - {1}".format(mdi, str(exc)))
2990 return True
2991
2992 def delete_storage_account(self, resource_group, name):
2993 self.log("Delete storage account {0}".format(name))
2994 self.results['actions'].append("Deleted storage account {0}".format(name))
2995 try:
2996 self.storage_client.storage_accounts.delete(self.resource_group, name)
2997 except Exception as exc:
2998 self.fail("Error deleting storage account {0} - {1}".format(name, str(exc)))
2999 return True
3000
3001 def delete_vm_storage(self, vhd_uris):
3002 # FUTURE: figure out a cloud_env indepdendent way to delete these
3003 for uri in vhd_uris:
3004 self.log("Extracting info from blob uri '{0}'".format(uri))
3005 try:
3006 blob_parts = extract_names_from_blob_uri(uri, self._cloud_environment.suffixes.storage_endpoint)
3007 except Exception as exc:
3008 self.fail("Error parsing blob URI {0}".format(str(exc)))
3009 storage_account_name = blob_parts['accountname']
3010 container_name = blob_parts['containername']
3011 blob_name = blob_parts['blobname']
3012
3013 blob_service_client = self.get_blob_service_client(self.resource_group, storage_account_name)
3014
3015 self.log("Delete blob {0}:{1}".format(container_name, blob_name))
3016 self.results['actions'].append("Deleted blob {0}:{1}".format(container_name, blob_name))
3017 try:
3018 blob_service_client.get_blob_client(container=container_name, blob=blob_name).delete_blob()
3019 except Exception as exc:
3020 self.fail("Error deleting blob {0}:{1} - {2}".format(container_name, blob_name, str(exc)))
3021 return True
3022
3023 def get_marketplace_image_version(self):
3024 try:
3025 versions = self.compute_client.virtual_machine_images.list(self.location,
3026 self.image['publisher'],
3027 self.image['offer'],
3028 self.image['sku'],
3029 orderby='name')
3030 except Exception as exc:
3031 self.fail("Error fetching image {0} {1} {2} - {3}".format(self.image['publisher'],
3032 self.image['offer'],
3033 self.image['sku'],
3034 str(exc)))
3035
3036 if versions and len(versions) > 0:
3037 if self.image['version'] == 'latest':
3038 version = versions[len(versions) - 1]
3039
3040 def image_timestamp_to_datetime(version_string):
3041 version_len = len(version_string)
3042 if version_len == 8:
3043 t_format = "%Y%m%d"
3044 elif version_len <= 10:
3045 t_format = "%Y%m%d%H"
3046 elif version_len <= 12:
3047 t_format = "%Y%m%d%H%M"
3048 elif version_len <= 14:
3049 t_format = "%Y%m%d%H%M%S"
3050 return datetime.strptime(version_string, t_format)
3051
3052 if 8 <= len(version.name.split('.')[-1]) and len(version.name.split('.')[-1]) <= 14:
3053 version_date = image_timestamp_to_datetime(version.name.split('.')[-1])
3054 for item in versions:
3055 item_date = image_timestamp_to_datetime(item.name.split('.')[-1])
3056 if item_date > version_date:
3057 version = item
3058 version_date = item_date
3059 else:
3060 version_name = version.name.split('.')[-1]
3061 for item in versions:
3062 item_name = item.name.split('.')[-1]
3063 if item_name > version_name:
3064 version = item
3065 version_name = item_name
3066 return version
3067 for version in versions:
3068 if version.name == self.image['version']:
3069 return version
3070
3071 self.fail("Error could not find image {0} {1} {2} {3}".format(self.image['publisher'],
3072 self.image['offer'],
3073 self.image['sku'],
3074 self.image['version']))
3075 return None
3076
3077 def get_custom_image_reference(self, name, resource_group=None):
3078 try:
3079 if resource_group:
3080 vm_images = self.compute_client.images.list_by_resource_group(resource_group)
3081 else:
3082 vm_images = self.compute_client.images.list()
3083 except Exception as exc:
3084 self.fail("Error fetching custom images from subscription - {0}".format(str(exc)))
3085
3086 for vm_image in vm_images:
3087 if vm_image.name == name:
3088 self.log("Using custom image id {0}".format(vm_image.id))
3089 return self.compute_models.ImageReference(id=vm_image.id)
3090
3091 self.fail("Error could not find image with name {0}".format(name))
3092 return None
3093
3094 def get_capacity_reservation_group(self, resource_group, name):
3095 try:
3096 return self.compute_client.capacity_reservation_groups.get(resource_group, name)
3097 except Exception as exc:
3098 self.fail("Error fetching capacity reservation group {0} - {1}".format(name, str(exc)))
3099
3100 def get_proximity_placement_group(self, resource_group, name):
3101 try:
3102 return self.compute_client.proximity_placement_groups.get(resource_group, name)
3103 except Exception as exc:
3104 self.fail("Error fetching proximity placement group {0} - {1}".format(name, str(exc)))
3105
3106 def get_availability_set(self, resource_group, name):
3107 try:
3108 return self.compute_client.availability_sets.get(resource_group, name)
3109 except Exception as exc:
3110 self.fail("Error fetching availability set {0} - {1}".format(name, str(exc)))
3111
3112 def get_storage_account(self, resource_group, name):
3113 try:
3114 account = self.storage_client.storage_accounts.get_properties(resource_group,
3115 name)
3116 return account
3117 except Exception as exc:
3118 self.fail("Error fetching storage account {0} - {1}".format(name, str(exc)))
3119
3120 def create_or_update_vm(self, params, remove_autocreated_on_failure):
3121 try:
3122 poller = self.compute_client.virtual_machines.begin_create_or_update(self.resource_group, self.name, params)
3123 self.get_poller_result(poller)
3124 except Exception as exc:
3125 if remove_autocreated_on_failure:
3126 self.remove_autocreated_resources(params.tags)
3127 self.fail("Error creating or updating virtual machine {0} - {1}".format(self.name, str(exc)))
3128
3129 def vm_size_is_valid(self):
3130 '''
3131 Validate self.vm_size against the list of virtual machine sizes available for the account and location.
3132
3133 :return: boolean
3134 '''
3135 try:
3136 sizes = self.compute_client.virtual_machine_sizes.list(self.location)
3137 except Exception as exc:
3138 self.fail("Error retrieving available machine sizes - {0}".format(str(exc)))
3139 for size in sizes:
3140 if size.name == self.vm_size:
3141 return True
3142 return False
3143
3144 def create_default_storage_account(self, vm_dict=None):
3145 '''
3146 Create (once) a default storage account <vm name>XXXX, where XXXX is a random number.
3147 NOTE: If <vm name>XXXX exists, use it instead of failing. Highly unlikely.
3148 If this method is called multiple times across executions it will return the same
3149 storage account created with the random name which is stored in a tag on the VM.
3150
3151 vm_dict is passed in during an update, so we can obtain the _own_sa_ tag and return
3152 the default storage account we created in a previous invocation
3153
3154 :return: storage account object
3155 '''
3156 account = None
3157 valid_name = False
3158 if self.tags is None:
3159 self.tags = {}
3160
3161 if self.tags.get('_own_sa_', None):
3162 # We previously created one in the same invocation
3163 return self.get_storage_account(self.resource_group, self.tags['_own_sa_'])
3164
3165 if vm_dict and vm_dict.get('tags', {}).get('_own_sa_', None):
3166 # We previously created one in a previous invocation
3167 # We must be updating, like adding boot diagnostics
3168 return self.get_storage_account(self.resource_group, vm_dict['tags']['_own_sa_'])
3169
3170 # Attempt to find a valid storage account name
3171 storage_account_name_base = re.sub('[^a-zA-Z0-9]', '', self.name[:20].lower())
3172 for i in range(0, 5):
3173 rand = random.randrange(1000, 9999)
3174 storage_account_name = storage_account_name_base + str(rand)
3175 if self.check_storage_account_name(storage_account_name):
3176 valid_name = True
3177 break
3178
3179 if not valid_name:
3180 self.fail("Failed to create a unique storage account name for {0}. Try using a different VM name."
3181 .format(self.name))
3182
3183 try:
3184 account = self.storage_client.storage_accounts.get_properties(self.resource_group, storage_account_name)
3185 except Exception:
3186 pass
3187
3188 if account:
3189 self.log("Storage account {0} found.".format(storage_account_name))
3190 self.check_provisioning_state(account)
3191 return account
3192 sku = self.storage_models.Sku(name=self.storage_models.SkuName.standard_lrs)
3193 sku.tier = self.storage_models.SkuTier.standard
3194 kind = self.storage_models.Kind.storage
3195 # pylint: disable=missing-kwoa
3196 parameters = self.storage_models.StorageAccountCreateParameters(sku=sku, kind=kind, location=self.location)
3197 self.log("Creating storage account {0} in location {1}".format(storage_account_name, self.location))
3198 self.results['actions'].append("Created storage account {0}".format(storage_account_name))
3199 try:
3200 poller = self.storage_client.storage_accounts.begin_create(self.resource_group, storage_account_name, parameters)
3201 self.get_poller_result(poller)
3202 except Exception as exc:
3203 self.fail("Failed to create storage account: {0} - {1}".format(storage_account_name, str(exc)))
3204 self.tags['_own_sa_'] = storage_account_name
3205 return self.get_storage_account(self.resource_group, storage_account_name)
3206
3207 def check_storage_account_name(self, name):
3208 self.log("Checking storage account name availability for {0}".format(name))
3209 try:
3210 account_name = self.storage_models.StorageAccountCheckNameAvailabilityParameters(name=name)
3211 response = self.storage_client.storage_accounts.check_name_availability(account_name)
3212 if response.reason == 'AccountNameInvalid':
3213 raise Exception("Invalid default storage account name: {0}".format(name))
3214 except Exception as exc:
3215 self.fail("Error checking storage account name availability for {0} - {1}".format(name, str(exc)))
3216
3217 return response.name_available
3218
3219 def create_default_nic(self):
3220 '''
3221 Create a default Network Interface <vm name>01. Requires an existing virtual network
3222 with one subnet. If NIC <vm name>01 exists, use it. Otherwise, create one.
3223 Default NIC and the public IP associated with it, have delete_option = "DELETE".
3224
3225 :return: NIC object
3226 '''
3227
3228 network_interface_name = self.name + '01'
3229 nic = None
3230 if self.tags is None:
3231 self.tags = {}
3232
3233 self.log("Create default NIC {0}".format(network_interface_name))
3234 self.log("Check to see if NIC {0} exists".format(network_interface_name))
3235 try:
3236 nic = self.network_client.network_interfaces.get(self.resource_group, network_interface_name)
3237 except ResourceNotFoundError:
3238 pass
3239
3240 if nic:
3241 self.log("NIC {0} found.".format(network_interface_name))
3242 self.check_provisioning_state(nic)
3243 return nic
3244
3245 self.log("NIC {0} does not exist.".format(network_interface_name))
3246
3247 virtual_network_resource_group = None
3248 if self.virtual_network_resource_group:
3249 virtual_network_resource_group = self.virtual_network_resource_group
3250 else:
3251 virtual_network_resource_group = self.resource_group
3252
3253 if self.virtual_network_name:
3254 try:
3255 self.network_client.virtual_networks.get(virtual_network_resource_group, self.virtual_network_name)
3256 virtual_network_name = self.virtual_network_name
3257 except ResourceNotFoundError as exc:
3258 self.fail("Error: fetching virtual network {0} - {1}".format(self.virtual_network_name, str(exc)))
3259
3260 else:
3261 # Find a virtual network
3262 no_vnets_msg = "Error: unable to find virtual network in resource group {0}. A virtual network " \
3263 "with at least one subnet must exist in order to create a NIC for the virtual " \
3264 "machine.".format(virtual_network_resource_group)
3265
3266 virtual_network_name = None
3267 try:
3268 vnets = self.network_client.virtual_networks.list(virtual_network_resource_group)
3269 except ResourceNotFoundError:
3270 self.log('cloud error!')
3271 self.fail(no_vnets_msg)
3272
3273 for vnet in vnets:
3274 virtual_network_name = vnet.name
3275 self.log('vnet name: {0}'.format(vnet.name))
3276 break
3277
3278 if not virtual_network_name:
3279 self.fail(no_vnets_msg)
3280
3281 if self.subnet_name:
3282 try:
3283 subnet = self.network_client.subnets.get(virtual_network_resource_group, virtual_network_name, self.subnet_name)
3284 subnet_id = subnet.id
3285 except Exception as exc:
3286 self.fail("Error: fetching subnet {0} - {1}".format(self.subnet_name, str(exc)))
3287 else:
3288 no_subnets_msg = "Error: unable to find a subnet in virtual network {0}. A virtual network " \
3289 "with at least one subnet must exist in order to create a NIC for the virtual " \
3290 "machine.".format(virtual_network_name)
3291
3292 subnet_id = None
3293 try:
3294 subnets = self.network_client.subnets.list(virtual_network_resource_group, virtual_network_name)
3295 except Exception:
3296
3297 self.fail(no_subnets_msg)
3298
3299 for subnet in subnets:
3300 subnet_id = subnet.id
3301 self.log('subnet id: {0}'.format(subnet_id))
3302 break
3303
3304 if not subnet_id:
3305 self.fail(no_subnets_msg)
3306
3307 pip = None
3308 if self.public_ip_allocation_method != 'Disabled':
3309 self.results['actions'].append('Created default public IP {0}'.format(self.name + '01'))
3310 sku = self.network_models.PublicIPAddressSku(name="Standard")
3311 pip_facts = self.create_default_pip(self.resource_group, self.location, self.name + '01', self.public_ip_allocation_method, sku=sku)
3312 pip = self.network_models.PublicIPAddress(id=pip_facts.id, location=pip_facts.location, resource_guid=pip_facts.resource_guid, sku=sku)
3313 # ensure Public IP gets deleted when NIC is deleted
3314 pip.delete_option = 'Delete'
3315 self.tags['_own_pip_'] = self.name + '01'
3316
3317 parameters = self.network_models.NetworkInterface(
3318 location=self.location,
3319 ip_configurations=[
3320 self.network_models.NetworkInterfaceIPConfiguration(
3321 private_ip_allocation_method='Dynamic',
3322 )
3323 ]
3324 )
3325 parameters.ip_configurations[0].subnet = self.network_models.Subnet(id=subnet_id)
3326 parameters.ip_configurations[0].name = 'default'
3327
3328 if self.created_nsg:
3329 self.results['actions'].append('Created default security group {0}'.format(self.name + '01'))
3330 group = self.create_default_securitygroup(self.resource_group, self.location, self.name + '01', self.os_type,
3331 self.open_ports)
3332 parameters.network_security_group = self.network_models.NetworkSecurityGroup(id=group.id,
3333 location=group.location,
3334 resource_guid=group.resource_guid)
3335 self.tags['_own_nsg_'] = self.name + '01'
3336
3337 parameters.ip_configurations[0].public_ip_address = pip
3338
3339 self.log("Creating NIC {0}".format(network_interface_name))
3340 self.log(self.serialize_obj(parameters, 'NetworkInterface'), pretty_print=True)
3341 self.results['actions'].append("Created NIC {0}".format(network_interface_name))
3342 try:
3343 poller = self.network_client.network_interfaces.begin_create_or_update(self.resource_group,
3344 network_interface_name,
3345 parameters)
3346 new_nic = self.get_poller_result(poller)
3347 self.tags['_own_nic_'] = network_interface_name
3348 except Exception as exc:
3349 self.fail("Error creating network interface {0} - {1}".format(network_interface_name, str(exc)))
3350 return new_nic
3351
3352 def parse_network_interface(self, nic):
3353 nic = self.parse_resource_to_dict(nic)
3354 if 'name' not in nic:
3355 self.fail("Invalid network interface {0}".format(str(nic)))
3356 return format_resource_id(val=nic['name'],
3357 subscription_id=nic['subscription_id'],
3358 resource_group=nic['resource_group'],
3359 namespace='Microsoft.Network',
3360 types='networkInterfaces')
3361
3362
3363 def main():
3364 AzureRMVirtualMachine()
3365
3366
3367 if __name__ == '__main__':
3368 main()