forked from ansible-collections/azure
-
Notifications
You must be signed in to change notification settings - Fork 1
/
azure_rm_virtualmachinescaleset.py
1557 lines (1409 loc) · 71.2 KB
/
azure_rm_virtualmachinescaleset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
#
# Copyright (c) 2016 Sertac Ozercan, <seozerca@microsoft.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: azure_rm_virtualmachinescaleset
version_added: "0.1.2"
short_description: Manage Azure virtual machine scale sets
description:
- Create and update a virtual machine scale set.
- Note that this module was called M(azure.azcollection.azure_rm_virtualmachine_scaleset) before Ansible 2.8. The usage did not change.
options:
resource_group:
description:
- Name of the resource group containing the virtual machine scale set.
required: true
type: str
name:
description:
- Name of the virtual machine.
required: true
type: str
state:
description:
- Assert the state of the virtual machine scale set.
- State C(present) will check that the machine exists with the requested configuration. If the configuration
of the existing machine does not match, the machine will be updated.
- State C(absent) will remove the virtual machine scale set.
default: present
type: str
choices:
- absent
- present
location:
description:
- Valid Azure location. Defaults to location of the resource group.
type: str
short_hostname:
description:
- Short host name.
type: str
vm_size:
description:
- A valid Azure VM size value. For example, C(Standard_D4).
- The list of choices varies depending on the subscription and location. Check your subscription for available choices.
type: str
capacity:
description:
- Capacity of VMSS.
default: 1
type: int
tier:
description:
- SKU Tier.
type: str
choices:
- Basic
- Standard
upgrade_policy:
description:
- Upgrade policy.
- Required when creating the Azure virtual machine scale sets.
type: str
choices:
- Manual
- Automatic
priority:
description:
- Priority of the VMSS.
- C(None) is the equivalent of Regular VM.
type: str
choices:
- None
- Spot
eviction_policy:
description:
- Specifies the eviction policy for the Azure Spot virtual machine.
- Requires priority to be set to Spot.
type: str
choices:
- Deallocate
- Delete
max_price:
description:
- Specifies the maximum price you are willing to pay for a Azure Spot VM/VMSS.
- This price is in US Dollars.
- C(-1) indicates default price to be up-to on-demand.
- Requires priority to be set to Spot.
default: -1
type: float
admin_username:
description:
- Admin username used to access the host after it is created. Required when creating a VM.
type: str
admin_password:
description:
- Password for the admin username.
- Not required if the os_type is Linux and SSH password authentication is disabled by setting I(ssh_password_enabled=false).
type: str
ssh_password_enabled:
description:
- When the os_type is Linux, setting I(ssh_password_enabled=false) will disable SSH password authentication and require use of SSH keys.
type: bool
default: true
ssh_public_keys:
description:
- For I(os_type=Linux) provide a list of SSH keys.
- Each item in the list should be a dictionary where the dictionary contains two keys, C(path) and C(key_data).
- Set the C(path) to the default location of the authorized_keys files.
- On an Enterprise Linux host, for example, the I(path=/home/<admin username>/.ssh/authorized_keys).
Set C(key_data) to the actual value of the public key.
type: list
elements: dict
image:
description:
- Specifies the image used to build the VM.
- If a string, the image is sourced from a custom image based on the name.
- If a dict with the keys I(publisher), I(offer), I(sku), and I(version), the image is sourced from a Marketplace image.
Note that set I(version=latest) to get the most recent version of a given image.
- 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.
Note that the key I(resource_group) is optional and if omitted, all images in the subscription will be searched for by I(name).
- Custom image support was added in Ansible 2.5.
- Required when creating.
type: raw
os_disk_caching:
description:
- Type of OS disk caching.
type: str
choices:
- ReadOnly
- ReadWrite
default: ReadOnly
aliases:
- disk_caching
os_disk_size_gb:
description:
- Specifies the size of the operating system disk in gigabytes.
- This can be used to overwrite the size of the disk in a virtual machine image.
type: int
os_type:
description:
- Base type of operating system.
type: str
choices:
- Windows
- Linux
default: Linux
ephemeral_os_disk:
description:
- Parameters of ephemeral disk settings that can be specified for operating system disk.
- Ephemeral OS disk is only supported for VMS Instances using Managed Disk.
type: bool
managed_disk_type:
description:
- Managed disk type.
type: str
choices:
- Standard_LRS
- Premium_LRS
- StandardSSD_LRS
- UltraSSD_LRS
- Premium_ZRS
- StandardSSD_ZRS
data_disks:
description:
- Describes list of data disks.
type: list
elements: dict
suboptions:
lun:
description:
- The logical unit number for data disk.
default: '0'
type: str
disk_size_gb:
description:
- The initial disk size in GB for blank data disks.
type: int
managed_disk_type:
description:
- Managed data disk type.
type: str
choices:
- Standard_LRS
- Premium_LRS
- StandardSSD_LRS
- UltraSSD_LRS
- Premium_ZRS
- StandardSSD_ZRS
caching:
description:
- Type of data disk caching.
type: str
choices:
- ReadOnly
- ReadWrite
default: ReadOnly
virtual_network_resource_group:
description:
- When creating a virtual machine, if a specific virtual network from another resource group should be
used.
- Use this parameter to specify the resource group to use.
type: str
virtual_network_name:
description:
- Virtual Network name.
aliases:
- virtual_network
type: str
subnet_name:
description:
- Subnet name.
type: str
aliases:
- subnet
public_ip_per_vm:
description:
- Assign a public IP to each virtual machine of the scale set
type: bool
default: False
load_balancer:
description:
- Load balancer name.
type: str
application_gateway:
description:
- Application gateway name.
type: str
remove_on_absent:
description:
- When removing a VM using I(state=absent), also remove associated resources.
- It can be C(all) or a list with any of the following ['network_interfaces', 'virtual_storage', 'public_ips'].
- Any other input will be ignored.
type: list
elements: str
default: ['all']
enable_accelerated_networking:
description:
- Indicates whether user wants to allow accelerated networking for virtual machines in scaleset being created.
type: bool
security_group:
description:
- Existing security group with which to associate the subnet.
- It can be the security group name which is in the same resource group.
- It can be the resource ID.
- It can be a dict which contains I(name) and I(resource_group) of the security group.
aliases:
- security_group_name
type: raw
overprovision:
description:
- Specifies whether the Virtual Machine Scale Set should be overprovisioned.
type: bool
single_placement_group:
description:
- When true this limits the scale set to a single placement group, of max size 100 virtual machines.
type: bool
default: False
plan:
description:
- Third-party billing plan for the VM.
type: dict
suboptions:
name:
description:
- Billing plan name.
required: true
type: str
product:
description:
- Product name.
required: true
type: str
publisher:
description:
- Publisher offering the plan.
required: true
type: str
promotion_code:
description:
- Optional promotion code.
type: str
zones:
description:
- A list of Availability Zones for your virtual machine scale set.
type: list
elements: str
custom_data:
description:
- Data which is made available to the virtual machine and used by e.g., C(cloud-init).
- Many images in the marketplace are not cloud-init ready. Thus, data sent to I(custom_data) would be ignored.
- If the image you are attempting to use is not listed in
U(https://docs.microsoft.com/en-us/azure/virtual-machines/linux/using-cloud-init#cloud-init-overview),
follow these steps U(https://docs.microsoft.com/en-us/azure/virtual-machines/linux/cloudinit-prepare-custom-image).
type: str
scale_in_policy:
description:
- define the order in which vmss instances are scaled-in
type: str
choices:
- Default
- NewestVM
- OldestVM
terminate_event_timeout_minutes:
description:
- timeout time for termination notification event
- in range between 5 and 15
type: int
platform_fault_domain_count:
description:
- Fault Domain count for each placement group.
type: int
default: 1
orchestration_mode:
description:
- Specifies the orchestration mode for the virtual machine scale set.
- When I(orchestration_mode=Flexible), I(public_ip_per_vm=True) must be set.
- When I(orchestration_mode=Flexible), I(platform_fault_domain_count) must be set.
- When I(orchestration_mode=Flexible), I(single_placement_group=False) must be set.
- When I(orchestration_mode=Flexible), it cannot be configured I(overprovision).
- When I(orchestration_mode=Flexible), it cannot be configured I(upgrade_policy) and configured when I(orchestration_mode=Uniform).
type: str
choices:
- Flexible
- Uniform
default: Flexible
security_profile:
description:
- Specifies the Security related profile settings for the virtual machine sclaset.
type: dict
suboptions:
encryption_at_host:
description:
- This property can be used by user in the request to enable or disable the Host Encryption for the virtual machine sclaset.
- This will enable the encryption for all the disks including Resource/Temp disk at host itself.
type: bool
security_type:
description:
- Specifies the SecurityType of the virtual machine sclaset.
- It is set as TrustedLaunch to enable UefiSettings.
type: str
choices:
- TrustedLaunch
uefi_settings:
description:
- Specifies the security settings like secure boot and vTPM used while creating the virtual machine scalset.
type: dict
suboptions:
secure_boot_enabled:
description:
- Specifies whether secure boot should be enabled on the virtual machine sclaset.
type: bool
v_tpm_enabled:
description:
- Specifies whether vTPM should be enabled on the virtual machine scalset.
type: bool
extends_documentation_fragment:
- azure.azcollection.azure
- azure.azcollection.azure_tags
author:
- Sertac Ozercan (@sozercan)
'''
EXAMPLES = '''
- name: Create VMSS
azure_rm_virtualmachinescaleset:
resource_group: myResourceGroup
name: testvmss
vm_size: Standard_DS1_v2
capacity: 2
virtual_network_name: testvnet
upgrade_policy: Manual
subnet_name: testsubnet
terminate_event_timeout_minutes: 10
scale_in_policy: NewestVM
admin_username: "{{ username }}"
ssh_password_enabled: false
ssh_public_keys:
- path: /home/adminUser/.ssh/authorized_keys
key_data: < insert your ssh public key here... >
managed_disk_type: Standard_LRS
image:
offer: 0001-com-ubuntu-server-focal
publisher: canonical
sku: 20_04-lts-gen2
version: latest
data_disks:
- lun: 0
disk_size_gb: 64
caching: ReadWrite
managed_disk_type: Standard_LRS
- name: Create VMSS with an image that requires plan information
azure_rm_virtualmachinescaleset:
resource_group: myResourceGroup
name: testvmss
vm_size: Standard_DS1_v2
capacity: 3
virtual_network_name: testvnet
upgrade_policy: Manual
subnet_name: testsubnet
admin_username: "{{ username }}"
ssh_password_enabled: false
ssh_public_keys:
- path: /home/adminUser/.ssh/authorized_keys
key_data: < insert your ssh public key here... >
managed_disk_type: Standard_LRS
image:
offer: cis-ubuntu-linux-1804-l1
publisher: center-for-internet-security-inc
sku: Stable
version: latest
plan:
name: cis-ubuntu-linux-1804-l1
product: cis-ubuntu-linux-1804-l1
publisher: center-for-internet-security-inc
data_disks:
- lun: 0
disk_size_gb: 64
caching: ReadWrite
managed_disk_type: Standard_LRS
- name: Create a VMSS with a custom image
azure_rm_virtualmachinescaleset:
resource_group: myResourceGroup
name: testvmss
vm_size: Standard_DS1_v2
capacity: 2
virtual_network_name: testvnet
upgrade_policy: Manual
subnet_name: testsubnet
admin_username: "{{ username }}"
admin_password: "{{ password }}"
managed_disk_type: Standard_LRS
image: customimage001
- name: Create a VMSS with over 100 instances
azure_rm_virtualmachinescaleset:
resource_group: myResourceGroup
name: testvmss
vm_size: Standard_DS1_v2
capacity: 120
single_placement_group: false
virtual_network_name: testvnet
upgrade_policy: Manual
subnet_name: testsubnet
admin_username: "{{ username }}"
admin_password: "{{ password }}"
managed_disk_type: Standard_LRS
image: customimage001
- name: Create a VMSS with a custom image from a particular resource group
azure_rm_virtualmachinescaleset:
resource_group: myResourceGroup
name: testvmss
vm_size: Standard_DS1_v2
capacity: 2
virtual_network_name: testvnet
upgrade_policy: Manual
subnet_name: testsubnet
admin_username: "{{ username }}"
admin_password: "{{ password }}"
managed_disk_type: Standard_LRS
image:
name: customimage001
resource_group: myResourceGroup
- name: Create a VMSS with Spot Instance
azure_rm_virtualmachinescaleset:
resource_group: myResourceGroup
name: testvmss
vm_size: Standard_DS1_v2
capacity: 5
priority: Spot
eviction_policy: Deallocate
virtual_network_name: testvnet
upgrade_policy: Manual
subnet_name: testsubnet
admin_username: "{{ username }}"
admin_password: "{{ password }}"
managed_disk_type: Standard_LRS
image: customimage001
- name: Create VMSS with security group
azure_rm_virtualmachinescaleset:
resource_group: "{{ resource_group }}"
name: testVMSS{{ rpfx }}
vm_size: Standard_D4s_v3
admin_username: testuser
single_placement_group: false
platform_fault_domain_count: 1
public_ip_per_vm: true
ssh_password_enabled: false
ssh_public_keys:
- path: /home/testuser/.ssh/authorized_keys
key_data: "ssh-rsa ****"
virtual_network_name: VMSStestVnet
subnet_name: VMSStestSubnet
managed_disk_type: Standard_LRS
orchestration_mode: Flexible
os_disk_caching: ReadWrite
security_profile:
uefi_settings:
secure_boot_enabled: true
v_tpm_enabled: false
encryption_at_host: false
security_type: TrustedLaunch
image:
offer: 0001-com-ubuntu-server-jammy
publisher: Canonical
sku: 22_04-lts-gen2
version: latest
data_disks:
- lun: 0
disk_size_gb: 64
caching: ReadWrite
managed_disk_type: Standard_LRS
'''
RETURN = '''
azure_vmss:
description:
- Facts about the current state of the object.
- Note that facts are not part of the registered output but available directly.
returned: always
type: dict
sample: {
"properties": {
"overprovision": true,
"platformFaultDomainCount": 1,
"orchestrationMode": "Flexible",
"scaleInPolicy": {
"rules": [
"NewestVM"
]
},
"singlePlacementGroup": true,
"upgradePolicy": {
"mode": "Manual"
},
"virtualMachineProfile": {
"networkProfile": {
"networkInterfaceConfigurations": [
{
"name": "testvmss",
"properties": {
"dnsSettings": {
"dnsServers": []
},
"enableAcceleratedNetworking": false,
"ipConfigurations": [
{
"name": "default",
"properties": {
"privateIPAddressVersion": "IPv4",
"subnet": {
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/virtualNetworks/testvnet/subnets/testsubnet"
}
}
}
],
"primary": true
}
}
]
},
"osProfile": {
"adminUsername": "testuser",
"computerNamePrefix": "testvmss",
"linuxConfiguration": {
"disablePasswordAuthentication": true,
"ssh": {
"publicKeys": [
{
"keyData": "",
"path": "/home/testuser/.ssh/authorized_keys"
}
]
}
},
"secrets": []
},
"scheduledEventsProfile": {
"terminateNotificationProfile": {
"enable": true,
"notBeforeTimeout": "PT10M"
}
},
"storageProfile": {
"dataDisks": [
{
"caching": "ReadWrite",
"createOption": "empty",
"diskSizeGB": 64,
"lun": 0,
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
}
],
"imageReference": {
"offer": "0001-com-ubuntu-server-focal",
"publisher": "canonical",
"sku": "20_04-lts-gen2",
"version": "20.04.202111210"
},
"securityProfile": {
"encryptionAtHost": false,
"securityType": "TrustedLaunch",
"uefiSettings": {
"secureBootEnabled": true,
"vTpmEnabled": false
}
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "fromImage",
"managedDisk": {
"storageAccountType": "Standard_LRS"
}
}
}
}
},
"sku": {
"capacity": 2,
"name": "Standard_DS1_v2",
"tier": "Standard"
},
"tags": null,
"type": "Microsoft.Compute/virtualMachineScaleSets"
}
''' # NOQA
import base64
import time
try:
from azure.core.exceptions import ResourceNotFoundError
from azure.mgmt.core.tools import parse_resource_id
from azure.core.exceptions import ResourceNotFoundError
except ImportError:
# This is handled in azure_rm_common
pass
from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase, azure_id_to_dict, format_resource_id
from ansible.module_utils.basic import to_native, to_bytes
AZURE_OBJECT_CLASS = 'VirtualMachineScaleSet'
AZURE_ENUM_MODULES = ['azure.mgmt.compute.models']
class AzureRMVirtualMachineScaleSet(AzureRMModuleBase):
def __init__(self):
self.module_arg_spec = dict(
resource_group=dict(type='str', required=True),
name=dict(type='str', required=True),
state=dict(choices=['present', 'absent'], default='present', type='str'),
location=dict(type='str'),
short_hostname=dict(type='str'),
vm_size=dict(type='str'),
tier=dict(type='str', choices=['Basic', 'Standard']),
capacity=dict(type='int', default=1),
upgrade_policy=dict(type='str', choices=['Automatic', 'Manual']),
priority=dict(type='str', choices=['None', 'Spot']),
eviction_policy=dict(type='str', choices=['Deallocate', 'Delete']),
max_price=dict(type='float', default=-1),
admin_username=dict(type='str'),
admin_password=dict(type='str', no_log=True),
ssh_password_enabled=dict(type='bool', default=True),
ssh_public_keys=dict(type='list', elements='dict'),
image=dict(type='raw'),
os_disk_caching=dict(type='str', aliases=['disk_caching'], choices=['ReadOnly', 'ReadWrite'],
default='ReadOnly'),
os_type=dict(type='str', choices=['Linux', 'Windows'], default='Linux'),
managed_disk_type=dict(type='str', choices=['Standard_LRS', 'Premium_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS', 'Premium_ZRS', 'StandardSSD_ZRS']),
data_disks=dict(
type='list',
elements='dict',
options=dict(
lun=dict(type='str', default='0'),
disk_size_gb=dict(type='int'),
caching=dict(type='str', default='ReadOnly', choices=['ReadOnly', 'ReadWrite']),
managed_disk_type=dict(
type='str',
choices=['Standard_LRS', 'Premium_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS', 'Premium_ZRS', 'StandardSSD_ZRS']
)
)
),
subnet_name=dict(type='str', aliases=['subnet']),
public_ip_per_vm=dict(type='bool', default=False),
load_balancer=dict(type='str'),
application_gateway=dict(type='str'),
virtual_network_resource_group=dict(type='str'),
virtual_network_name=dict(type='str', aliases=['virtual_network']),
remove_on_absent=dict(type='list', default=['all'], elements='str'),
enable_accelerated_networking=dict(type='bool'),
security_group=dict(type='raw', aliases=['security_group_name']),
overprovision=dict(type='bool'),
single_placement_group=dict(type='bool', default=False),
zones=dict(type='list', elements='str'),
custom_data=dict(type='str'),
plan=dict(type='dict', options=dict(publisher=dict(type='str', required=True),
product=dict(type='str', required=True), name=dict(type='str', required=True),
promotion_code=dict(type='str'))),
scale_in_policy=dict(type='str', choices=['Default', 'OldestVM', 'NewestVM']),
terminate_event_timeout_minutes=dict(type='int'),
ephemeral_os_disk=dict(type='bool'),
orchestration_mode=dict(type='str',
choices=['Uniform', 'Flexible'],
default='Flexible',),
platform_fault_domain_count=dict(type='int', default=1),
os_disk_size_gb=dict(type='int'),
security_profile=dict(
type='dict',
options=dict(
encryption_at_host=dict(type='bool'),
security_type=dict(type='str', choices=['TrustedLaunch']),
uefi_settings=dict(
type='dict',
options=dict(
secure_boot_enabled=dict(type='bool'),
v_tpm_enabled=dict(type='bool'),
)
)
)
),
)
self.resource_group = None
self.name = None
self.state = None
self.location = None
self.short_hostname = None
self.vm_size = None
self.capacity = None
self.tier = None
self.upgrade_policy = None
self.priority = None
self.eviction_policy = None
self.admin_username = None
self.admin_password = None
self.ssh_password_enabled = None
self.ssh_public_keys = None
self.image = None
self.os_disk_caching = None
self.managed_disk_type = None
self.data_disks = None
self.os_type = None
self.subnet_name = None
self.virtual_network_resource_group = None
self.virtual_network_name = None
self.public_ip_per_vm = None
self.tags = None
self.differences = None
self.load_balancer = None
self.application_gateway = None
self.enable_accelerated_networking = None
self.security_group = None
self.overprovision = None
self.zones = None
self.custom_data = None
self.plan = None
self.scale_in_policy = None
self.terminate_event_timeout_minutes = None
self.ephemeral_os_disk = None
self.orchestration_mode = None
self.os_disk_size_gb = None
self.security_profile = None
mutually_exclusive = [('load_balancer', 'application_gateway')]
self.results = dict(
changed=False,
actions=[],
ansible_facts=dict(azure_vmss=None)
)
super(AzureRMVirtualMachineScaleSet, self).__init__(
derived_arg_spec=self.module_arg_spec,
supports_check_mode=True,
mutually_exclusive=mutually_exclusive)
def exec_module(self, **kwargs):
for key in list(self.module_arg_spec.keys()) + ['tags']:
setattr(self, key, kwargs[key])
if self.module._name == 'azure_rm_virtualmachine_scaleset':
self.module.deprecate("The 'azure_rm_virtualmachine_scaleset' module has been renamed to 'azure_rm_virtualmachinescaleset'", version=(2, 9))
# make sure options are lower case
self.remove_on_absent = set([resource.lower() for resource in self.remove_on_absent])
# convert elements to ints
self.zones = [int(i) for i in self.zones] if self.zones else None
# default virtual_network_resource_group to resource_group
if not self.virtual_network_resource_group:
self.virtual_network_resource_group = self.resource_group
changed = False
results = dict()
vmss = None
disable_ssh_password = None
subnet = None
image_reference = None
load_balancer_backend_address_pools = None
load_balancer_inbound_nat_pools = None
load_balancer = None
application_gateway = None
application_gateway_backend_address_pools = None
support_lb_change = True
public_ip_address_configuration = None
resource_group = self.get_resource_group(self.resource_group)
if not self.location:
# Set default location
self.location = resource_group.location
if self.custom_data:
self.custom_data = to_native(base64.b64encode(to_bytes(self.custom_data)))
if self.state == 'present':
# Verify parameters and resolve any defaults
if self.vm_size and not self.vm_size_is_valid():
self.fail("Parameter error: vm_size {0} is not valid for your subscription and location.".format(
self.vm_size
))
# if self.virtual_network_name:
# virtual_network = self.get_virtual_network(self.virtual_network_name)
if self.ssh_public_keys:
msg = "Parameter error: expecting ssh_public_keys to be a list of type dict where " \
"each dict contains keys: path, key_data."
for key in self.ssh_public_keys:
if not isinstance(key, dict):
self.fail(msg)
if not key.get('path') or not key.get('key_data'):
self.fail(msg)
if self.image and isinstance(self.image, dict):
if all(key in self.image for key in ('publisher', 'offer', 'sku', 'version')):
marketplace_image = self.get_marketplace_image_version()
if self.image['version'] == 'latest':
self.image['version'] = marketplace_image.name
self.log("Using image version {0}".format(self.image['version']))
image_reference = self.compute_models.ImageReference(
publisher=self.image['publisher'],
offer=self.image['offer'],
sku=self.image['sku'],
version=self.image['version']
)
elif self.image.get('name'):
custom_image = True
image_reference = self.get_custom_image_reference(
self.image.get('name'),
self.image.get('resource_group'))
elif self.image.get('id'):
try:
image_reference = self.compute_models.ImageReference(id=self.image['id'])
except Exception as exc:
self.fail("id Error: Cannot get image from the reference id - {0}".format(self.image['id']))
else:
self.fail("parameter error: expecting image to contain [publisher, offer, sku, version], [name, resource_group] or [id]")
elif self.image and isinstance(self.image, str):
custom_image = True
image_reference = self.get_custom_image_reference(self.image)
elif self.image:
self.fail("parameter error: expecting image to be a string or dict not {0}".format(type(self.image).__name__))
disable_ssh_password = not self.ssh_password_enabled
if self.load_balancer:
load_balancer = self.get_load_balancer(self.load_balancer)
load_balancer_backend_address_pools = ([self.compute_models.SubResource(id=resource.id)
for resource in load_balancer.backend_address_pools]
if load_balancer.backend_address_pools else None)
load_balancer_inbound_nat_pools = ([self.compute_models.SubResource(id=resource.id)
for resource in load_balancer.inbound_nat_pools]
if load_balancer.inbound_nat_pools else None)
if self.application_gateway:
application_gateway = self.get_application_gateway(self.application_gateway)
application_gateway_backend_address_pools = ([self.compute_models.SubResource(id=resource.id)
for resource in application_gateway.backend_address_pools]
if application_gateway.backend_address_pools else None)
if self.public_ip_per_vm:
public_ip_address_configuration = self.compute_models.VirtualMachineScaleSetPublicIPAddressConfiguration(name='instancepublicip')
try:
self.log("Fetching virtual machine scale set {0}".format(self.name))
vmss = self.compute_client.virtual_machine_scale_sets.get(self.resource_group, self.name)
self.check_provisioning_state(vmss, self.state)
vmss_dict = self.serialize_vmss(vmss)
if self.state == 'present':
differences = []
results = vmss_dict
current_osdisk = vmss_dict['virtual_machine_profile']['storage_profile']['os_disk']
current_ephemeral = current_osdisk.get('diff_disk_settings', None)
current_properties = vmss_dict['virtual_machine_profile']
if self.priority and self.priority != current_properties.get('priority', 'None'):
self.fail('VM Priority is not updatable: requested virtual machine priority is {0}'.format(self.priority))
if self.eviction_policy and \
self.eviction_policy != current_properties.get('eviction_policy', None):
self.fail('VM Eviction Policy is not updatable: requested virtual machine eviction policy is {0}'.format(self.eviction_policy))
if self.max_price and \
vmss_dict['virtual_machine_profile'].get('billing_profile', None) and \
self.max_price != vmss_dict['virtual_machine_profile']['billing_profile'].get('max_price', None):
self.fail('VM Maximum Price is not updatable: requested virtual machine maximum price is {0}'.format(self.max_price))
if self.ephemeral_os_disk and current_ephemeral is None:
self.fail('Ephemeral OS disk not updatable: virtual machine scale set ephemeral OS disk is {0}'.format(self.ephemeral_os_disk))
elif not self.ephemeral_os_disk and current_ephemeral is not None:
self.fail('Ephemeral OS disk not updatable: virtual machine scale set ephemeral OS disk is {0}'.format(self.ephemeral_os_disk))
if self.os_disk_size_gb and \
self.os_disk_size_gb != vmss_dict['virtual_machine_profile']['storage_profile']['os_disk']['disk_size_gb']:
self.fail('VMSS OS disk size is not updatable: requested virtual machine OS disk size is {0}'.format(self.os_disk_size_gb))
if self.os_disk_caching and \
self.os_disk_caching != vmss_dict['virtual_machine_profile']['storage_profile']['os_disk']['caching']:
self.log('CHANGED: virtual machine scale set {0} - OS disk caching'.format(self.name))
differences.append('OS Disk caching')
changed = True
vmss_dict['virtual_machine_profile']['storage_profile']['os_disk']['caching'] = self.os_disk_caching
if self.capacity and \
self.capacity != vmss_dict['sku']['capacity']:
self.log('CHANGED: virtual machine scale set {0} - Capacity'.format(self.name))
differences.append('Capacity')
changed = True
vmss_dict['sku']['capacity'] = self.capacity
if self.data_disks and \
len(self.data_disks) != len(vmss_dict['virtual_machine_profile']['storage_profile'].get('data_disks', [])):
self.log('CHANGED: virtual machine scale set {0} - Data Disks'.format(self.name))
differences.append('Data Disks')
changed = True
if self.upgrade_policy and \
self.upgrade_policy != vmss_dict['upgrade_policy']['mode']:
self.log('CHANGED: virtual machine scale set {0} - Upgrade Policy'.format(self.name))
differences.append('Upgrade Policy')
changed = True
vmss_dict['upgrade_policy']['mode'] = self.upgrade_policy
if image_reference and \
image_reference.as_dict() != vmss_dict['virtual_machine_profile']['storage_profile']['image_reference']:
self.log('CHANGED: virtual machine scale set {0} - Image'.format(self.name))
differences.append('Image')
changed = True
vmss_dict['virtual_machine_profile']['storage_profile']['image_reference'] = image_reference.as_dict()
update_tags, vmss_dict['tags'] = self.update_tags(vmss_dict.get('tags', dict()))
if update_tags:
differences.append('Tags')
changed = True
if self.overprovision is not None and bool(self.overprovision) != bool(vmss_dict.get('overprovision')):
differences.append('overprovision')
changed = True
if bool(self.single_placement_group) != bool(vmss_dict['single_placement_group']):
differences.append('single_placement_group')
changed = True
vmss_dict['zones'] = [int(i) for i in vmss_dict['zones']] if 'zones' in vmss_dict and vmss_dict['zones'] else None
if self.zones != vmss_dict['zones']:
self.log("CHANGED: virtual machine scale sets {0} zones".format(self.name))
differences.append('Zones')
changed = True
vmss_dict['zones'] = self.zones
if self.terminate_event_timeout_minutes:
timeout = self.terminate_event_timeout_minutes