forked from saltstack/salt
/
azurearm.py
1841 lines (1572 loc) · 59 KB
/
azurearm.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
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
.. versionadded:: 2016.11.0
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure>`_ >= 2.0rc5
* `Microsoft Azure Storage SDK for Python <https://pypi.python.org/pypi/azure-storage>`_ >= 0.32
* `Microsoft Azure CLI <https://pypi.python.org/pypi/azure-cli>` >= 2.0.12
:configuration:
Required provider parameters:
if using username and password:
* ``subscription_id``
* ``username``
* ``password``
if using a service principal:
* ``subscription_id``
* ``tenant``
* ``client_id``
* ``secret``
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config with username and password:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
username: larry
password: 123pass
Or my-azure-config with service principal:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF
client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF
secret: XXXXXXXXXXXXXXXXXXXXXXXX
The Service Principal can be created with the new Azure CLI (https://github.com/Azure/azure-cli) with:
az ad sp create-for-rbac -n "http://<yourappname>" --role <role> --scopes <scope>
For example, this creates a service principal with 'owner' role for the whole subscription:
az ad sp create-for-rbac -n "http://mysaltapp" --role owner --scopes /subscriptions/3287abc8-f98a-c678-3bde-326766fd3617
*Note: review the details of Service Principals. Owner role is more than you normally need, and you can restrict scope to a resource group or individual resources.
'''
# pylint: disable=E0102
# pylint: disable=wrong-import-position,wrong-import-order
from __future__ import absolute_import, print_function, unicode_literals
import os
import os.path
import time
import logging
import pprint
import base64
import collections
import pkgutil
import salt.cache
import salt.config as config
import salt.utils.cloud
import salt.utils.data
import salt.utils.files
import salt.utils.stringutils
import salt.utils.yaml
from salt.ext import six
import salt.version
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout,
)
from salt.ext.six.moves import filter
# Import 3rd-party libs
HAS_LIBS = False
try:
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
from azure.common.credentials import (
UserPassCredentials,
ServicePrincipalCredentials,
)
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.compute.models import (
CachingTypes,
DataDisk,
DiskCreateOptionTypes,
HardwareProfile,
ImageReference,
NetworkInterfaceReference,
NetworkProfile,
OSDisk,
OSProfile,
StorageProfile,
SubResource,
VirtualHardDisk,
VirtualMachine,
VirtualMachineSizeTypes,
)
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.network.models import (
IPAllocationMethod,
NetworkInterface,
NetworkInterfaceDnsSettings,
NetworkInterfaceIPConfiguration,
NetworkSecurityGroup,
PublicIPAddress,
SecurityRule,
)
from azure.mgmt.resource.resources import ResourceManagementClient
from azure.mgmt.storage import StorageManagementClient
from azure.mgmt.web import WebSiteManagementClient
from msrestazure.azure_exceptions import CloudError
if pkgutil.find_loader('azure.multiapi'):
# use multiapi version if available
from azure.multiapi.storage.v2016_05_31 import CloudStorageAccount
else:
from azure.storage import CloudStorageAccount
HAS_LIBS = True
except ImportError:
pass
# pylint: enable=wrong-import-position,wrong-import-order
__virtualname__ = 'azurearm'
# pylint: disable=invalid-name
cache = None
storconn = None
compconn = None
netconn = None
webconn = None
resconn = None
# pylint: enable=invalid-name
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return (
False,
'The following dependencies are required to use the AzureARM driver: '
'Microsoft Azure SDK for Python >= 2.0rc5, '
'Microsoft Azure Storage SDK for Python >= 0.32'
)
global cache # pylint: disable=global-statement,invalid-name
cache = salt.cache.Cache(__opts__)
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
provider = config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'tenant', 'client_id', 'secret')
)
if provider is False:
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'username', 'password')
)
else:
return provider
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azurearm': HAS_LIBS}
)
def get_conn(Client=None):
'''
Return a conn object for the passed VM data
'''
if Client is None:
Client = ComputeManagementClient
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
tenant = config.get_cloud_config_value(
'tenant',
get_configured_provider(), __opts__, search_global=False
)
if tenant is not None:
client_id = config.get_cloud_config_value(
'client_id',
get_configured_provider(), __opts__, search_global=False
)
secret = config.get_cloud_config_value(
'secret',
get_configured_provider(), __opts__, search_global=False
)
credentials = ServicePrincipalCredentials(client_id, secret, tenant=tenant)
else:
username = config.get_cloud_config_value(
'username',
get_configured_provider(), __opts__, search_global=False
)
password = config.get_cloud_config_value(
'password',
get_configured_provider(), __opts__, search_global=False
)
credentials = UserPassCredentials(username, password)
client = Client(
credentials=credentials,
subscription_id=subscription_id,
)
client.config.add_user_agent('SaltCloud/{0}'.format(salt.version.__version__))
return client
def get_location():
'''
Return the location that is configured for this provider
'''
return config.get_cloud_config_value(
'location',
get_configured_provider(), __opts__, search_global=False
)
def avail_locations(conn=None, call=None): # pylint: disable=unused-argument
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
global webconn # pylint: disable=global-statement,invalid-name
if not webconn:
webconn = get_conn(WebSiteManagementClient)
ret = {}
regions = webconn.global_model.get_subscription_geo_regions()
if hasattr(regions, 'value'):
regions = regions.value
for location in regions: # pylint: disable=no-member
lowername = six.text_type(location.name).lower().replace(' ', '')
ret[lowername] = object_to_dict(location)
return ret
def avail_images(conn=None, call=None): # pylint: disable=unused-argument
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
global compconn # pylint: disable=global-statement,invalid-name
if not compconn:
compconn = get_conn()
region = get_location()
bank = 'cloud/metadata/azurearm/{0}'.format(region)
publishers = cache.cache(
bank,
'publishers',
compconn.virtual_machine_images.list_publishers,
loop_fun=object_to_dict,
expire=config.get_cloud_config_value(
'expire_publisher_cache', get_configured_provider(),
__opts__, search_global=False, default=604800, # 7 days
),
location=region,
)
ret = {}
for publisher in publishers:
pub_bank = os.path.join(bank, 'publishers', publisher['name'])
offers = cache.cache(
pub_bank,
'offers',
compconn.virtual_machine_images.list_offers,
loop_fun=object_to_dict,
expire=config.get_cloud_config_value(
'expire_offer_cache', get_configured_provider(),
__opts__, search_global=False, default=518400, # 6 days
),
location=region,
publisher_name=publisher['name'],
)
for offer in offers:
offer_bank = os.path.join(pub_bank, 'offers', offer['name'])
skus = cache.cache(
offer_bank,
'skus',
compconn.virtual_machine_images.list_skus,
loop_fun=object_to_dict,
expire=config.get_cloud_config_value(
'expire_sku_cache', get_configured_provider(),
__opts__, search_global=False, default=432000, # 5 days
),
location=region,
publisher_name=publisher['name'],
offer=offer['name'],
)
for sku in skus:
sku_bank = os.path.join(offer_bank, 'skus', sku['name'])
results = cache.cache(
sku_bank,
'results',
compconn.virtual_machine_images.list,
loop_fun=object_to_dict,
expire=config.get_cloud_config_value(
'expire_version_cache', get_configured_provider(),
__opts__, search_global=False, default=345600, # 4 days
),
location=region,
publisher_name=publisher['name'],
offer=offer['name'],
skus=sku['name'],
)
for version in results:
name = '|'.join((
publisher['name'],
offer['name'],
sku['name'],
version['name'],
))
ret[name] = {
'publisher': publisher['name'],
'offer': offer['name'],
'sku': sku['name'],
'version': version['name'],
}
return ret
def avail_sizes(call=None): # pylint: disable=unused-argument
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
global compconn # pylint: disable=global-statement,invalid-name
if not compconn:
compconn = get_conn()
ret = {}
location = get_location()
sizes = compconn.virtual_machine_sizes.list(location)
for size in sizes:
ret[size.name] = object_to_dict(size)
return ret
def list_nodes(conn=None, call=None): # pylint: disable=unused-argument
'''
List VMs on this Azure Active Provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
global compconn # pylint: disable=global-statement,invalid-name
if not compconn:
compconn = get_conn()
nodes = list_nodes_full(compconn, call)
active_resource_group = None
try:
provider, driver = __active_provider_name__.split(':')
active_resource_group = __opts__['providers'][provider][driver]['resource_group']
except KeyError:
pass
for node in nodes:
if active_resource_group is not None:
if nodes[node]['resource_group'] != active_resource_group:
continue
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None): # pylint: disable=unused-argument
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
global compconn # pylint: disable=global-statement,invalid-name
if not compconn:
compconn = get_conn()
ret = {}
for group in list_resource_groups():
nodes = compconn.virtual_machines.list(group)
for node in nodes:
private_ips, public_ips = __get_ips_from_node(group, node)
ret[node.name] = object_to_dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.hardware_profile.vm_size
ret[node.name]['state'] = node.provisioning_state
ret[node.name]['private_ips'] = private_ips
ret[node.name]['public_ips'] = public_ips
ret[node.name]['storage_profile']['data_disks'] = []
ret[node.name]['resource_group'] = group
for disk in node.storage_profile.data_disks:
ret[node.name]['storage_profile']['data_disks'].append(make_safe(disk))
try:
ret[node.name]['image'] = '|'.join((
ret[node.name]['storage_profile']['image_reference']['publisher'],
ret[node.name]['storage_profile']['image_reference']['offer'],
ret[node.name]['storage_profile']['image_reference']['sku'],
ret[node.name]['storage_profile']['image_reference']['version'],
))
except TypeError:
try:
ret[node.name]['image'] = ret[node.name]['storage_profile']['os_disk']['image']['uri']
except TypeError:
ret[node.name]['image'] = None
return ret
def __get_ips_from_node(resource_group, node):
'''
List private and public IPs from a VM interface
'''
global netconn # pylint: disable=global-statement,invalid-name
if not netconn:
netconn = get_conn(NetworkManagementClient)
private_ips = []
public_ips = []
for node_iface in node.network_profile.network_interfaces:
node_iface_name = node_iface.id.split('/')[-1]
network_interface = netconn.network_interfaces.get(resource_group, node_iface_name)
for ip_configuration in network_interface.ip_configurations:
if ip_configuration.private_ip_address:
private_ips.append(ip_configuration.private_ip_address)
if ip_configuration.public_ip_address and ip_configuration.public_ip_address.id:
public_iface_name = ip_configuration.public_ip_address.id.split('/')[-1]
public_iface = netconn.public_ip_addresses.get(resource_group, public_iface_name)
public_ips.append(public_iface.ip_address)
return private_ips, public_ips
def list_resource_groups(conn=None, call=None): # pylint: disable=unused-argument
'''
List resource groups associated with the account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
global resconn # pylint: disable=global-statement,invalid-name
if not resconn:
resconn = get_conn(ResourceManagementClient)
ret = {}
region = get_location()
bank = 'cloud/metadata/azurearm/{0}'.format(region)
groups = cache.cache(
bank,
'resource_groups',
resconn.resource_groups.list,
loop_fun=object_to_dict,
expire=config.get_cloud_config_value(
'expire_group_cache', get_configured_provider(),
__opts__, search_global=False, default=14400,
)
)
for group in groups:
ret[group['name']] = group
return ret
def list_nodes_select(conn=None, call=None): # pylint: disable=unused-argument
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, resource_group=None, call=None): # pylint: disable=unused-argument
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
global compconn # pylint: disable=global-statement,invalid-name
if not compconn:
compconn = get_conn()
data = None
if resource_group is None:
for group in list_resource_groups():
try:
instance = compconn.virtual_machines.get(group, name)
data = object_to_dict(instance)
resource_group = group
except CloudError:
continue
# Find under which cloud service the name is listed, if any
if data is None:
return {}
ifaces = {}
if 'network_profile' not in data:
data['network_profile'] = {}
if 'network_interfaces' not in data['network_profile']:
data['network_profile']['network_interfaces'] = []
for iface in data['network_profile']['network_interfaces']:
iface_name = iface.id.split('/')[-1]
iface_data = show_interface(kwargs={
'resource_group': resource_group,
'iface_name': iface_name,
'name': name,
})
ifaces[iface_name] = iface_data
data['network_profile']['network_interfaces'] = ifaces
data['resource_group'] = resource_group
__utils__['cloud.cache_node'](
salt.utils.data.simple_types_filter(data),
__active_provider_name__,
__opts__
)
return data
def list_networks(call=None, kwargs=None): # pylint: disable=unused-argument
'''
List virtual networks
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
global netconn # pylint: disable=global-statement,invalid-name
if not netconn:
netconn = get_conn(NetworkManagementClient)
region = get_location()
bank = 'cloud/metadata/azurearm/{0}/virtual_networks'.format(region)
if kwargs is None:
kwargs = {}
if 'group' in kwargs:
groups = [kwargs['group']]
else:
groups = list_resource_groups()
ret = {}
for group in groups:
try:
networks = cache.cache(
bank,
group,
netconn.virtual_networks.list,
loop_fun=make_safe,
expire=config.get_cloud_config_value(
'expire_network_cache', get_configured_provider(),
__opts__, search_global=False, default=3600,
),
resource_group_name=group,
)
except CloudError:
networks = {}
for vnet in networks:
ret[vnet['name']] = make_safe(vnet)
ret[vnet['name']]['subnets'] = list_subnets(
kwargs={'group': group, 'network': vnet['name']}
)
return ret
def list_subnets(call=None, kwargs=None): # pylint: disable=unused-argument
'''
List subnets in a virtual network
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
global netconn # pylint: disable=global-statement,invalid-name
if not netconn:
netconn = get_conn(NetworkManagementClient)
if 'group' in kwargs and 'resource_group' not in kwargs:
kwargs['resource_group'] = kwargs['group']
if 'resource_group' not in kwargs:
raise SaltCloudSystemExit(
'A resource_group must be specified as "group" or "resource_group"'
)
if 'network' not in kwargs:
raise SaltCloudSystemExit(
'A "network" must be specified'
)
region = get_location()
bank = 'cloud/metadata/azurearm/{0}/{1}'.format(region, kwargs['network'])
ret = {}
subnets = netconn.subnets.list(kwargs['resource_group'], kwargs['network'])
for subnet in subnets:
ret[subnet.name] = make_safe(subnet)
ret[subnet.name]['ip_configurations'] = {}
if subnet.ip_configurations:
for ip_ in subnet.ip_configurations:
comps = ip_.id.split('/')
name = comps[-1]
ret[subnet.name]['ip_configurations'][name] = make_safe(ip_)
ret[subnet.name]['ip_configurations'][name]['subnet'] = subnet.name
ret[subnet.name]['resource_group'] = kwargs['resource_group']
return ret
def delete_interface(call=None, kwargs=None): # pylint: disable=unused-argument
'''
Create a network interface
'''
global netconn # pylint: disable=global-statement,invalid-name
if not netconn:
netconn = get_conn(NetworkManagementClient)
if kwargs.get('resource_group') is None:
kwargs['resource_group'] = config.get_cloud_config_value(
'resource_group', {}, __opts__, search_global=True
)
ips = []
iface = netconn.network_interfaces.get(
kwargs['resource_group'],
kwargs['iface_name'],
)
iface_name = iface.name
for ip_ in iface.ip_configurations:
ips.append(ip_.name)
poller = netconn.network_interfaces.delete(
kwargs['resource_group'],
kwargs['iface_name'],
)
poller.wait()
for ip_ in ips:
poller = netconn.public_ip_addresses.delete(kwargs['resource_group'], ip_)
poller.wait()
return {iface_name: ips}
def delete_ip(call=None, kwargs=None): # pylint: disable=unused-argument
'''
Create a network interface
'''
global netconn # pylint: disable=global-statement,invalid-name
if not netconn:
netconn = get_conn(NetworkManagementClient)
if kwargs.get('resource_group') is None:
kwargs['resource_group'] = config.get_cloud_config_value(
'resource_group', {}, __opts__, search_global=True
)
return netconn.public_ip_addresses.delete(
kwargs['resource_group'],
kwargs['ip_name'],
)
def show_interface(call=None, kwargs=None): # pylint: disable=unused-argument
'''
Create a network interface
'''
global netconn # pylint: disable=global-statement,invalid-name
if not netconn:
netconn = get_conn(NetworkManagementClient)
if kwargs is None:
kwargs = {}
if kwargs.get('group'):
kwargs['resource_group'] = kwargs['group']
if kwargs.get('resource_group') is None:
kwargs['resource_group'] = config.get_cloud_config_value(
'resource_group', {}, __opts__, search_global=True
)
iface_name = kwargs.get('iface_name', kwargs.get('name'))
iface = netconn.network_interfaces.get(
kwargs['resource_group'],
iface_name,
)
data = object_to_dict(iface)
data['resource_group'] = kwargs['resource_group']
data['ip_configurations'] = {}
for ip_ in iface.ip_configurations:
data['ip_configurations'][ip_.name] = make_safe(ip_)
if ip_.public_ip_address is not None:
try:
pubip = netconn.public_ip_addresses.get(
kwargs['resource_group'],
ip_.name,
)
data['ip_configurations'][ip_.name]['public_ip_address']['ip_address'] = pubip.ip_address
except Exception as exc:
log.warning('There was a %s cloud error: %s', type(exc), exc)
continue
return data
def list_ip_configurations(call=None, kwargs=None): # pylint: disable=unused-argument
'''
List IP configurations
'''
global netconn # pylint: disable=global-statement,invalid-name
if not netconn:
netconn = get_conn(NetworkManagementClient)
if kwargs is None:
kwargs = {}
if 'group' not in kwargs:
if 'resource_group' in kwargs:
kwargs['group'] = kwargs['resource_group']
else:
raise SaltCloudSystemExit(
'A resource_group must be specified as "group" or "resource_group"'
)
ip_conf = {}
for ip_ in kwargs.get('ip_configurations', []):
ip_data = object_to_dict(ip_)
ip_conf[ip_data['name']] = ip_data
try:
pub_ip = netconn.public_ip_addresses.get( # pylint: disable=no-member
kwargs['resource_group'], ip_data['name']
).ip_address
ip_conf[ip_data['name']]['public_ip_address'] = pub_ip
except CloudError:
# There is no public IP on this interface
pass
return ip_conf
def list_interfaces(call=None, kwargs=None): # pylint: disable=unused-argument
'''
Create a network interface
'''
global netconn # pylint: disable=global-statement,invalid-name
if not netconn:
netconn = get_conn(NetworkManagementClient)
if kwargs is None:
kwargs = {}
if kwargs.get('resource_group') is None:
kwargs['resource_group'] = kwargs.get('group')
if kwargs['resource_group'] is None:
kwargs['resource_group'] = config.get_cloud_config_value(
'resource_group', {}, __opts__, search_global=True,
default=config.get_cloud_config_value(
'group', {}, __opts__, search_global=True
)
)
region = get_location()
bank = 'cloud/metadata/azurearm/{0}'.format(region)
interfaces = cache.cache(
bank,
'network_interfaces',
netconn.network_interfaces.list,
loop_fun=make_safe,
expire=config.get_cloud_config_value(
'expire_interface_cache', get_configured_provider(),
__opts__, search_global=False, default=3600,
),
resource_group_name=kwargs['resource_group']
)
ret = {}
for interface in interfaces:
ret[interface['name']] = interface
return ret
def create_interface(call=None, kwargs=None): # pylint: disable=unused-argument
'''
Create a network interface
'''
global netconn # pylint: disable=global-statement,invalid-name
if not netconn:
netconn = get_conn(NetworkManagementClient)
if kwargs is None:
kwargs = {}
vm_ = kwargs
if kwargs.get('location') is None:
kwargs['location'] = get_location()
if kwargs.get('network') is None:
kwargs['network'] = config.get_cloud_config_value(
'network', vm_, __opts__, search_global=True
)
if kwargs.get('subnet') is None:
kwargs['subnet'] = config.get_cloud_config_value(
'subnet', vm_, __opts__, default='default', search_global=True
)
if kwargs.get('iface_name') is None:
kwargs['iface_name'] = '{0}-iface0'.format(vm_['name'])
backend_pools = None
if kwargs.get('load_balancer') and kwargs.get('backend_pool'):
load_balancer_obj = netconn.load_balancers.get(
resource_group_name=kwargs['network_resource_group'],
load_balancer_name=kwargs['load_balancer'],
)
backend_pools = list(filter(
lambda backend: backend.name == kwargs['backend_pool'],
load_balancer_obj.backend_address_pools,
))
subnet_obj = netconn.subnets.get(
resource_group_name=kwargs['network_resource_group'],
virtual_network_name=kwargs['network'],
subnet_name=kwargs['subnet'],
)
ip_kwargs = {}
ip_configurations = None
if 'private_ip_address' in kwargs.keys():
ip_kwargs['private_ip_address'] = kwargs['private_ip_address']
ip_kwargs['private_ip_allocation_method'] = IPAllocationMethod.static
else:
ip_kwargs['private_ip_allocation_method'] = IPAllocationMethod.dynamic
if bool(kwargs.get('public_ip')) is True:
pub_ip_name = '{0}-ip'.format(kwargs['iface_name'])
poller = netconn.public_ip_addresses.create_or_update(
resource_group_name=kwargs['resource_group'],
public_ip_address_name=pub_ip_name,
parameters=PublicIPAddress(
location=kwargs['location'],
public_ip_allocation_method=IPAllocationMethod.static,
),
)
count = 0
poller.wait()
while True:
try:
pub_ip_data = netconn.public_ip_addresses.get(
kwargs['resource_group'],
pub_ip_name,
)
if pub_ip_data.ip_address: # pylint: disable=no-member
ip_kwargs['public_ip_address'] = PublicIPAddress(
id=six.text_type(pub_ip_data.id), # pylint: disable=no-member
)
ip_configurations = [
NetworkInterfaceIPConfiguration(
name='{0}-ip'.format(kwargs['iface_name']),
load_balancer_backend_address_pools=backend_pools,
subnet=subnet_obj,
**ip_kwargs
)
]
break
except CloudError as exc:
log.error('There was a cloud error: %s', exc)
count += 1
if count > 120:
raise ValueError('Timed out waiting for public IP Address.')
time.sleep(5)
else:
priv_ip_name = '{0}-ip'.format(kwargs['iface_name'])
ip_configurations = [
NetworkInterfaceIPConfiguration(
name='{0}-ip'.format(kwargs['iface_name']),
load_balancer_backend_address_pools=backend_pools,
subnet=subnet_obj,
**ip_kwargs
)
]
dns_settings = None
if kwargs.get('dns_servers') is not None:
if isinstance(kwargs['dns_servers'], list):
dns_settings = NetworkInterfaceDnsSettings(
dns_servers=kwargs['dns_servers'],
applied_dns_servers=kwargs['dns_servers'],
internal_dns_name_label=None,
internal_fqdn=None,
internal_domain_name_suffix=None,
)
network_security_group = None
if kwargs.get('security_group') is not None:
network_security_group = netconn.network_security_groups.get(
resource_group_name=kwargs['resource_group'],
network_security_group_name=kwargs['security_group'],
)
iface_params = NetworkInterface(
location=kwargs['location'],
network_security_group=network_security_group,
ip_configurations=ip_configurations,
dns_settings=dns_settings,
)
poller = netconn.network_interfaces.create_or_update(
kwargs['resource_group'], kwargs['iface_name'], iface_params
)
poller.wait()
count = 0
while True:
try:
return show_interface(kwargs=kwargs)
except CloudError:
count += 1
if count > 120:
raise ValueError('Timed out waiting for operation to complete.')
time.sleep(5)
def request_instance(call=None, kwargs=None): # pylint: disable=unused-argument
'''