Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2016 Sertac Ozercan, <[email protected]>
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10
11 DOCUMENTATION = '''
12 ---
13 module: azure_rm_virtualmachinescaleset
14
15 version_added: "0.1.2"
16
17 short_description: Manage Azure virtual machine scale sets
18
19 description:
20 - Create and update a virtual machine scale set.
21 - Note that this module was called M(azure.azcollection.azure_rm_virtualmachine_scaleset) before Ansible 2.8. The usage did not change.
22
23 options:
24 resource_group:
25 description:
26 - Name of the resource group containing the virtual machine scale set.
27 required: true
28 type: str
29 name:
30 description:
31 - Name of the virtual machine.
32 required: true
33 type: str
34 state:
35 description:
36 - Assert the state of the virtual machine scale set.
37 - State C(present) will check that the machine exists with the requested configuration. If the configuration
38 of the existing machine does not match, the machine will be updated.
39 - State C(absent) will remove the virtual machine scale set.
40 default: present
41 type: str
42 choices:
43 - absent
44 - present
45 location:
46 description:
47 - Valid Azure location. Defaults to location of the resource group.
48 type: str
49 short_hostname:
50 description:
51 - Short host name.
52 type: str
53 vm_size:
54 description:
55 - A valid Azure VM size value. For example, C(Standard_D4).
56 - The list of choices varies depending on the subscription and location. Check your subscription for available choices.
57 type: str
58 capacity:
59 description:
60 - Capacity of VMSS.
61 default: 1
62 type: int
63 tier:
64 description:
65 - SKU Tier.
66 type: str
67 choices:
68 - Basic
69 - Standard
70 upgrade_policy:
71 description:
72 - Upgrade policy.
73 - Required when creating the Azure virtual machine scale sets.
74 type: str
75 choices:
76 - Manual
77 - Automatic
78 priority:
79 description:
80 - Priority of the VMSS.
81 - C(None) is the equivalent of Regular VM.
82 type: str
83 choices:
84 - None
85 - Spot
86 - Regular
87 eviction_policy:
88 description:
89 - Specifies the eviction policy for the Azure Spot virtual machine.
90 - Requires priority to be set to Spot.
91 type: str
92 choices:
93 - Deallocate
94 - Delete
95 max_price:
96 description:
97 - Specifies the maximum price you are willing to pay for a Azure Spot VM/VMSS.
98 - This price is in US Dollars.
99 - C(-1) indicates default price to be up-to on-demand.
100 - Requires priority to be set to Spot.
101 default: -1
102 type: float
103 admin_username:
104 description:
105 - Admin username used to access the host after it is created. Required when creating a VM.
106 type: str
107 admin_password:
108 description:
109 - Password for the admin username.
110 - Not required if the os_type is Linux and SSH password authentication is disabled by setting I(ssh_password_enabled=false).
111 type: str
112 ssh_password_enabled:
113 description:
114 - When the os_type is Linux, setting I(ssh_password_enabled=false) will disable SSH password authentication and require use of SSH keys.
115 type: bool
116 default: true
117 ssh_public_keys:
118 description:
119 - For I(os_type=Linux) provide a list of SSH keys.
120 - Each item in the list should be a dictionary where the dictionary contains two keys, C(path) and C(key_data).
121 - Set the C(path) to the default location of the authorized_keys files.
122 - On an Enterprise Linux host, for example, the I(path=/home/<admin username>/.ssh/authorized_keys).
123 Set C(key_data) to the actual value of the public key.
124 type: list
125 elements: dict
126 image:
127 description:
128 - Specifies the image used to build the VM.
129 - If a string, the image is sourced from a custom image based on the name.
130 - If a dict with the keys I(publisher), I(offer), I(sku), and I(version), the image is sourced from a Marketplace image.
131 Note that set I(version=latest) to get the most recent version of a given image.
132 - If a dict with the keys I(name) and I(resource_group), the image is sourced from a custom image based on the I(name) and I(resource_group) set.
133 Note that the key I(resource_group) is optional and if omitted, all images in the subscription will be searched for by I(name).
134 - Custom image support was added in Ansible 2.5.
135 - For community images, a dict with the keys I(community_gallery_image_id). Specified the community gallery image unique id for vm demployment.
136 - The I(community_gallery_image_id) can be fetched from shared gallery image GET call.
137 - Required when creating.
138 type: raw
139 os_disk_caching:
140 description:
141 - Type of OS disk caching.
142 type: str
143 choices:
144 - ReadOnly
145 - ReadWrite
146 default: ReadOnly
147 aliases:
148 - disk_caching
149 os_disk_size_gb:
150 description:
151 - Specifies the size of the operating system disk in gigabytes.
152 - This can be used to overwrite the size of the disk in a virtual machine image.
153 type: int
154 os_disk_encryption_set:
155 description:
156 - The resource ID of the disk encryption set for the OS disk.
157 type: str
158 os_type:
159 description:
160 - Base type of operating system.
161 type: str
162 choices:
163 - Windows
164 - Linux
165 - windows
166 - linux
167 default: Linux
168 ephemeral_os_disk:
169 description:
170 - Parameters of ephemeral disk settings that can be specified for operating system disk.
171 - Ephemeral OS disk is only supported for VMS Instances using Managed Disk.
172 type: bool
173 managed_disk_type:
174 description:
175 - Managed disk type.
176 type: str
177 choices:
178 - Standard_LRS
179 - Premium_LRS
180 - StandardSSD_LRS
181 - UltraSSD_LRS
182 - Premium_ZRS
183 - StandardSSD_ZRS
184 data_disks:
185 description:
186 - Describes list of data disks.
187 type: list
188 elements: dict
189 suboptions:
190 lun:
191 description:
192 - The logical unit number for data disk.
193 default: '0'
194 type: str
195 disk_size_gb:
196 description:
197 - The initial disk size in GB for blank data disks.
198 type: int
199 managed_disk_type:
200 description:
201 - Managed data disk type.
202 type: str
203 choices:
204 - Standard_LRS
205 - Premium_LRS
206 - StandardSSD_LRS
207 - UltraSSD_LRS
208 - Premium_ZRS
209 - StandardSSD_ZRS
210 caching:
211 description:
212 - Type of data disk caching.
213 type: str
214 choices:
215 - ReadOnly
216 - ReadWrite
217 default: ReadOnly
218 disk_encryption_set:
219 description:
220 - The resource ID of the disk encryption set for the data disks.
221 type: str
222 virtual_network_resource_group:
223 description:
224 - When creating a virtual machine, if a specific virtual network from another resource group should be
225 used.
226 - Use this parameter to specify the resource group to use.
227 type: str
228 virtual_network_name:
229 description:
230 - Virtual Network name.
231 aliases:
232 - virtual_network
233 type: str
234 subnet_name:
235 description:
236 - Subnet name.
237 type: str
238 aliases:
239 - subnet
240 public_ip_per_vm:
241 description:
242 - Assign a public IP to each virtual machine of the scale set
243 type: bool
244 default: False
245 load_balancer:
246 description:
247 - Load balancer name.
248 type: str
249 application_gateway:
250 description:
251 - Application gateway name.
252 type: str
253 remove_on_absent:
254 description:
255 - When removing a VM using I(state=absent), also remove associated resources.
256 - It can be C(all) or a list with any of the following ['network_interfaces', 'virtual_storage', 'public_ips'].
257 - Any other input will be ignored.
258 type: list
259 elements: str
260 default: ['all']
261 enable_accelerated_networking:
262 description:
263 - Indicates whether user wants to allow accelerated networking for virtual machines in scaleset being created.
264 type: bool
265 security_group:
266 description:
267 - Existing security group with which to associate the subnet.
268 - It can be the security group name which is in the same resource group.
269 - It can be the resource ID.
270 - It can be a dict which contains I(name) and I(resource_group) of the security group.
271 aliases:
272 - security_group_name
273 type: raw
274 overprovision:
275 description:
276 - Specifies whether the Virtual Machine Scale Set should be overprovisioned.
277 type: bool
278 single_placement_group:
279 description:
280 - When true this limits the scale set to a single placement group, of max size 100 virtual machines.
281 type: bool
282 default: False
283 plan:
284 description:
285 - Third-party billing plan for the VM.
286 type: dict
287 suboptions:
288 name:
289 description:
290 - Billing plan name.
291 required: true
292 type: str
293 product:
294 description:
295 - Product name.
296 required: true
297 type: str
298 publisher:
299 description:
300 - Publisher offering the plan.
301 required: true
302 type: str
303 promotion_code:
304 description:
305 - Optional promotion code.
306 type: str
307 zones:
308 description:
309 - A list of Availability Zones for your virtual machine scale set.
310 type: list
311 elements: str
312 custom_data:
313 description:
314 - Data which is made available to the virtual machine and used by e.g., C(cloud-init).
315 - Many images in the marketplace are not cloud-init ready. Thus, data sent to I(custom_data) would be ignored.
316 - If the image you are attempting to use is not listed in
317 U(https://docs.microsoft.com/en-us/azure/virtual-machines/linux/using-cloud-init#cloud-init-overview),
318 follow these steps U(https://docs.microsoft.com/en-us/azure/virtual-machines/linux/cloudinit-prepare-custom-image).
319 type: str
320 scale_in_policy:
321 description:
322 - define the order in which vmss instances are scaled-in
323 type: str
324 choices:
325 - Default
326 - NewestVM
327 - OldestVM
328 terminate_event_timeout_minutes:
329 description:
330 - timeout time for termination notification event
331 - in range between 5 and 15
332 type: int
333 platform_fault_domain_count:
334 description:
335 - Fault Domain count for each placement group.
336 type: int
337 default: 1
338 orchestration_mode:
339 description:
340 - Specifies the orchestration mode for the virtual machine scale set.
341 - When I(orchestration_mode=Flexible), I(public_ip_per_vm=True) must be set.
342 - When I(orchestration_mode=Flexible), I(platform_fault_domain_count) must be set.
343 - When I(orchestration_mode=Flexible), I(single_placement_group=False) must be set.
344 - When I(orchestration_mode=Flexible), it cannot be configured I(overprovision).
345 - When I(orchestration_mode=Flexible), it cannot be configured I(upgrade_policy) and configured when I(orchestration_mode=Uniform).
346 type: str
347 choices:
348 - Flexible
349 - Uniform
350 default: Flexible
351 security_profile:
352 description:
353 - Specifies the Security related profile settings for the virtual machine sclaset.
354 type: dict
355 suboptions:
356 encryption_at_host:
357 description:
358 - This property can be used by user in the request to enable or disable the Host Encryption for the virtual machine sclaset.
359 - This will enable the encryption for all the disks including Resource/Temp disk at host itself.
360 type: bool
361 security_type:
362 description:
363 - Specifies the SecurityType of the virtual machine sclaset.
364 - It is set as TrustedLaunch to enable UefiSettings.
365 type: str
366 choices:
367 - TrustedLaunch
368 uefi_settings:
369 description:
370 - Specifies the security settings like secure boot and vTPM used while creating the virtual machine scalset.
371 type: dict
372 suboptions:
373 secure_boot_enabled:
374 description:
375 - Specifies whether secure boot should be enabled on the virtual machine sclaset.
376 type: bool
377 v_tpm_enabled:
378 description:
379 - Specifies whether vTPM should be enabled on the virtual machine scalset.
380 type: bool
381 application_security_groups:
382 description:
383 - Specifies an array of references to application security group. Resource ID of the application security group.
384 type: list
385 elements: str
386 private_ip_address_version:
387 description:
388 - Available from Api-Version 2017-03-30 onwards, it represents whether the specific ipconfiguration is C(IPv4) or C(IPv6).
389 - Default is taken as IPv4.
390 type: str
391 choices:
392 - IPv4
393 - IPv6
394
395 extends_documentation_fragment:
396 - azure.azcollection.azure
397 - azure.azcollection.azure_tags
398 - azure.azcollection.azure_identity_multiple
399
400 author:
401 - Sertac Ozercan (@sozercan)
402
403 '''
404 EXAMPLES = '''
405
406 - name: Create VMSS
407 azure_rm_virtualmachinescaleset:
408 resource_group: myResourceGroup
409 name: testvmss
410 vm_size: Standard_DS1_v2
411 capacity: 2
412 virtual_network_name: testvnet
413 upgrade_policy: Manual
414 subnet_name: testsubnet
415 terminate_event_timeout_minutes: 10
416 scale_in_policy: NewestVM
417 admin_username: "{{ username }}"
418 ssh_password_enabled: false
419 ssh_public_keys:
420 - path: /home/adminUser/.ssh/authorized_keys
421 key_data: < insert your ssh public key here... >
422 managed_disk_type: Standard_LRS
423 image:
424 offer: 0001-com-ubuntu-server-focal
425 publisher: canonical
426 sku: 20_04-lts-gen2
427 version: latest
428 data_disks:
429 - lun: 0
430 disk_size_gb: 64
431 caching: ReadWrite
432 managed_disk_type: Standard_LRS
433
434 - name: Create VMSS with an image that requires plan information
435 azure_rm_virtualmachinescaleset:
436 resource_group: myResourceGroup
437 name: testvmss
438 vm_size: Standard_DS1_v2
439 capacity: 3
440 virtual_network_name: testvnet
441 upgrade_policy: Manual
442 subnet_name: testsubnet
443 admin_username: "{{ username }}"
444 ssh_password_enabled: false
445 ssh_public_keys:
446 - path: /home/adminUser/.ssh/authorized_keys
447 key_data: < insert your ssh public key here... >
448 managed_disk_type: Standard_LRS
449 image:
450 offer: cis-ubuntu-linux-1804-l1
451 publisher: center-for-internet-security-inc
452 sku: Stable
453 version: latest
454 plan:
455 name: cis-ubuntu-linux-1804-l1
456 product: cis-ubuntu-linux-1804-l1
457 publisher: center-for-internet-security-inc
458 data_disks:
459 - lun: 0
460 disk_size_gb: 64
461 caching: ReadWrite
462 managed_disk_type: Standard_LRS
463
464 - name: Create a VMSS with a custom image
465 azure_rm_virtualmachinescaleset:
466 resource_group: myResourceGroup
467 name: testvmss
468 vm_size: Standard_DS1_v2
469 capacity: 2
470 virtual_network_name: testvnet
471 upgrade_policy: Manual
472 subnet_name: testsubnet
473 admin_username: "{{ username }}"
474 admin_password: "{{ password }}"
475 managed_disk_type: Standard_LRS
476 image: customimage001
477
478 - name: Create a VMSS with a community gallery image ID
479 azure_rm_virtualmachinescaleset:
480 resource_group: myResourceGroup
481 name: testvmss
482 vm_size: Standard_D8_v4
483 admin_username: testuser
484 single_placement_group: false
485 platform_fault_domain_count: 1
486 public_ip_per_vm: true
487 ssh_password_enabled: false
488 ssh_public_keys:
489 - path: /home/testuser/.ssh/authorized_keys
490 key_data: "ssh-rsa ********* [email protected]"
491 virtual_network_name: VMSStestVnet
492 subnet_name: VMSStestSubnet
493 managed_disk_type: Standard_LRS
494 orchestration_mode: Flexible
495 os_disk_caching: ReadWrite
496 image:
497 community_gallery_image_id: "/CommunityGalleries/yellowbrick-fc7e81f1-87dd-4989-9ca8-03743762e873/Images/Ubuntu-5.15.0-1035-azure_22.04"
498 data_disks:
499 - lun: 0
500 disk_size_gb: 64
501 caching: ReadWrite
502 managed_disk_type: Standard_LRS
503
504 - name: Create a VMSS with over 100 instances
505 azure_rm_virtualmachinescaleset:
506 resource_group: myResourceGroup
507 name: testvmss
508 vm_size: Standard_DS1_v2
509 capacity: 120
510 single_placement_group: false
511 virtual_network_name: testvnet
512 upgrade_policy: Manual
513 subnet_name: testsubnet
514 admin_username: "{{ username }}"
515 admin_password: "{{ password }}"
516 managed_disk_type: Standard_LRS
517 image: customimage001
518
519 - name: Create a VMSS with a custom image from a particular resource group
520 azure_rm_virtualmachinescaleset:
521 resource_group: myResourceGroup
522 name: testvmss
523 vm_size: Standard_DS1_v2
524 capacity: 2
525 virtual_network_name: testvnet
526 upgrade_policy: Manual
527 subnet_name: testsubnet
528 admin_username: "{{ username }}"
529 admin_password: "{{ password }}"
530 managed_disk_type: Standard_LRS
531 image:
532 name: customimage001
533 resource_group: myResourceGroup
534
535 - name: Create a VMSS with Spot Instance
536 azure_rm_virtualmachinescaleset:
537 resource_group: myResourceGroup
538 name: testvmss
539 vm_size: Standard_DS1_v2
540 capacity: 5
541 priority: Spot
542 eviction_policy: Deallocate
543 virtual_network_name: testvnet
544 upgrade_policy: Manual
545 subnet_name: testsubnet
546 admin_username: "{{ username }}"
547 admin_password: "{{ password }}"
548 managed_disk_type: Standard_LRS
549 image: customimage001
550
551 - name: Create VMSS with security group
552 azure_rm_virtualmachinescaleset:
553 resource_group: "{{ resource_group }}"
554 name: testVMSS{{ rpfx }}
555 vm_size: Standard_D4s_v3
556 admin_username: testuser
557 single_placement_group: false
558 platform_fault_domain_count: 1
559 public_ip_per_vm: true
560 ssh_password_enabled: false
561 ssh_public_keys:
562 - path: /home/testuser/.ssh/authorized_keys
563 key_data: "ssh-rsa ****"
564 virtual_network_name: VMSStestVnet
565 subnet_name: VMSStestSubnet
566 managed_disk_type: Standard_LRS
567 orchestration_mode: Flexible
568 os_disk_caching: ReadWrite
569 security_profile:
570 uefi_settings:
571 secure_boot_enabled: true
572 v_tpm_enabled: false
573 encryption_at_host: false
574 security_type: TrustedLaunch
575 image:
576 offer: 0001-com-ubuntu-server-jammy
577 publisher: Canonical
578 sku: 22_04-lts-gen2
579 version: latest
580 data_disks:
581 - lun: 0
582 disk_size_gb: 64
583 caching: ReadWrite
584 managed_disk_type: Standard_LRS
585 '''
586
587 RETURN = '''
588 azure_vmss:
589 description:
590 - Facts about the current state of the object.
591 - Note that facts are not part of the registered output but available directly.
592 returned: always
593 type: dict
594 sample: {
595 "constrained_maximum_capacity": false,
596 "etag": "3",
597 "id": "/subscriptions/xxx-xxx/resourceGroups/v-xisuRG02/providers/Microsoft.Compute/virtualMachineScaleSets/testVMSStestvmss",
598 "location": "eastus",
599 "name": "testVMSStestvmss",
600 "orchestration_mode": "Flexible",
601 "platform_fault_domain_count": 1,
602 "provisioning_state": "Succeeded",
603 "single_placement_group": false,
604 "sku": {
605 "capacity": 1,
606 "name": "Standard_A1_v2",
607 "tier": "Standard"
608 },
609 "tags": {
610 "key2": "value2",
611 "key3": "value3"
612 },
613 "time_created": "2025-04-22T08:03:29.427822Z",
614 "type": "Microsoft.Compute/virtualMachineScaleSets",
615 "unique_id": "da4393f5-6060-4a0e-8ae5-7616316402b8",
616 "upgrade_policy": {
617 "mode": "Manual"
618 },
619 "virtual_machine_profile": {
620 "network_profile": {
621 "network_api_version": "2020-11-01",
622 "network_interface_configurations": [
623 {
624 "auxiliary_mode": "None",
625 "auxiliary_sku": "None",
626 "delete_option": "Delete",
627 "disable_tcp_state_tracking": false,
628 "dns_settings": {
629 "dns_servers": []
630 },
631 "enable_ip_forwarding": false,
632 "ip_configurations": [
633 {
634 "application_gateway_backend_address_pools": [],
635 "application_security_groups": [
636 {
637 "id": "/subscriptions/xxx-xxx/resourceGroups/v-xisuRG02/providers/Microsoft.Network/applicationSecurityGroups/apptestvmss02"
638 },
639 {
640 "id": "/subscriptions/xxx-xxx/resourceGroups/v-xisuRG02/providers/Microsoft.Network/applicationSecurityGroups/apptestvmss"
641 }
642 ],
643 "load_balancer_backend_address_pools": [],
644 "name": "default",
645 "primary": true,
646 "private_ip_address_version": "IPv4",
647 "public_ip_address_configuration": {
648 "idle_timeout_in_minutes": 4,
649 "ip_tags": [],
650 "name": "instancepublicip",
651 "public_ip_address_version": "IPv4"
652 },
653 "subnet": {
654 "id": "/subscriptions/xxx-xxx/resourceGroups/v-xisuRG02/providers/Microsoft.Network/virtualNetworks/VMSStestVnet/subnets/VMSStestSubnet"
655 }
656 }
657 ],
658 "name": "testVMSStestvmss",
659 "primary": true
660 }
661 ]
662 },
663 "os_profile": {
664 "admin_username": "testuser",
665 "allow_extension_operations": true,
666 "computer_name_prefix": "testVMSStestvmss",
667 "linux_configuration": {
668 "disable_password_authentication": true,
669 "patch_settings": {
670 "assessment_mode": "ImageDefault",
671 "patch_mode": "ImageDefault"
672 },
673 "provision_vm_agent": true,
674 "ssh": {
675 "public_keys": [
676 {
677 "key_data": "ssh-rsa xxxxxxxxxx [email protected]",
678 "path": "/home/testuser/.ssh/authorized_keys"
679 }
680 ]
681 }
682 },
683 "require_guest_provision_signal": true,
684 "secrets": []
685 },
686 "storage_profile": {
687 "data_disks": [
688 {
689 "caching": "ReadWrite",
690 "create_option": "Empty",
691 "delete_option": "Delete",
692 "disk_size_gb": 64,
693 "lun": 0,
694 "managed_disk": {
695 "storage_account_type": "Standard_LRS"
696 }
697 }
698 ],
699 "image_reference": {
700 "offer": "0001-com-ubuntu-server-focal",
701 "publisher": "Canonical",
702 "sku": "20_04-lts",
703 "version": "20.04.202504030"
704 },
705 "os_disk": {
706 "caching": "ReadWrite",
707 "create_option": "FromImage",
708 "delete_option": "Delete",
709 "disk_size_gb": 30,
710 "managed_disk": {
711 "storage_account_type": "Standard_LRS"
712 },
713 "os_type": "Linux"
714 }
715 },
716 "time_created": "2025-04-22T08:53:17.201851Z"
717 }
718 }
719 ''' # NOQA
720
721 import base64
722 import time
723
724 try:
725 from azure.core.exceptions import ResourceNotFoundError
726 from azure.mgmt.core.tools import parse_resource_id
727 from azure.core.exceptions import ResourceNotFoundError
728 from azure.mgmt.compute.models import (VirtualMachineScaleSetIdentity, UserAssignedIdentitiesValue)
729
730 except ImportError:
731 # This is handled in azure_rm_common
732 pass
733
734 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import azure_id_to_dict, format_resource_id
735 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
736 from ansible.module_utils.basic import to_native, to_bytes
737
738
739 AZURE_OBJECT_CLASS = 'VirtualMachineScaleSet'
740
741 AZURE_ENUM_MODULES = ['azure.mgmt.compute.models']
742
743
744 class AzureRMVirtualMachineScaleSet(AzureRMModuleBaseExt):
745
746 def __init__(self):
747
748 self.module_arg_spec = dict(
749 resource_group=dict(type='str', required=True),
750 name=dict(type='str', required=True),
751 state=dict(choices=['present', 'absent'], default='present', type='str'),
752 location=dict(type='str'),
753 short_hostname=dict(type='str'),
754 vm_size=dict(type='str'),
755 tier=dict(type='str', choices=['Basic', 'Standard']),
756 capacity=dict(type='int', default=1),
757 upgrade_policy=dict(type='str', choices=['Automatic', 'Manual']),
758 priority=dict(type='str', choices=['None', 'Spot', 'Regular']),
759 eviction_policy=dict(type='str', choices=['Deallocate', 'Delete']),
760 max_price=dict(type='float', default=-1),
761 admin_username=dict(type='str'),
762 admin_password=dict(type='str', no_log=True),
763 ssh_password_enabled=dict(type='bool', default=True),
764 ssh_public_keys=dict(type='list', elements='dict'),
765 image=dict(type='raw'),
766 os_disk_caching=dict(type='str', aliases=['disk_caching'], choices=['ReadOnly', 'ReadWrite'],
767 default='ReadOnly'),
768 os_type=dict(type='str', choices=['Linux', 'Windows', 'linux', 'windows'], default='Linux'),
769 managed_disk_type=dict(type='str', choices=['Standard_LRS', 'Premium_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS', 'Premium_ZRS', 'StandardSSD_ZRS']),
770 os_disk_encryption_set=dict(type='str'),
771 data_disks=dict(
772 type='list',
773 elements='dict',
774 options=dict(
775 lun=dict(type='str', default='0'),
776 disk_size_gb=dict(type='int'),
777 caching=dict(type='str', default='ReadOnly', choices=['ReadOnly', 'ReadWrite']),
778 managed_disk_type=dict(
779 type='str',
780 choices=['Standard_LRS', 'Premium_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS', 'Premium_ZRS', 'StandardSSD_ZRS']
781 ),
782 disk_encryption_set=dict(type='str')
783 )
784 ),
785 subnet_name=dict(type='str', aliases=['subnet']),
786 public_ip_per_vm=dict(type='bool', default=False),
787 load_balancer=dict(type='str'),
788 application_gateway=dict(type='str'),
789 virtual_network_resource_group=dict(type='str'),
790 virtual_network_name=dict(type='str', aliases=['virtual_network']),
791 remove_on_absent=dict(type='list', default=['all'], elements='str'),
792 enable_accelerated_networking=dict(type='bool'),
793 security_group=dict(type='raw', aliases=['security_group_name']),
794 overprovision=dict(type='bool'),
795 single_placement_group=dict(type='bool', default=False),
796 zones=dict(type='list', elements='str'),
797 custom_data=dict(type='str'),
798 plan=dict(type='dict', options=dict(publisher=dict(type='str', required=True),
799 product=dict(type='str', required=True), name=dict(type='str', required=True),
800 promotion_code=dict(type='str'))),
801 scale_in_policy=dict(type='str', choices=['Default', 'OldestVM', 'NewestVM']),
802 terminate_event_timeout_minutes=dict(type='int'),
803 ephemeral_os_disk=dict(type='bool'),
804 orchestration_mode=dict(type='str',
805 choices=['Uniform', 'Flexible'],
806 default='Flexible',),
807 platform_fault_domain_count=dict(type='int', default=1),
808 os_disk_size_gb=dict(type='int'),
809 security_profile=dict(
810 type='dict',
811 options=dict(
812 encryption_at_host=dict(type='bool'),
813 security_type=dict(type='str', choices=['TrustedLaunch']),
814 uefi_settings=dict(
815 type='dict',
816 options=dict(
817 secure_boot_enabled=dict(type='bool'),
818 v_tpm_enabled=dict(type='bool'),
819 )
820 )
821 )
822 ),
823 identity=dict(
824 type='dict',
825 options=self.managed_identity_multiple_spec
826 ),
827 application_security_groups=dict(
828 type='list',
829 elements='str'
830 ),
831 private_ip_address_version=dict(
832 type='str',
833 choices=['IPv4', 'IPv6']
834 )
835 )
836
837 self.resource_group = None
838 self.name = None
839 self.state = None
840 self.location = None
841 self.short_hostname = None
842 self.vm_size = None
843 self.capacity = None
844 self.tier = None
845 self.upgrade_policy = None
846 self.priority = None
847 self.eviction_policy = None
848 self.admin_username = None
849 self.admin_password = None
850 self.ssh_password_enabled = None
851 self.ssh_public_keys = None
852 self.image = None
853 self.os_disk_caching = None
854 self.managed_disk_type = None
855 self.os_disk_encryption_set = None
856 self.data_disks = None
857 self.os_type = None
858 self.subnet_name = None
859 self.virtual_network_resource_group = None
860 self.virtual_network_name = None
861 self.public_ip_per_vm = None
862 self.tags = None
863 self.differences = None
864 self.load_balancer = None
865 self.application_gateway = None
866 self.enable_accelerated_networking = None
867 self.security_group = None
868 self.overprovision = None
869 self.zones = None
870 self.custom_data = None
871 self.plan = None
872 self.scale_in_policy = None
873 self.terminate_event_timeout_minutes = None
874 self.ephemeral_os_disk = None
875 self.orchestration_mode = None
876 self.os_disk_size_gb = None
877 self.security_profile = None
878 self._managed_identity = None
879 self.identity = None
880 self.application_security_groups = None
881 self.private_ip_address_version = None
882
883 mutually_exclusive = [('load_balancer', 'application_gateway')]
884 self.results = dict(
885 changed=False,
886 actions=[],
887 ansible_facts=dict(azure_vmss=None)
888 )
889
890 super(AzureRMVirtualMachineScaleSet, self).__init__(
891 derived_arg_spec=self.module_arg_spec,
892 supports_check_mode=True,
893 mutually_exclusive=mutually_exclusive)
894
895 @property
896 def managed_identity(self):
897 if not self._managed_identity:
898 self._managed_identity = {"identity": VirtualMachineScaleSetIdentity,
899 "user_assigned": UserAssignedIdentitiesValue
900 }
901 return self._managed_identity
902
903 def exec_module(self, **kwargs):
904
905 for key in list(self.module_arg_spec.keys()) + ['tags']:
906 setattr(self, key, kwargs[key])
907
908 # make sure options are lower case
909 self.remove_on_absent = set([resource.lower() for resource in self.remove_on_absent])
910
911 # convert elements to ints
912 self.zones = [int(i) for i in self.zones] if self.zones else None
913
914 # default virtual_network_resource_group to resource_group
915 if not self.virtual_network_resource_group:
916 self.virtual_network_resource_group = self.resource_group
917
918 changed = False
919 results = dict()
920 vmss = None
921 disable_ssh_password = None
922 subnet = None
923 image_reference = None
924 load_balancer_backend_address_pools = None
925 load_balancer_inbound_nat_pools = None
926 load_balancer = None
927 application_gateway = None
928 application_gateway_backend_address_pools = None
929 support_lb_change = True
930 public_ip_address_configuration = None
931 application_security_groups = None
932 if self.application_security_groups is not None:
933 application_security_groups = [self.compute_models.SubResource(id=item) for item in self.application_security_groups]
934
935 resource_group = self.get_resource_group(self.resource_group)
936 if not self.location:
937 # Set default location
938 self.location = resource_group.location
939
940 if self.custom_data:
941 self.custom_data = to_native(base64.b64encode(to_bytes(self.custom_data)))
942
943 if self.state == 'present':
944 # Verify parameters and resolve any defaults
945
946 if self.vm_size and not self.vm_size_is_valid():
947 self.fail("Parameter error: vm_size {0} is not valid for your subscription and location.".format(
948 self.vm_size
949 ))
950
951 # if self.virtual_network_name:
952 # virtual_network = self.get_virtual_network(self.virtual_network_name)
953
954 if self.ssh_public_keys:
955 msg = "Parameter error: expecting ssh_public_keys to be a list of type dict where " \
956 "each dict contains keys: path, key_data."
957 for key in self.ssh_public_keys:
958 if not isinstance(key, dict):
959 self.fail(msg)
960 if not key.get('path') or not key.get('key_data'):
961 self.fail(msg)
962
963 if self.image and isinstance(self.image, dict):
964 if all(key in self.image for key in ('publisher', 'offer', 'sku', 'version')):
965 marketplace_image = self.get_marketplace_image_version()
966 if self.image['version'] == 'latest':
967 self.image['version'] = marketplace_image.name
968 self.log("Using image version {0}".format(self.image['version']))
969
970 image_reference = self.compute_models.ImageReference(
971 publisher=self.image['publisher'],
972 offer=self.image['offer'],
973 sku=self.image['sku'],
974 version=self.image['version']
975 )
976 elif self.image.get('name'):
977 custom_image = True
978 image_reference = self.get_custom_image_reference(
979 self.image.get('name'),
980 self.image.get('resource_group'))
981 elif self.image.get('id'):
982 try:
983 image_reference = self.compute_models.ImageReference(id=self.image['id'])
984 except Exception as exc:
985 self.fail("id Error: Cannot get image from the reference id - {0}".format(self.image['id']))
986 elif self.image.get('community_gallery_image_id'):
987 try:
988 image_reference = self.compute_models.ImageReference(community_gallery_image_id=self.image['community_gallery_image_id'])
989 except Exception as exc:
990 self.fail("id Error: Cannot get image from the cummunity gallery image id- {0}".format(self.image['community_gallery_image_id']))
991 else:
992 self.fail("parameter error: expecting image to contain [publisher, offer, sku, version], [name, resource_group] or [id]")
993 elif self.image and isinstance(self.image, str):
994 custom_image = True
995 image_reference = self.get_custom_image_reference(self.image)
996 elif self.image:
997 self.fail("parameter error: expecting image to be a string or dict not {0}".format(type(self.image).__name__))
998
999 disable_ssh_password = not self.ssh_password_enabled
1000
1001 if self.load_balancer:
1002 load_balancer = self.get_load_balancer(self.load_balancer)
1003 load_balancer_backend_address_pools = ([self.compute_models.SubResource(id=resource.id)
1004 for resource in load_balancer.backend_address_pools]
1005 if load_balancer.backend_address_pools else None)
1006 load_balancer_inbound_nat_pools = ([self.compute_models.SubResource(id=resource.id)
1007 for resource in load_balancer.inbound_nat_pools]
1008 if load_balancer.inbound_nat_pools else None)
1009
1010 if self.application_gateway:
1011 application_gateway = self.get_application_gateway(self.application_gateway)
1012 application_gateway_backend_address_pools = ([self.compute_models.SubResource(id=resource.id)
1013 for resource in application_gateway.backend_address_pools]
1014 if application_gateway.backend_address_pools else None)
1015
1016 if self.public_ip_per_vm:
1017 public_ip_address_configuration = self.compute_models.VirtualMachineScaleSetPublicIPAddressConfiguration(name='instancepublicip')
1018
1019 try:
1020 self.log("Fetching virtual machine scale set {0}".format(self.name))
1021 vmss = self.compute_client.virtual_machine_scale_sets.get(self.resource_group, self.name)
1022 self.check_provisioning_state(vmss, self.state)
1023 vmss_dict = self.serialize_vmss(vmss)
1024
1025 if self.state == 'present':
1026 differences = []
1027 results = vmss_dict
1028 current_osdisk = vmss_dict['virtual_machine_profile']['storage_profile']['os_disk']
1029 current_ephemeral = current_osdisk.get('diff_disk_settings', None)
1030 current_properties = vmss_dict['virtual_machine_profile']
1031
1032 if self.priority and self.priority != current_properties.get('priority', 'None'):
1033 self.fail('VM Priority is not updatable: requested virtual machine priority is {0}'.format(self.priority))
1034 if self.eviction_policy and \
1035 self.eviction_policy != current_properties.get('eviction_policy', None):
1036 self.fail('VM Eviction Policy is not updatable: requested virtual machine eviction policy is {0}'.format(self.eviction_policy))
1037 if self.max_price and \
1038 vmss_dict['virtual_machine_profile'].get('billing_profile', None) and \
1039 self.max_price != vmss_dict['virtual_machine_profile']['billing_profile'].get('max_price', None):
1040 self.fail('VM Maximum Price is not updatable: requested virtual machine maximum price is {0}'.format(self.max_price))
1041
1042 if self.ephemeral_os_disk and current_ephemeral is None:
1043 self.fail('Ephemeral OS disk not updatable: virtual machine scale set ephemeral OS disk is {0}'.format(self.ephemeral_os_disk))
1044 elif not self.ephemeral_os_disk and current_ephemeral is not None:
1045 self.fail('Ephemeral OS disk not updatable: virtual machine scale set ephemeral OS disk is {0}'.format(self.ephemeral_os_disk))
1046
1047 if self.os_disk_size_gb and \
1048 self.os_disk_size_gb != vmss_dict['virtual_machine_profile']['storage_profile']['os_disk']['disk_size_gb']:
1049 self.fail('VMSS OS disk size is not updatable: requested virtual machine OS disk size is {0}'.format(self.os_disk_size_gb))
1050
1051 if self.os_disk_caching and \
1052 self.os_disk_caching != vmss_dict['virtual_machine_profile']['storage_profile']['os_disk']['caching']:
1053 self.log('CHANGED: virtual machine scale set {0} - OS disk caching'.format(self.name))
1054 differences.append('OS Disk caching')
1055 changed = True
1056 vmss_dict['virtual_machine_profile']['storage_profile']['os_disk']['caching'] = self.os_disk_caching
1057
1058 if self.capacity and \
1059 self.capacity != vmss_dict['sku']['capacity']:
1060 self.log('CHANGED: virtual machine scale set {0} - Capacity'.format(self.name))
1061 differences.append('Capacity')
1062 changed = True
1063 vmss_dict['sku']['capacity'] = self.capacity
1064
1065 if self.vm_size and \
1066 self.vm_size != vmss_dict['sku']['name']:
1067 self.log('CHANGED: virtual machine scale set {0} - VM Size'.format(self.name))
1068 differences.append('VM Size')
1069 changed = True
1070 vmss_dict['sku']['name'] = self.vm_size
1071
1072 if self.data_disks and \
1073 len(self.data_disks) != len(vmss_dict['virtual_machine_profile']['storage_profile'].get('data_disks', [])):
1074 self.log('CHANGED: virtual machine scale set {0} - Data Disks'.format(self.name))
1075 differences.append('Data Disks')
1076 changed = True
1077
1078 if self.upgrade_policy and \
1079 self.upgrade_policy != vmss_dict['upgrade_policy']['mode']:
1080 self.log('CHANGED: virtual machine scale set {0} - Upgrade Policy'.format(self.name))
1081 differences.append('Upgrade Policy')
1082 changed = True
1083 vmss_dict['upgrade_policy']['mode'] = self.upgrade_policy
1084
1085 if image_reference and \
1086 image_reference.as_dict() != vmss_dict['virtual_machine_profile']['storage_profile']['image_reference']:
1087 self.log('CHANGED: virtual machine scale set {0} - Image'.format(self.name))
1088 differences.append('Image')
1089 changed = True
1090 vmss_dict['virtual_machine_profile']['storage_profile']['image_reference'] = image_reference.as_dict()
1091
1092 if self.identity:
1093 update_identity, self.identity = self.update_managed_identity(new_identity=self.identity, curr_identity=vmss_dict.get('identity', dict()))
1094 if update_identity:
1095 differences.append('Identity')
1096 changed = True
1097
1098 update_tags, self.tags = self.update_tags(vmss_dict.get('tags', dict()))
1099 if update_tags:
1100 differences.append('Tags')
1101 changed = True
1102
1103 if self.overprovision is not None and bool(self.overprovision) != bool(vmss_dict.get('overprovision')):
1104 differences.append('overprovision')
1105 changed = True
1106
1107 if bool(self.single_placement_group) != bool(vmss_dict['single_placement_group']):
1108 differences.append('single_placement_group')
1109 changed = True
1110
1111 vmss_dict['zones'] = [int(i) for i in vmss_dict['zones']] if 'zones' in vmss_dict and vmss_dict['zones'] else None
1112 if self.zones != vmss_dict['zones']:
1113 self.log("CHANGED: virtual machine scale sets {0} zones".format(self.name))
1114 differences.append('Zones')
1115 changed = True
1116 vmss_dict['zones'] = self.zones
1117
1118 if self.terminate_event_timeout_minutes:
1119 timeout = self.terminate_event_timeout_minutes
1120 if timeout < 5 or timeout > 15:
1121 self.fail("terminate_event_timeout_minutes should >= 5 and <= 15")
1122 iso_8601_format = "PT" + str(timeout) + "M"
1123 old = vmss_dict['virtual_machine_profile'].get('scheduled_events_profile', {}).\
1124 get('terminate_notification_profile', {}).get('not_before_timeout', "")
1125 if old != iso_8601_format:
1126 differences.append('terminateNotification')
1127 changed = True
1128 vmss_dict['virtual_machine_profile'].setdefault('scheduled_events_profile', {})['terminate_notification_profile'] = {
1129 'not_before_timeout': iso_8601_format,
1130 "enable": 'true'
1131 }
1132
1133 if self.scale_in_policy and self.scale_in_policy != vmss_dict.get('scale_in_policy', {}).get('rules', [""])[0]:
1134 self.log("CHANGED: virtual machine sale sets {0} scale in policy".format(self.name))
1135 differences.append('scaleInPolicy')
1136 changed = True
1137 vmss_dict.setdefault('scale_in_policy', {})['rules'] = [self.scale_in_policy]
1138
1139 nicConfigs = vmss_dict['virtual_machine_profile']['network_profile']['network_interface_configurations']
1140
1141 backend_address_pool = nicConfigs[0]['ip_configurations'][0].get('load_balancer_backend_address_pools', [])
1142 backend_address_pool += nicConfigs[0]['ip_configurations'][0].get('application_gateway_backend_address_pools', [])
1143 lb_or_ag_id = None
1144 if (len(nicConfigs) != 1 or len(backend_address_pool) != 1):
1145 support_lb_change = False # Currently not support for the vmss contains more than one loadbalancer
1146 self.module.warn('Updating more than one load balancer on VMSS is currently not supported')
1147 else:
1148 if load_balancer:
1149 lb_or_ag_id = "{0}/".format(load_balancer.id)
1150 elif application_gateway:
1151 lb_or_ag_id = "{0}/".format(application_gateway.id)
1152
1153 backend_address_pool_id = backend_address_pool[0].get('id')
1154 if lb_or_ag_id is not None and (bool(lb_or_ag_id) != bool(backend_address_pool_id) or not backend_address_pool_id.startswith(lb_or_ag_id)):
1155 differences.append('load_balancer')
1156 changed = True
1157
1158 if self.application_security_groups is not None:
1159 for item in nicConfigs[0]['ip_configurations'][0].get('application_security_groups', []):
1160 if item['id'] not in self.application_security_groups:
1161 self.application_security_groups.append(item['id'])
1162 if len(self.application_security_groups) != len(nicConfigs[0]['ip_configurations'][0].get('application_security_groups', [])):
1163 changed = True
1164 differences.append('application_security_groups')
1165
1166 if self.custom_data:
1167 if self.custom_data != vmss_dict['virtual_machine_profile']['os_profile'].get('custom_data'):
1168 differences.append('custom_data')
1169 changed = True
1170 vmss_dict['virtual_machine_profile']['os_profile']['custom_data'] = self.custom_data
1171
1172 if self.orchestration_mode and self.orchestration_mode != vmss_dict.get('orchestration_mode'):
1173 self.fail("The orchestration_mode parameter cannot be updated!")
1174 else:
1175 self.orchestration_mode = vmss_dict.get('orchestration_mode')
1176
1177 if self.platform_fault_domain_count and self.platform_fault_domain_count != vmss_dict.get('platform_fault_domain_count'):
1178 self.fail("The platform_fault_domain_count parameter cannot be updated!")
1179
1180 if self.security_profile is not None:
1181 update_security_profile = False
1182 if 'securityProfile' not in vmss_dict['virtual_machine_profile'].keys():
1183 update_security_profile = True
1184 differences.append('security_profile')
1185 else:
1186 if self.security_profile.get('encryption_at_host') is not None:
1187 if bool(self.security_profile.get('encryption_at_host')) != \
1188 bool(vmss_dict['virtual_machine_profile']['security_profile']['encryption_at_host']):
1189 update_security_profle = True
1190 else:
1191 self.security_profile['encryption_at_host'] = \
1192 vmss_dict['virtual_machine_profile']['security_profile']['encryption_at_host']
1193 if self.security_profile.get('security_type') is not None:
1194 if self.security_profile.get('security_type') != \
1195 vmss_dict['virtual_machine_profile']['security_profile']['security_type']:
1196 update_security_profile = True
1197 if self.security_profile.get('uefi_settings') is not None:
1198 if self.security_profile['uefi_settings'].get('secure_boot_enabled') is not None:
1199 if bool(self.security_profile['uefi_settings']['secure_boot_enabled']) != \
1200 bool(vmss_dict['virtual_machine_profile']['security_profile']['uefi_settings']['secure_boot_nabled']):
1201 update_security_profile = True
1202 else:
1203 self.security_profile['uefi_settings']['secure_boot_enabled'] = \
1204 vmss_dict['virtual_machine_profile']['security_profile']['uefi_settings']['secure_boot_enabled']
1205 if self.security_profile['uefi_settings'].get('v_tpm_enabled') is not None:
1206 if bool(self.security_profile['uefi_settings']['v_tpm_enabled']) != \
1207 bool(vmss_dict['virtual_machine_profile']['security_profile']['uefi_settings']['v_tpm_enabled']):
1208 update_security_profile = True
1209 else:
1210 self.security_profile['uefi_settings']['v_tpm_enabled'] = \
1211 vmss_dict['virtual_machine_profile']['security_profile']['uefi_settings']['v_tpm_enabled']
1212 if update_security_profile:
1213 changed = True
1214 differences.append('security_profile')
1215
1216 self.differences = differences
1217
1218 elif self.state == 'absent':
1219 self.log("CHANGED: virtual machine scale set {0} exists and requested state is 'absent'".format(self.name))
1220 results = dict()
1221 changed = True
1222
1223 except ResourceNotFoundError:
1224 self.log('Virtual machine scale set {0} does not exist'.format(self.name))
1225 if self.state == 'present':
1226 self.log("CHANGED: virtual machine scale set {0} does not exist but state is 'present'.".format(self.name))
1227 changed = True
1228 if self.identity:
1229 update_identity, self.identity = self.update_managed_identity(new_identity=self.identity)
1230
1231 self.results['changed'] = changed
1232 self.results['ansible_facts']['azure_vmss'] = results
1233
1234 if self.check_mode:
1235 return self.results
1236
1237 if changed:
1238 if self.state == 'present':
1239 if not vmss:
1240 # Create the VMSS
1241 if self.vm_size is None:
1242 self.fail("vm size must be set")
1243
1244 self.log("Create virtual machine scale set {0}".format(self.name))
1245 self.results['actions'].append('Created VMSS {0}'.format(self.name))
1246
1247 if self.os_type == 'Linux' or self.os_type == 'linux':
1248 if disable_ssh_password and not self.ssh_public_keys:
1249 self.fail("Parameter error: ssh_public_keys required when disabling SSH password.")
1250
1251 if not self.virtual_network_name:
1252 self.fail("virtual network name is required")
1253
1254 if self.subnet_name:
1255 subnet = self.get_subnet(self.virtual_network_name, self.subnet_name)
1256
1257 if not self.short_hostname:
1258 self.short_hostname = self.name
1259
1260 if not image_reference:
1261 self.fail("Parameter error: an image is required when creating a virtual machine.")
1262
1263 if self.os_disk_encryption_set:
1264 os_disk_encryption_set = self.compute_models.DiskEncryptionSetParameters(id=self.os_disk_encryption_set)
1265 managed_disk = self.compute_models.VirtualMachineScaleSetManagedDiskParameters(storage_account_type=self.managed_disk_type,
1266 disk_encryption_set=os_disk_encryption_set)
1267 else:
1268 managed_disk = self.compute_models.VirtualMachineScaleSetManagedDiskParameters(storage_account_type=self.managed_disk_type)
1269
1270 if self.security_group:
1271 nsg = self.parse_nsg()
1272 if nsg:
1273 self.security_group = self.network_models.NetworkSecurityGroup(id=nsg.get('id'))
1274
1275 plan = None
1276 if self.plan:
1277 plan = self.compute_models.Plan(name=self.plan.get('name'), product=self.plan.get('product'),
1278 publisher=self.plan.get('publisher'),
1279 promotion_code=self.plan.get('promotion_code'))
1280
1281 os_profile = None
1282 if self.admin_username or self.custom_data or self.ssh_public_keys:
1283 os_profile = self.compute_models.VirtualMachineScaleSetOSProfile(
1284 admin_username=self.admin_username,
1285 computer_name_prefix=self.short_hostname,
1286 custom_data=self.custom_data
1287 )
1288
1289 vmss_resource = self.compute_models.VirtualMachineScaleSet(
1290 location=self.location,
1291 overprovision=self.overprovision,
1292 single_placement_group=self.single_placement_group,
1293 tags=self.tags,
1294 orchestration_mode=self.orchestration_mode,
1295 platform_fault_domain_count=self.platform_fault_domain_count,
1296 upgrade_policy=self.compute_models.UpgradePolicy(
1297 mode=self.upgrade_policy
1298 ) if self.upgrade_policy is not None else None,
1299 sku=self.compute_models.Sku(
1300 name=self.vm_size,
1301 capacity=self.capacity,
1302 tier=self.tier,
1303 ),
1304 plan=plan,
1305 virtual_machine_profile=self.compute_models.VirtualMachineScaleSetVMProfile(
1306 os_profile=os_profile,
1307 # pylint: disable=missing-kwoa
1308 storage_profile=self.compute_models.VirtualMachineScaleSetStorageProfile(
1309 os_disk=self.compute_models.VirtualMachineScaleSetOSDisk(
1310 managed_disk=managed_disk,
1311 create_option=self.compute_models.DiskCreateOptionTypes.from_image,
1312 caching=self.os_disk_caching,
1313 disk_size_gb=self.os_disk_size_gb,
1314 diff_disk_settings=self.compute_models.DiffDiskSettings(option='Local') if self.ephemeral_os_disk else None,
1315 ),
1316 image_reference=image_reference,
1317 ),
1318 network_profile=self.compute_models.VirtualMachineScaleSetNetworkProfile(
1319 network_interface_configurations=[
1320 self.compute_models.VirtualMachineScaleSetNetworkConfiguration(
1321 name=self.name,
1322 primary=True,
1323 ip_configurations=[
1324 self.compute_models.VirtualMachineScaleSetIPConfiguration(
1325 name='default',
1326 subnet=self.compute_models.ApiEntityReference(
1327 id=subnet.id
1328 ),
1329 public_ip_address_configuration=public_ip_address_configuration,
1330 primary=True,
1331 load_balancer_backend_address_pools=load_balancer_backend_address_pools,
1332 load_balancer_inbound_nat_pools=load_balancer_inbound_nat_pools,
1333 application_gateway_backend_address_pools=application_gateway_backend_address_pools,
1334 application_security_groups=application_security_groups,
1335 private_ip_address_version=self.private_ip_address_version
1336 )
1337 ],
1338 enable_accelerated_networking=self.enable_accelerated_networking,
1339 network_security_group=self.security_group
1340 )
1341 ],
1342 network_api_version='2020-11-01' if self.orchestration_mode == 'Flexible' else None
1343 )
1344 ),
1345 zones=self.zones
1346 )
1347
1348 if self.identity:
1349 vmss_resource.identity = self.identity
1350
1351 if self.priority == 'Spot':
1352 vmss_resource.virtual_machine_profile.priority = self.priority
1353 vmss_resource.virtual_machine_profile.eviction_policy = self.eviction_policy
1354 vmss_resource.virtual_machine_profile.billing_profile = self.compute_models.BillingProfile(
1355 max_price=self.max_price
1356 )
1357 elif self.priority == 'Regular':
1358 vmss_resource.virtual_machine_profile.priority = self.priority
1359
1360 if self.scale_in_policy:
1361 vmss_resource.scale_in_policy = self.gen_scale_in_policy()
1362
1363 if self.terminate_event_timeout_minutes:
1364 vmss_resource.virtual_machine_profile.scheduled_events_profile = self.gen_scheduled_event_profile()
1365
1366 if self.admin_password:
1367 vmss_resource.virtual_machine_profile.os_profile.admin_password = self.admin_password
1368
1369 if (self.os_type == 'Linux' or self.os_type == 'linux') and os_profile:
1370 vmss_resource.virtual_machine_profile.os_profile.linux_configuration = self.compute_models.LinuxConfiguration(
1371 disable_password_authentication=disable_ssh_password
1372 )
1373
1374 if self.ssh_public_keys:
1375 ssh_config = self.compute_models.SshConfiguration()
1376 ssh_config.public_keys = \
1377 [self.compute_models.SshPublicKey(path=key['path'], key_data=key['key_data']) for key in self.ssh_public_keys]
1378 vmss_resource.virtual_machine_profile.os_profile.linux_configuration.ssh = ssh_config
1379
1380 if self.data_disks:
1381 data_disks = []
1382
1383 for data_disk in self.data_disks:
1384 if data_disk.get('disk_encryption_set'):
1385 data_disk_encryption_set = self.compute_models.DiskEncryptionSetParameters(id=data_disk['disk_encryption_set'])
1386 data_disk_managed_disk = self.compute_models.VirtualMachineScaleSetManagedDiskParameters(
1387 storage_account_type=data_disk.get('managed_disk_type', None),
1388 disk_encryption_set=data_disk_encryption_set
1389 )
1390 else:
1391 data_disk_managed_disk = self.compute_models.VirtualMachineScaleSetManagedDiskParameters(
1392 storage_account_type=data_disk.get('managed_disk_type', None)
1393 )
1394
1395 data_disk['caching'] = data_disk.get(
1396 'caching',
1397 self.compute_models.CachingTypes.read_only
1398 )
1399
1400 data_disks.append(self.compute_models.VirtualMachineScaleSetDataDisk(
1401 lun=data_disk.get('lun', None),
1402 caching=data_disk.get('caching', None),
1403 create_option=self.compute_models.DiskCreateOptionTypes.empty,
1404 disk_size_gb=data_disk.get('disk_size_gb', None),
1405 managed_disk=data_disk_managed_disk,
1406 ))
1407
1408 vmss_resource.virtual_machine_profile.storage_profile.data_disks = data_disks
1409
1410 if self.plan:
1411 try:
1412 plan_name = self.plan.get('name')
1413 plan_product = self.plan.get('product')
1414 plan_publisher = self.plan.get('publisher')
1415 term = self.marketplace_client.marketplace_agreements.get(
1416 offer_type='virtualmachine', publisher_id=plan_publisher, offer_id=plan_product, plan_id=plan_name)
1417 term.accepted = True
1418 self.marketplace_client.marketplace_agreements.create(
1419 offer_type='virtualmachine', publisher_id=plan_publisher, offer_id=plan_product, plan_id=plan_name, parameters=term)
1420 except Exception as exc:
1421 self.fail(("Error accepting terms for virtual machine {0} with plan {1}. " +
1422 "Only service admin/account admin users can purchase images " +
1423 "from the marketplace. - {2}").format(self.name, self.plan, str(exc)))
1424
1425 if self.security_profile is not None:
1426 uefi_settings_spec = None
1427 if self.security_profile.get('uefi_settings') is not None:
1428 uefi_settings_spec = self.compute_models.UefiSettings(
1429 secure_boot_enabled=self.security_profile['uefi_settings'].get('secure_boot_enabled'),
1430 v_tpm_enabled=self.security_profile['uefi_settings'].get('v_tpm_enabled'),
1431 )
1432 security_profile = self.compute_models.SecurityProfile(
1433 uefi_settings=uefi_settings_spec,
1434 encryption_at_host=self.security_profile.get('encryption_at_host'),
1435 security_type=self.security_profile.get('security_type'),
1436 )
1437 vmss_resource.virtual_machine_profile.security_profile = security_profile
1438
1439 self.log("Create virtual machine with parameters:")
1440 self.create_or_update_vmss(vmss_resource)
1441
1442 elif self.differences and len(self.differences) > 0:
1443 self.log("Update virtual machine scale set {0}".format(self.name))
1444 self.results['actions'].append('Updated VMSS {0}'.format(self.name))
1445
1446 vmss_resource = self.get_vmss()
1447 vmss_resource.virtual_machine_profile.storage_profile.os_disk.caching = self.os_disk_caching
1448 vmss_resource.sku.capacity = self.capacity
1449 vmss_resource.sku.name = self.vm_size
1450 vmss_resource.orchestration_mode = self.orchestration_mode
1451 vmss_resource.platform_fault_domain_count = self.platform_fault_domain_count
1452 vmss_resource.overprovision = self.overprovision
1453 vmss_resource.single_placement_group = self.single_placement_group
1454 vmss_resource.tags = self.tags
1455
1456 if support_lb_change:
1457 if self.load_balancer:
1458 vmss_resource.virtual_machine_profile.network_profile.network_interface_configurations[0] \
1459 .ip_configurations[0].load_balancer_backend_address_pools = load_balancer_backend_address_pools
1460 vmss_resource.virtual_machine_profile.network_profile.network_interface_configurations[0] \
1461 .ip_configurations[0].load_balancer_inbound_nat_pools = load_balancer_inbound_nat_pools
1462 vmss_resource.virtual_machine_profile.network_profile.network_interface_configurations[0] \
1463 .ip_configurations[0].application_gateway_backend_address_pools = None
1464 elif self.application_gateway:
1465 vmss_resource.virtual_machine_profile.network_profile.network_interface_configurations[0] \
1466 .ip_configurations[0].application_gateway_backend_address_pools = application_gateway_backend_address_pools
1467 vmss_resource.virtual_machine_profile.network_profile.network_interface_configurations[0] \
1468 .ip_configurations[0].load_balancer_backend_address_pools = None
1469 vmss_resource.virtual_machine_profile.network_profile.network_interface_configurations[0] \
1470 .ip_configurations[0].load_balancer_inbound_nat_pools = None
1471
1472 if self.application_security_groups is not None:
1473 vmss_resource.virtual_machine_profile.network_profile.network_interface_configurations[0].ip_configurations[0] \
1474 .application_security_groups = [self.compute_models.SubResource(id=item) for item in self.application_security_groups]
1475
1476 if self.data_disks is not None:
1477 data_disks = []
1478 for data_disk in self.data_disks:
1479 if data_disk.get('disk_encryption_set'):
1480 data_disk_encryption_set = self.compute_models.DiskEncryptionSetParameters(id=data_disk['disk_encryption_set'])
1481 data_disk_managed_disk = self.compute_models.VirtualMachineScaleSetManagedDiskParameters(
1482 storage_account_type=data_disk.get('managed_disk_type', None),
1483 disk_encryption_set=data_disk_encryption_set
1484 )
1485 else:
1486 data_disk_managed_disk = self.compute_models.VirtualMachineScaleSetManagedDiskParameters(
1487 storage_account_type=data_disk.get('managed_disk_type', None)
1488 )
1489 data_disks.append(self.compute_models.VirtualMachineScaleSetDataDisk(
1490 lun=data_disk['lun'],
1491 caching=data_disk['caching'],
1492 create_option=self.compute_models.DiskCreateOptionTypes.empty,
1493 disk_size_gb=data_disk['disk_size_gb'],
1494 managed_disk=data_disk_managed_disk,
1495 ))
1496 vmss_resource.virtual_machine_profile.storage_profile.data_disks = data_disks
1497
1498 if self.security_profile is not None:
1499 uefi_settings_spec = None
1500 if self.security_profile.get('uefi_settings') is not None:
1501 uefi_settings_spec = self.compute_models.UefiSettings(
1502 secure_boot_enabled=self.security_profile['uefi_settings'].get('secure_boot_enabled'),
1503 v_tpm_enabled=self.security_profile['uefi_settings'].get('v_tpm_enabled'),
1504 )
1505 security_profile = self.compute_models.SecurityProfile(
1506 uefi_settings=uefi_settings_spec,
1507 encryption_at_host=self.security_profile.get('encryption_at_host'),
1508 security_type=self.security_profile.get('security_type'),
1509 )
1510 vmss_resource.virtual_machine_profile.security_profile = security_profile
1511
1512 if self.scale_in_policy:
1513 vmss_resource.scale_in_policy = self.gen_scale_in_policy()
1514
1515 if self.terminate_event_timeout_minutes:
1516 vmss_resource.virtual_machine_profile.scheduled_events_profile = self.gen_scheduled_event_profile()
1517
1518 if self.identity:
1519 vmss_resource.identity = self.identity
1520
1521 if image_reference is not None:
1522 vmss_resource.virtual_machine_profile.storage_profile.image_reference = image_reference
1523
1524 self.log("Update virtual machine with parameters:")
1525 self.create_or_update_vmss(vmss_resource)
1526
1527 self.results['ansible_facts']['azure_vmss'] = self.serialize_vmss(self.get_vmss())
1528
1529 elif self.state == 'absent':
1530 # delete the VM
1531 self.log("Delete virtual machine scale set {0}".format(self.name))
1532 self.results['ansible_facts']['azure_vmss'] = None
1533 self.delete_vmss(vmss)
1534
1535 # until we sort out how we want to do this globally
1536 del self.results['actions']
1537
1538 return self.results
1539
1540 def get_vmss(self):
1541 '''
1542 Get the VMSS
1543
1544 :return: VirtualMachineScaleSet object
1545 '''
1546 try:
1547 retry_count = 0
1548 vmss = self.compute_client.virtual_machine_scale_sets.get(self.resource_group, self.name)
1549 while True:
1550 if retry_count == 20:
1551 self.fail("Error {0} has a provisioning state of Updating. Expecting state to be Successed.".format(self.name))
1552
1553 if vmss.provisioning_state != 'Succeeded':
1554 retry_count = retry_count + 1
1555 time.sleep(150)
1556 vmss = self.compute_client.virtual_machine_scale_sets.get(self.resource_group, self.name)
1557 else:
1558 break
1559 return vmss
1560 except ResourceNotFoundError as exc:
1561 self.fail("Error getting virtual machine scale set {0} - {1}".format(self.name, str(exc)))
1562
1563 def get_virtual_network(self, name):
1564 try:
1565 vnet = self.network_client.virtual_networks.get(self.virtual_network_resource_group, name)
1566 return vnet
1567 except ResourceNotFoundError as exc:
1568 self.fail("Error fetching virtual network {0} - {1}".format(name, str(exc)))
1569
1570 def get_subnet(self, vnet_name, subnet_name):
1571 self.log("Fetching subnet {0} in virtual network {1}".format(subnet_name, vnet_name))
1572 try:
1573 subnet = self.network_client.subnets.get(self.virtual_network_resource_group, vnet_name, subnet_name)
1574 except Exception as exc:
1575 self.fail("Error: fetching subnet {0} in virtual network {1} - {2}".format(
1576 subnet_name,
1577 vnet_name,
1578 str(exc)))
1579 return subnet
1580
1581 def get_load_balancer(self, id):
1582 id_dict = parse_resource_id(id)
1583 try:
1584 return self.network_client.load_balancers.get(id_dict.get('resource_group', self.resource_group), id_dict.get('name'))
1585 except ResourceNotFoundError as exc:
1586 self.fail("Error fetching load balancer {0} - {1}".format(id, str(exc)))
1587
1588 def get_application_gateway(self, id):
1589 id_dict = parse_resource_id(id)
1590 try:
1591 return self.network_client.application_gateways.get(id_dict.get('resource_group', self.resource_group), id_dict.get('name'))
1592 except ResourceNotFoundError as exc:
1593 self.fail("Error fetching application_gateway {0} - {1}".format(id, str(exc)))
1594
1595 def serialize_vmss(self, vmss):
1596 '''
1597 Convert a VirtualMachineScaleSet object to dict.
1598
1599 :param vm: VirtualMachineScaleSet object
1600 :return: dict
1601 '''
1602
1603 result = self.serialize_obj(vmss, AZURE_OBJECT_CLASS, enum_modules=AZURE_ENUM_MODULES)
1604 result['id'] = vmss.id
1605 result['name'] = vmss.name
1606 result['type'] = vmss.type
1607 result['location'] = vmss.location
1608 result['tags'] = vmss.tags
1609
1610 return result
1611
1612 def delete_vmss(self, vmss):
1613 self.log("Deleting virtual machine scale set {0}".format(self.name))
1614 self.results['actions'].append("Deleted virtual machine scale set {0}".format(self.name))
1615 try:
1616 poller = self.compute_client.virtual_machine_scale_sets.begin_delete(self.resource_group, self.name)
1617 # wait for the poller to finish
1618 self.get_poller_result(poller)
1619 except Exception as exc:
1620 self.fail("Error deleting virtual machine scale set {0} - {1}".format(self.name, str(exc)))
1621
1622 return True
1623
1624 def get_marketplace_image_version(self):
1625 try:
1626 versions = self.compute_client.virtual_machine_images.list(self.location,
1627 self.image['publisher'],
1628 self.image['offer'],
1629 self.image['sku'])
1630 except ResourceNotFoundError as exc:
1631 self.fail("Error fetching image {0} {1} {2} - {3}".format(self.image['publisher'],
1632 self.image['offer'],
1633 self.image['sku'],
1634 str(exc)))
1635 if versions and len(versions) > 0:
1636 if self.image['version'] == 'latest':
1637 return versions[len(versions) - 1]
1638 for version in versions:
1639 if version.name == self.image['version']:
1640 return version
1641
1642 self.fail("Error could not find image {0} {1} {2} {3}".format(self.image['publisher'],
1643 self.image['offer'],
1644 self.image['sku'],
1645 self.image['version']))
1646
1647 def get_custom_image_reference(self, name, resource_group=None):
1648 try:
1649 if resource_group:
1650 vm_images = self.compute_client.images.list_by_resource_group(resource_group)
1651 else:
1652 vm_images = self.compute_client.images.list()
1653 except ResourceNotFoundError as exc:
1654 self.fail("Error fetching custom images from subscription - {0}".format(str(exc)))
1655
1656 for vm_image in vm_images:
1657 if vm_image.name == name:
1658 self.log("Using custom image id {0}".format(vm_image.id))
1659 return self.compute_models.ImageReference(id=vm_image.id)
1660
1661 self.fail("Error could not find image with name {0}".format(name))
1662
1663 def create_or_update_vmss(self, params):
1664 try:
1665 poller = self.compute_client.virtual_machine_scale_sets.begin_create_or_update(self.resource_group, self.name, params)
1666 self.get_poller_result(poller)
1667 except Exception as exc:
1668 self.fail("Error creating or updating virtual machine {0} - {1}".format(self.name, str(exc)))
1669
1670 def vm_size_is_valid(self):
1671 '''
1672 Validate self.vm_size against the list of virtual machine sizes available for the account and location.
1673
1674 :return: boolean
1675 '''
1676 try:
1677 sizes = self.compute_client.virtual_machine_sizes.list(self.location)
1678 except ResourceNotFoundError as exc:
1679 self.fail("Error retrieving available machine sizes - {0}".format(str(exc)))
1680 for size in sizes:
1681 if size.name == self.vm_size:
1682 return True
1683 return False
1684
1685 def parse_nsg(self):
1686 nsg = self.security_group
1687 resource_group = self.resource_group
1688 if isinstance(self.security_group, dict):
1689 nsg = self.security_group.get('name')
1690 resource_group = self.security_group.get('resource_group', self.resource_group)
1691 id = format_resource_id(val=nsg,
1692 subscription_id=self.subscription_id,
1693 namespace='Microsoft.Network',
1694 types='networkSecurityGroups',
1695 resource_group=resource_group)
1696 name = azure_id_to_dict(id).get('name')
1697 return dict(id=id, name=name)
1698
1699 def gen_scheduled_event_profile(self):
1700 if self.terminate_event_timeout_minutes is None:
1701 return None
1702
1703 scheduledEventProfile = self.compute_models.ScheduledEventsProfile()
1704 terminationProfile = self.compute_models.TerminateNotificationProfile()
1705 terminationProfile.not_before_timeout = "PT" + str(self.terminate_event_timeout_minutes) + "M"
1706 terminationProfile.enable = True
1707 scheduledEventProfile.terminate_notification_profile = terminationProfile
1708 return scheduledEventProfile
1709
1710 def gen_scale_in_policy(self):
1711 if self.scale_in_policy is None:
1712 return None
1713
1714 return self.compute_models.ScaleInPolicy(rules=[self.scale_in_policy])
1715
1716
1717 def main():
1718 AzureRMVirtualMachineScaleSet()
1719
1720
1721 if __name__ == '__main__':
1722 main()