-
Notifications
You must be signed in to change notification settings - Fork 1
/
cloud-harness.py
executable file
·6122 lines (5386 loc) · 339 KB
/
cloud-harness.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/env python
'''
Version: 0.2
Author: Anton Belodedenko ([email protected])
Date: 16/06/2015
Name: Cloud Harness
Git: https://github.com/ab77/cloud-harness
Synopsis:
Python wrapper for cloud service provider APIs/SDKs, supporting:
- Azure Service Management Module
Requires:
- [Requests: HTTP for Humans](http://docs.python-requests.org/en/latest/)
- [Python module that makes working with XML feel like you are working with JSON](https://github.com/martinblech/xmltodict)
- [Microsoft Azure Python SDK/API](https://github.com/Azure/azure-sdk-for-python)
- [Python interface to the OpenSSL library](https://github.com/pyca/pyopenssl)
- [PyCrypto - The Python Cryptography Toolkit](https://www.dlitz.net/software/pycrypto/)
'''
import time, sys, os, argparse, logging, json, pprint, ConfigParser, hashlib, string, inspect, traceback, uuid
from datetime import date, timedelta, datetime
from calendar import timegm
from random import sample, randint
from xml.etree.ElementTree import Element, SubElement, tostring, fromstring
from base64 import b64encode
from urlparse import urlsplit, urlunsplit, parse_qs
from urllib import quote_plus
from functools import wraps
from zipfile import ZipFile, ZIP_DEFLATED
from StringIO import StringIO
try:
import requests
except ImportError:
sys.stderr.write('ERROR: Python module "requests" not found, please run "pip install requests".\n')
sys.exit(1)
try:
from azure import *
from azure.servicemanagement import *
from azure.common import *
from azure.servicemanagement import *
from azure.storage import AccessPolicy
from azure.storage.blob import BlobService
from azure.storage.sharedaccesssignature import SharedAccessPolicy, SharedAccessSignature
except ImportError:
sys.stderr.write('ERROR: Python module "azure" not found, please run "pip install azure".\n')
sys.exit(1)
try:
import xmltodict
except ImportError:
sys.stderr.write('ERROR: Python module "xmltodict" not found, please run "pip install xmltodict".\n')
sys.exit()
try:
import OpenSSL.crypto as pyopenssl
except ImportError:
sys.stderr.write('ERROR: Python module "pyOpenSSL" not found, please run "pip install pyopenssl".\n')
sys.exit()
try:
from Crypto.Util import asn1
from Crypto.PublicKey import RSA
except ImportError:
sys.stderr.write('ERROR: Python module "PyCrypto" not found, please run "pip install pycrypto".\n')
sys.exit()
try:
import yaml
except ImportError:
sys.stderr.write('ERROR: Python module "PyYAML" not found, please run "pip install pyyaml".\n')
sys.exit()
def mkdate(dt, format):
return datetime.strftime(dt, format)
def recurse_dict(d):
for k, v in d.iteritems():
if isinstance(v, dict):
return recurse_dict(v)
else:
return v
DEFAULT_TRIES = 3
DEFAULT_DELAY = 2
DEFAULT_BACKOFF = 2
def retry(ExceptionToCheck, tries=DEFAULT_TRIES, delay=DEFAULT_DELAY, backoff=DEFAULT_BACKOFF, cdata=None):
"""Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
:param ExceptionToCheck: the exception to check. may be a tuple of
exceptions to check
:type ExceptionToCheck: Exception or tuple
:param tries: number of times to try (not retry) before giving up
:type tries: int
:param delay: initial delay between retries in seconds
:type delay: int
:param backoff: backoff multiplier e.g. value of 2 will double the delay
each retry
:type backoff: int
:param logger: logger to use. If None, print
:type logger: logging.Logger instance
"""
def deco_retry(f):
@wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
while mtries > 0:
try:
return f(*args, **kwargs)
except ExceptionToCheck, e:
logger(message='%s, retrying in %d seconds (mtries=%d): %s' % (repr(e), mdelay, mtries, str(cdata)))
time.sleep(mdelay)
mtries -= 1
mdelay *= backoff
return f(*args, **kwargs)
return f_retry # true decorator
return deco_retry
def args():
parser = argparse.ArgumentParser()
sp = parser.add_subparsers()
azure = sp.add_parser('azure')
azure.add_argument('provider', action='store_const', const='azure', help=argparse.SUPPRESS)
azure.add_argument('--action', type=str, required=False, default=AzureCloudClass.default_action, choices=[a['action'] for a in AzureCloudClass.actions], help='action (default: %s)' % AzureCloudClass.default_action)
azure.add_argument('--subscription_id', type=str, required=False, default=AzureCloudClass.default_subscription_id, help='Azure subscription ID (default: %s)' % AzureCloudClass.default_subscription_id)
azure.add_argument('--management_certificate', type=str, required=False, default=AzureCloudClass.default_management_certificate, help='Azure management certificate (default: %s)' % AzureCloudClass.default_management_certificate)
azure.add_argument('--start_date', type=str, default=mkdate(AzureCloudClass.default_start_date, '%Y-%m-%d'), help='start date for list_subscription_operations (default: %s)' % mkdate(AzureCloudClass.default_start_date, '%Y-%m-%d'))
azure.add_argument('--end_date', type=str, default=mkdate(AzureCloudClass.default_end_date, '%Y-%m-%d'), help='end date for subscription_operations (default: %s)' % mkdate(AzureCloudClass.default_end_date, '%Y-%m-%d'))
azure.add_argument('--service', type=str, required=False, help='hosted service name')
azure.add_argument('--account', type=str, required=False, default=BaseCloudHarnessClass.default_storage_account, help='storage account name (default: %s)' % BaseCloudHarnessClass.default_storage_account)
azure.add_argument('--account_type', type=str, required=False, default=AzureCloudClass.default_account_type, choices=['Standard_LRS', 'Standard_ZRS', 'Standard_GRS', 'Standard_RAGRS'], help='storage account type (default %s)' % AzureCloudClass.default_account_type)
azure.add_argument('--key_type', type=str, required=False, default=AzureCloudClass.default_key_type, choices=['Primary', 'Secondary'], help='storage account key type (default %s)' % AzureCloudClass.default_key_type)
azure.add_argument('--container', type=str, required=False, default=BaseCloudHarnessClass.default_storage_container, help='storage container name (default: %s)' % BaseCloudHarnessClass.default_storage_container)
azure.add_argument('--label', type=str, required=False, help='resource label')
azure.add_argument('--description', type=str, required=False, help='resource description')
azure.add_argument('--name', type=str, nargs='+', required=False, help='resource name(s)')
azure.add_argument('--group', type=str, required=False, help='resource group')
azure.add_argument('--service_principal_id', type=str, required=False, help='service principal object ID')
azure.add_argument('--role_definition_id', type=str, required=False, help='role definition ID')
azure.add_argument('--namespace', type=str, required=False, default=AzureCloudClass.default_namespace, help='namespace (defualt: %s)' % AzureCloudClass.default_namespace)
azure.add_argument('--type', type=str, required=False, default=AzureCloudClass.default_type, help='resource type (defualt: %s)' % AzureCloudClass.default_type)
azure.add_argument('--dns', type=str, nargs='+', required=False, help='dns server name(s)')
azure.add_argument('--ipaddr', type=str, nargs='+', required=False, help='reserved IP address name or DNS server IP address(es)')
azure.add_argument('--blob', type=str, nargs='+', required=False, help='disk image blob name(s)')
azure.add_argument('--blobtype', type=str, required=False, default=AzureCloudClass.default_blobtype, choices=['block', 'page'], help='blob type (defualt: %s)' % AzureCloudClass.default_blobtype)
azure.add_argument('--family', type=str, required=False, help='OS image family')
azure.add_argument('--disk', type=str, required=False, help='disk name')
azure.add_argument('--delete_vhds', action='store_true', required=False, help='delete VHDs')
azure.add_argument('--delete_disks', action='store_true', required=False, help='delete disks')
azure.add_argument('--async', action='store_true', required=False, help='asynchronous operation')
azure.add_argument('--thumbprint', type=str, required=False, help='certificate thumbprint')
azure.add_argument('--certificate', type=str, required=False, help='certificate file')
azure.add_argument('--publish_settings', type=str, required=False, help='Azure publish_settings file')
azure.add_argument('--request_id', type=str, required=False, help='request ID')
azure.add_argument('--status', type=str, required=False, default=AzureCloudClass.default_status, choices=['Succeeded', 'InProgress', 'Failed'], help='wait for operation status (default %s)' % AzureCloudClass.default_status)
azure.add_argument('--post_capture_action', type=str, required=False, default=AzureCloudClass.default_post_capture_action, choices=['Delete', 'Reprovision'], help='post capture action (default %s)' % AzureCloudClass.default_post_capture_action)
azure.add_argument('--wait', type=int, required=False, default=AzureCloudClass.default_wait, help='operation wait time (default %i)' % AzureCloudClass.default_wait)
azure.add_argument('--timeout', type=int, required=False, default=AzureCloudClass.default_timeout, help='operation timeout (default %i)' % AzureCloudClass.default_timeout)
azure.add_argument('--deployment', type=str, required=False, help='(source) deployment name')
azure.add_argument('--upgrade_domain', type=int, required=False, help='upgrade_domain')
azure.add_argument('--production_deployment', type=str, required=False, help='production deployment name')
azure.add_argument('--package_url', type=str, required=False, help='service package URL')
azure.add_argument('--package_config', type=str, required=False, help='service package configuration file')
azure.add_argument('--deployment_status', type=str, required=False, choices=['Running', 'Suspended'], help='deployment status')
azure.add_argument('--mode', type=str, required=False, default=AzureCloudClass.default_mode, choices=['auto', 'manual'], help='deployment rollback mode (default %s)' % AzureCloudClass.default_mode)
azure.add_argument('--force', action='store_true', required=False, help='accept data loss during deployment rollback')
azure.add_argument('--slot', type=str, required=False, default=AzureCloudClass.default_deployment_slot, help='deployment slot (default %s)' % AzureCloudClass.default_deployment_slot)
azure.add_argument('--size', type=str, required=False, default=AzureCloudClass.default_size, help='VM size (default %s)' % AzureCloudClass.default_size)
azure.add_argument('--disk_size', type=int, required=False, default=AzureCloudClass.default_disk_size, help='disk size in GB (default %s)' % AzureCloudClass.default_disk_size)
azure.add_argument('--host_caching', type=str, required=False, default=AzureCloudClass.default_host_caching, choices=['ReadOnly', 'None', 'ReadOnly', 'ReadWrite'], help='disk caching (default %s)' % AzureCloudClass.default_host_caching)
azure.add_argument('--username', type=str, required=False, default=AzureCloudClass.default_user_name, help='username for VM deployments (default %s)' % AzureCloudClass.default_user_name)
azure.add_argument('--password', type=str, required=False, help='password for VM deployments')
azure.add_argument('--pwd_expiry', type=int, required=False, default=AzureCloudClass.default_pwd_expiry, help='VMAccess password expiry (default: %i days)' % AzureCloudClass.default_pwd_expiry)
azure.add_argument('--disable_pwd_auth', action='store_true', required=False, help='disable Linux password authentication')
azure.add_argument('--ssh_auth', action='store_true', required=False, help='Linux SSH key authentication')
azure.add_argument('--readonly', action='store_true', required=False, help='limit to read-only operations')
azure.add_argument('--verbose', action='store_true', required=False, help='verbose output')
azure.add_argument('--custom_data_file', type=str, required=False, help='custom data file')
azure.add_argument('--algorithm', type=str, default=AzureCloudClass.default_algorithm, required=False, help='thumbprint algorithm (default %s)' % AzureCloudClass.default_algorithm)
azure.add_argument('--os', type=str, required=False, choices=['Windows', 'Linux'], help='OS type')
azure.add_argument('--os_state', type=str, default=AzureCloudClass.default_os_state, required=False, choices=['Generalized', 'Specialized '], help='OS image state (default: %s)' % AzureCloudClass.default_os_state)
azure.add_argument('--language', type=str, required=False, help='OS image language')
azure.add_argument('--availset', type=str, required=False, help='availability set name')
azure.add_argument('--network', type=str, required=False, help='virtual network name')
azure.add_argument('--subnet', type=str, nargs='+', required=False, help='subnet name(s) (e.g. Subnet-1, Subnet-2, Subnet-3, Subnet-4, Subnet-5)')
azure.add_argument('--subnetaddr', type=str, nargs='+', required=False, help='subnet network address prefix(s) (e.g. 10.0.0.0/11, 10.32.0.0/11, 10.64.0.0/10, 192.168.0.0/19, 192.168.32.0/19 )')
azure.add_argument('--vnetaddr', type=str, nargs='+', required=False, help='virtual network address prefix(s) (e.g. 10.0.0.0/8, 192.168.0.0/16')
azure.add_argument('--lun', type=str, required=False, help='logical (disk) unit number (LUN)')
azure.add_argument('--location', type=str, required=False, help='resource location')
azure.add_argument('--publisher', type=str, required=False, default=AzureCloudClass.default_publisher, help='resource extension publisher name (default: %s)' % AzureCloudClass.default_publisher)
azure.add_argument('--extension', type=str, nargs='+', required=False, default=AzureCloudClass.default_extension, choices=['ChefClient', 'CustomScript', 'VMAccessAgent', 'OSPatching', 'DockerExtension', 'DSC', 'PuppetEnterpriseAgent', 'BGInfo', 'OctopusDeploy'], help='resource extension name(s) (default: %s)' % AzureCloudClass.default_extension)
azure.add_argument('--vmaop', type=str, required=False, default=AzureCloudClass.default_vmaop, choices=['ResetRDPConfig', 'ResetSSHKey', 'ResetSSHKeyAndPassword', 'ResetPassword', 'DeleteUser', 'ResetSSHConfig'], help='VMAccess operation (default: %s)' % AzureCloudClass.default_vmaop)
azure.add_argument('--patching_disabled', action='store_true', required=False, help='OSPatching disable patching')
azure.add_argument('--patching_stop', action='store_true', required=False, help='OSPatching stop patching')
azure.add_argument('--patching_reboot_after', type=str, required=False, default=AzureCloudClass.default_patching_reboot_after, choices=['Auto', 'Required', 'NotRequired'], help='OSPatching reboot after patching (default: %s)' % AzureCloudClass.default_patching_reboot_after)
azure.add_argument('--patching_interval', type=int, required=False, default=AzureCloudClass.default_patching_interval, help='OSPatching interval (default: %i)' % AzureCloudClass.default_patching_interval)
azure.add_argument('--patching_day', type=str, required=False, default=AzureCloudClass.default_patching_day, help='OSPatching patching day (default: %s)' % AzureCloudClass.default_patching_day)
azure.add_argument('--patching_starttime', type=str, required=False, default=AzureCloudClass.default_patching_starttime, help='OSPatching patching start time HH:MM (default: one off)')
azure.add_argument('--patching_category', type=str, required=False, default=AzureCloudClass.default_patching_category, choices=['ImportantAndRecommended', 'Important'], help='OSPatching patching catgory (default: %s)' % AzureCloudClass.default_patching_category)
azure.add_argument('--patching_duration', type=str, required=False, default=AzureCloudClass.default_patching_duration, help='OSPatching patching duration (default: %s)' % AzureCloudClass.default_patching_duration)
azure.add_argument('--patching_local', action='store_true', required=False, help='OSPatching patching local')
azure.add_argument('--patching_oneoff', action='store_true', required=False, help='OSPatching patching one-off')
azure.add_argument('--eula_uri', type=str, required=False, help='VM image EULA URI')
azure.add_argument('--privacy_uri', type=str, required=False, help='VM image privacy URI')
azure.add_argument('--icon_uri', type=str, required=False, help='VM image icon URI')
azure.add_argument('--small_icon_uri', type=str, required=False, help='VM image small icon URI')
azure.add_argument('--show_in_gui', action='store_true', required=False, help='show VM image in GUI')
azure.add_argument('--docker_port', type=str, required=False, default=AzureCloudClass.default_docker_port, help='Docker TCP port (default: %s)' % AzureCloudClass.default_docker_port)
azure.add_argument('--docker_options', type=str, nargs='+', required=False, default=AzureCloudClass.default_docker_options, help='Docker options (default: %s)' % AzureCloudClass.default_docker_options)
azure.add_argument('--docker_username', type=str, required=False, default=AzureCloudClass.default_docker_username, help='Docker registry server username (default: %s)' % AzureCloudClass.default_docker_username)
azure.add_argument('--docker_password', type=str, required=False, default=AzureCloudClass.default_docker_password, help='Docker registry password (default: %s)' % AzureCloudClass.default_docker_password)
azure.add_argument('--docker_email', type=str, required=False, default=AzureCloudClass.default_docker_email, help='Docker registry server email (default: %s)' % AzureCloudClass.default_docker_email)
azure.add_argument('--docker_ca_certificate', type=str, required=False, default=AzureCloudClass.default_docker_ca_certificate, help='Docker CA certificate for TSL configuration (default: %s)' % AzureCloudClass.default_docker_ca_certificate)
azure.add_argument('--docker_server_certificate', type=str, required=False, default=AzureCloudClass.default_docker_server_certificate, help='Docker server certificate for TSL configuration (default: %s)' % AzureCloudClass.default_docker_server_certificate)
azure.add_argument('--docker_server_key', type=str, required=False, default=AzureCloudClass.default_docker_server_key, help='Docker server private key for TSL configuration (default: %s)' % AzureCloudClass.default_docker_server_key)
azure.add_argument('--docker_registry_server', type=str, required=False, help='Docker registry server (default: DockerHub)')
azure.add_argument('--docker_compose', type=str, required=False, default=AzureCloudClass.default_docker_compose, help='Docker compose.yaml file (default: %s)' % AzureCloudClass.default_docker_compose)
azure.add_argument('--dsc_module', type=str, required=False, default=AzureCloudClass.default_dsc_module, help='DSC module (default: %s)' % AzureCloudClass.default_dsc_module)
azure.add_argument('--puppet_master', type=str, required=False, default=AzureCloudClass.default_puppet_master, help='Puppet Master IP or host-name (default: %s)' % AzureCloudClass.default_puppet_master)
args = parser.parse_args()
logger(message=str(args))
return args
def logger(message=None):
if BaseCloudHarnessClass.debug: sys.stderr.write('DEBUG %s\n' % repr(message))
if BaseCloudHarnessClass.log: logging.info('%s\n' % repr(message))
def generate_random_password(length=11):
pwd = ''.join(sample(map(chr, range(48, 57) + range(65, 90) + range(97, 122)), length))
if [d for d in pwd if d.isdigit()]:
return pwd
else:
return generate_random_password(length)
class BaseCloudHarnessClass():
log = False
debug = True
log_file = '%s' % os.path.basename(__file__).replace('py', 'log')
config_file = '%s' % os.path.basename(__file__).replace('py', 'conf')
cp = ConfigParser.SafeConfigParser()
try:
with open(config_file) as cf:
cp.readfp(cf)
except IOError:
pass
default_subscription_id = None
default_management_certificate = None
default_aad_app = None
default_client_id = None
default_client_key = None
default_tenant_id = None
default_api_version = None
default_docker_port = None
default_docker_options = None
default_docker_username = None
default_docker_password = None
default_docker_email = None
default_docker_ca_certificate = None
default_docker_server_certificate = None
default_docker_server_key = None
default_chef_server_url = None
default_chef_validation_client_name = None
default_chef_validation_key_file = None
default_chef_run_list = None
default_docker_port = None
default_docker_options = None
default_docker_username = None
default_docker_password = None
default_docker_email = None
default_docker_ca_certificate = None
default_docker_server_certificate = None
default_docker_server_key = None
default_docker_compose = None
default_dsc_module = None
default_puppet_master = None
default_octopus_server_url = None
default_octopus_api_key = None
default_octopus_environments = None
default_octopus_roles = None
default_octopus_port = None
default_windows_customscript_name = None
default_linux_customscript_name = None
default_remote_subnets = None
default_certificate = None
default_storage_account = None
default_storage_container = None
default_chef_autoupdate_client = None
default_chef_delete_config = None
default_chef_verify_api_cert = None
default_chef_ssl_verify_mode = None
default_patching_healthy_test_script = None
default_patching_idle_test_script = None
default_linux_custom_data_file = None
default_windows_custom_data_file = None
default_location = None
proxy = False
proxy_host = None
proxy_port = None
ssl_verify = False
try:
default_subscription_id = dict(cp.items('AzureConfig'))['subscription_id']
default_management_certificate = dict(cp.items('AzureConfig'))['management_certificate']
default_aad_app = dict(cp.items('AzureConfig'))['aad_app']
default_client_id = dict(cp.items('AzureConfig'))['client_id']
default_client_key = dict(cp.items('AzureConfig'))['client_key']
default_tenant_id = dict(cp.items('AzureConfig'))['tenant_id']
default_api_version = dict(cp.items('AzureConfig'))['api_version']
proxy = dict(cp.items('AzureConfig'))['proxy']
proxy_host = dict(cp.items('AzureConfig'))['proxy_host']
proxy_port = dict(cp.items('AzureConfig'))['proxy_port']
ssl_verify = dict(cp.items('AzureConfig'))['ssl_verify']
default_storage_account = dict(cp.items('AzureConfig'))['storage_account']
default_storage_container = dict(cp.items('AzureConfig'))['storage_container']
default_windows_customscript_name = dict(cp.items('CustomScriptExtensionForWindows'))['windows_customscript_name']
default_windows_custom_data_file = dict(cp.items('WindowsConfiguration'))['windows_custom_data_file']
default_linux_customscript_name = dict(cp.items('CustomScriptExtensionForLinux'))['linux_customscript_name']
default_linux_custom_data_file = dict(cp.items('LinuxConfiguration'))['linux_custom_data_file']
default_location = dict(cp.items('AzureConfig'))['location_name']
default_certificate = dict(cp.items('LinuxConfiguration'))['service_certificate']
default_remote_subnets = cp.items('DefaultEndpointACL')
default_chef_server_url = dict(cp.items('ChefClient'))['chef_server_url']
default_chef_validation_client_name = dict(cp.items('ChefClient'))['chef_validation_client_name']
default_chef_validation_key_file = dict(cp.items('ChefClient'))['chef_validation_key_file']
default_chef_run_list = dict(cp.items('ChefClient'))['chef_run_list']
default_chef_autoupdate_client = dict(cp.items('ChefClient'))['chef_autoupdate_client']
default_chef_delete_config = dict(cp.items('ChefClient'))['chef_delete_config']
default_chef_ssl_verify_mode = dict(cp.items('ChefClient'))['chef_ssl_verify_mode']
default_chef_verify_api_cert = dict(cp.items('ChefClient'))['chef_verify_api_cert']
default_puppet_master = dict(cp.items('PuppetEnterpriseAgent'))['puppet_master']
default_docker_port = dict(cp.items('DockerExtension'))['docker_port']
default_docker_options = dict(cp.items('DockerExtension'))['docker_options']
default_docker_username = dict(cp.items('DockerExtension'))['docker_username']
default_docker_password = dict(cp.items('DockerExtension'))['docker_password']
default_docker_email = dict(cp.items('DockerExtension'))['docker_email']
default_docker_ca_certificate = dict(cp.items('DockerExtension'))['docker_ca_certificate']
default_docker_server_certificate = dict(cp.items('DockerExtension'))['docker_server_certificate']
default_docker_server_key = dict(cp.items('DockerExtension'))['docker_server_key']
default_docker_compose = dict(cp.items('DockerExtension'))['docker_compose']
default_dsc_module = dict(cp.items('DSCExtension'))['dsc_module']
default_octopus_server_url = dict(cp.items('OctopusDeploy'))['octopus_server_url']
default_octopus_api_key = dict(cp.items('OctopusDeploy'))['octopus_api_key']
default_octopus_environments = dict(cp.items('OctopusDeploy'))['octopus_environments']
default_octopus_roles = dict(cp.items('OctopusDeploy'))['octopus_roles']
default_octopus_port = dict(cp.items('OctopusDeploy'))['octopus_port']
default_patching_healthy_test_script = dict(cp.items('OSPatchingExtensionForLinux'))['patching_healthy_test_script']
default_patching_idle_test_script = dict(cp.items('OSPatchingExtensionForLinux'))['patching_idle_test_script']
except:
pass
class AzureCloudClass(BaseCloudHarnessClass):
default_action = 'list_locations'
actions = [{'action': 'x_ms_version', 'params': [], 'collection': False},
{'action': 'host', 'params': [], 'collection': False},
{'action': 'cert_file', 'params': [], 'collection': False},
{'action': 'content_type', 'params': [], 'collection': False},
{'action': 'timeout', 'params': [], 'collection': False},
{'action': 'sub_id', 'params': [], 'collection': False},
{'action': 'request_session', 'params': [], 'collection': False},
{'action': 'requestid', 'params': [], 'collection': False},
{'action': 'list_collection', 'params': ['action'], 'collection': False},
{'action': 'list_dns_servers', 'params': ['service', 'deployment'], 'collection': False},
{'action': 'list_affinity_groups', 'params': [], 'collection': True},
{'action': 'list_disks', 'params': [], 'collection': True},
{'action': 'list_hosted_services', 'params': [], 'collection': True},
{'action': 'list_locations', 'params': [], 'collection': True},
{'action': 'list_management_certificates', 'params': [], 'collection': True},
{'action': 'list_operating_system_families', 'params': [], 'collection': True},
{'action': 'list_os_images', 'params': [], 'collection': True},
{'action': 'list_reserved_ip_addresses', 'params': [], 'collection': True},
{'action': 'list_resource_extension_versions', 'params': [], 'collection': False},
{'action': 'list_resource_extensions', 'params': [], 'collection': True},
{'action': 'list_resource_groups', 'params': [], 'collection': False},
{'action': 'list_resources_for_subscription', 'params': [], 'collection': False},
{'action': 'list_resources_for_group', 'params': ['group'], 'collection': False},
{'action': 'list_role_sizes', 'params': [], 'collection': True},
{'action': 'list_service_certificates', 'params': ['service'], 'collection': False},
{'action': 'list_storage_accounts', 'params': [], 'collection': True},
{'action': 'list_subscription_operations', 'params': [], 'collection': False},
{'action': 'list_subscriptions', 'params': [], 'collection': True},
{'action': 'list_subscriptions_arm', 'params': [], 'collection': False},
{'action': 'list_virtual_network_sites', 'params': ['action'], 'collection': True},
{'action': 'list_vm_images', 'params': [], 'collection': True},
{'action': 'list_role_definitions', 'params': [], 'collection': False},
{'action': 'list_tenants', 'params': [], 'collection': False},
{'action': 'list_linked_resources', 'params': [], 'collection': False},
{'action': 'list_resource_providers', 'params': [], 'collection': False},
{'action': 'list_locations_arm', 'params': [], 'collection': False},
{'action': 'list_virtual_machines_for_resource_group', 'params': ['group'], 'collection': False},
{'action': 'add_resource_extension', 'params': ['service', 'deployment', 'name', 'extension'], 'collection': False},
{'action': 'add_role', 'params': ['deployment', 'service', 'os', 'name', 'blob', 'subnet', 'account'], 'collection': False},
{'action': 'add_data_disk', 'params': ['service', 'deployment', 'name'], 'collection': False},
{'action': 'add_disk', 'params': ['name', 'os', 'blob'], 'collection': False},
{'action': 'add_dns_server', 'params': ['service', 'deployment', 'dns', 'ipaddr'], 'collection': False},
{'action': 'add_management_certificate', 'params': ['certificate'], 'collection': False},
{'action': 'add_os_image', 'params': ['name', 'blob', 'os'], 'collection': False},
{'action': 'add_service_certificate', 'params': ['service'], 'collection': False},
{'action': 'build_epacls_dict_from_xml', 'params': ['deployment', 'service', 'name'], 'collection': False},
{'action': 'build_chefclient_resource_extension', 'params': ['os'], 'collection': False},
{'action': 'build_customscript_resource_extension', 'params': ['os'], 'collection': False},
{'action': 'build_vmaccess_resource_extension', 'params': ['os'], 'collection': False},
{'action': 'build_ospatching_resource_extension', 'params': ['os'], 'collection': False},
{'action': 'build_docker_resource_extension', 'params': ['os'], 'collection': False},
{'action': 'build_dsc_resource_extension', 'params': ['os', 'dsc_module'], 'collection': False},
{'action': 'build_puppet_resource_extension', 'params': [], 'collection': False},
{'action': 'build_bginfo_resource_extension', 'params': [], 'collection': False},
{'action': 'build_octopusdeploy_resource_extension', 'params': [], 'collection': False},
{'action': 'build_resource_extension_dict', 'params': ['extension', 'publisher', 'version'], 'collection': False},
{'action': 'build_resource_extensions_xml_from_dict', 'params': ['rextrs'], 'collection': False},
{'action': 'check_hosted_service_name_availability', 'params': ['service'], 'collection': False},
{'action': 'check_storage_account_name_availability', 'params': ['account'], 'collection': False},
{'action': 'check_resource_name', 'params': ['name'], 'collection': False},
{'action': 'create_affinity_group', 'params': ['name'], 'collection': False},
{'action': 'create_hosted_service', 'params': ['service', 'label'], 'collection': False},
{'action': 'create_virtual_machine_deployment', 'params': ['deployment', 'service', 'os', 'name', 'blob', 'subnet', 'account', 'network'], 'collection': False},
{'action': 'create_virtual_network_site', 'params': ['network', 'subnet', 'subnetaddr', 'vnetaddr'], 'collection': False},
{'action': 'create_resource_group', 'params': ['group'], 'collection': False},
{'action': 'change_deployment_configuration', 'params': ['service', 'deployment', 'package_config'], 'collection': False},
{'action': 'create_storage_account', 'params': ['account'], 'collection': False},
{'action': 'create_role_assignment', 'params': ['role_definition_id'], 'collection': False},
{'action': 'capture_role', 'params': ['service', 'deployment', 'name', 'blob'], 'collection': False},
{'action': 'capture_vm_image', 'params': ['group', 'name'], 'collection': False},
{'action': 'capture_virtual_machine', 'params': ['name', 'group'], 'collection': False},
{'action': 'create_deployment', 'params': ['service', 'deployment', 'name', 'package_url', 'package_config'], 'collection': False},
{'action': 'create_reserved_ip_address', 'params': ['ipaddr'], 'collection': False},
{'action': 'create_vm_image', 'params': ['blob', 'os'], 'collection': False},
{'action': 'delete_affinity_group', 'params': ['name'], 'collection': False},
{'action': 'delete_role', 'params': ['deployment', 'service', 'name'], 'collection': False},
{'action': 'delete_os_image', 'params': ['name'], 'collection': False},
{'action': 'delete_disk', 'params': ['disk'], 'collection': False},
{'action': 'delete_disk_blob', 'params': ['blob'], 'collection': False},
{'action': 'delete_deployment', 'params': ['service', 'deployment'], 'collection': False},
{'action': 'delete_dns_server', 'params': ['service', 'deployment', 'dns'], 'collection': False},
{'action': 'delete_management_certificate', 'params': ['thumbprint'], 'collection': False},
{'action': 'delete_service_certificate', 'params': ['service', 'thumbprint'], 'collection': False},
{'action': 'delete_hosted_service', 'params': ['service'], 'collection': False},
{'action': 'delete_reserved_ip_address', 'params': ['ipaddr'], 'collection': False},
{'action': 'delete_storage_account', 'params': ['account'], 'collection': False},
{'action': 'delete_role_instances', 'params': ['service', 'deployment', 'name'], 'collection': False},
{'action': 'delete_data_disk', 'params': ['service', 'deployment', 'name', 'lun'], 'collection': False},
{'action': 'delete_vm_image', 'params': ['name'], 'collection': False},
{'action': 'delete_resource_group', 'params': ['group'], 'collection': False},
{'action': 'get_certificate_from_publish_settings', 'params': [], 'collection': False},
{'action': 'get_storage_account_properties', 'params': [], 'collection': False},
{'action': 'get_deployment_by_slot', 'params': ['service'], 'collection': False},
{'action': 'get_deployment_by_name', 'params': ['service', 'deployment'], 'collection': False},
{'action': 'get_role', 'params': ['service', 'deployment', 'name'], 'collection': False},
{'action': 'get_data_disk', 'params': ['name', 'service', 'deployment'], 'collection': False},
{'action': 'get_disk', 'params': ['disk'], 'collection': False},
{'action': 'get_hosted_service_properties', 'params': ['service'], 'collection': False},
{'action': 'get_management_certificate', 'params': ['thumbprint'], 'collection': False},
{'action': 'get_operation_status', 'params': ['request_id'], 'collection': False},
{'action': 'get_os_image', 'params': ['name'], 'collection': False},
{'action': 'get_reserved_ip_address', 'params': ['ipaddr'], 'collection': False},
{'action': 'get_service_certificate', 'params': ['service', 'thumbprint'], 'collection': False},
{'action': 'get_storage_account_keys', 'params': ['account'], 'collection': False},
{'action': 'get_subscription', 'params': [], 'collection': False},
{'action': 'get_subscription_properties', 'params': [], 'collection': False},
{'action': 'get_affinity_group_properties', 'params': ['name'], 'collection': False},
{'action': 'get_hosted_service_properties', 'params': ['service'], 'collection': False},
{'action': 'get_disk_by_role_name', 'params': ['service', 'deployment', 'name'], 'collection': False},
{'action': 'get_objs_for_role', 'params': ['deployment', 'service', 'name'], 'collection': False},
{'action': 'get_pub_key_and_thumbprint_from_x509_cert', 'params': ['certificate', 'algorithm'], 'collection': False},
{'action': 'get_service_principal_id_by_aad_app_name', 'params': [], 'collection': False},
{'action': 'get_epacls', 'params': ['service', 'deployment', 'name'], 'collection': False},
{'action': 'get_virtual_network_site', 'params': [], 'collection': False},
{'action': 'get_resource_group_properties', 'params': ['group'], 'collection': False},
{'action': 'get_virtual_machines_model_properties', 'params': ['name', 'group'], 'collection': False},
{'action': 'get_virtual_machines_instance_properties', 'params': ['name', 'group'], 'collection': False},
{'action': 'get_autoscale_settings_for_role', 'params': ['service', 'availset'], 'collection': False},
{'action': 'generate_signed_blob_url', 'params': ['account', 'container', 'script'], 'collection': False},
{'action': 'generalise_virtual_machine', 'params': ['name', 'group'], 'collection': False},
{'action': 'move_resources', 'params': [], 'collection': False},
{'action': 'perform_get', 'params': ['path'], 'collection': False},
{'action': 'perform_put', 'params': ['path', 'body'], 'collection': False},
{'action': 'perform_delete', 'params': ['path'], 'collection': False},
{'action': 'perform_post', 'params': ['path', 'body'], 'collection': False},
{'action': 'upload_blob', 'params': ['blob'], 'collection': False},
{'action': 'set_epacls', 'params': ['service', 'deployment', 'name', 'subnet'], 'collection': False},
{'action': 'reboot_role_instance', 'params': ['service', 'deployment', 'name'], 'collection': False},
{'action': 'start_role', 'params': ['service', 'deployment', 'name'], 'collection': False},
{'action': 'start_roles', 'params': ['service', 'deployment', 'name'], 'collection': False},
{'action': 'restart_role', 'params': ['service', 'deployment', 'name'], 'collection': False},
{'action': 'rebuild_role_instance', 'params': ['service', 'deployment', 'name'], 'collection': False},
{'action': 'regenerate_storage_account_keys', 'params': ['account'], 'collection': False},
{'action': 'reimage_role_instance', 'params': ['service', 'deployment', 'name'], 'collection': False},
{'action': 'rollback_update_or_upgrade', 'params': ['service', 'deployment'], 'collection': False},
{'action': 'register_subscription_with_resource_provider', 'params': [], 'collection': False},
{'action': 'swap_deployment', 'params': ['service', 'deployment', 'production_deployment'], 'collection': False},
{'action': 'shutdown_role', 'params': ['service', 'deployment', 'name'], 'collection': False},
{'action': 'shutdown_roles', 'params': ['service', 'deployment', 'name'], 'collection': False},
{'action': 'update_affinity_group', 'params': ['name'], 'collection': False},
{'action': 'update_data_disk', 'params': [], 'collection': False},
{'action': 'update_deployment_status', 'params': ['service', 'deployment', 'deployment_status'], 'collection': False},
{'action': 'update_disk', 'params': ['disk'], 'collection': False},
{'action': 'update_dns_server', 'params': ['service', 'deployment', 'dns', 'ipaddr'], 'collection': False},
{'action': 'update_hosted_service', 'params': [], 'collection': False},
{'action': 'update_os_image', 'params': ['blob', 'name'], 'collection': False},
{'action': 'update_role', 'params': ['deployment', 'service', 'name'], 'collection': False},
{'action': 'update_storage_account', 'params': [], 'collection': False},
{'action': 'update_vm_image', 'params': ['name'], 'collection': False},
{'action': 'update_resource_group', 'params': ['group'], 'collection': False},
{'action': 'upgrade_deployment', 'params': ['service', 'deployment', 'name', 'package_url', 'package_config'], 'collection': False},
{'action': 'unregister_subscription_with_resource_provider', 'params': [], 'collection': False},
{'action': 'wait_for_operation_status', 'params': [], 'collection': False},
{'action': 'wait_for_vm_provisioning_completion', 'params': ['service', 'deployment', 'name'], 'collection': False},
{'action': 'walk_upgrade_domain', 'params': ['service', 'deployment', 'upgrade_domain'], 'collection': False},
{'action': 'xml_networkconfig_fragment_from_dict', 'params': ['network', 'subnet', 'subnetaddr', 'vnetaddr'], 'collection': False},
{'action': 'xml_endpoint_fragment_from_dict', 'params': ['epacls'], 'collection': False}]
default_end_date = datetime.now()
default_start_date = default_end_date - timedelta(days=7)
default_publisher = 'Microsoft.Compute'
default_extension = 'CustomScriptExtension'
default_deployment_slot = 'Production'
default_size = 'Medium'
default_disk_size = 30
default_user_name = 'azureuser'
default_status = 'Succeeded'
default_wait = 15
default_timeout = 300
default_endpoints = {'Windows': [{'LocalPort': '5985',
'Name': 'WinRM',
'Port': str(randint(49152,65535)),
'Protocol': 'tcp'},
{'LocalPort': '5986',
'Name': 'PowerShell',
'Port': str(randint(49152,65535)),
'Protocol': 'tcp'},
{'LocalPort': '3389',
'Name': 'Remote Desktop',
'Port': str(randint(49152,65535)),
'Protocol': 'tcp'},
{'LocalPort': '10933',
'Name': 'TentacleIn',
'Port': str(randint(49152,65535)),
'Protocol': 'tcp'}],
'Linux': [{'LocalPort': '22',
'Name': 'SSH',
'Port': str(randint(49152,65535)),
'Protocol': 'tcp'},
{'LocalPort': '80',
'Name': 'HTTP',
'Port': str(randint(49152,65535)),
'Protocol': 'tcp'},
{'LocalPort': '443',
'Name': 'HTTPS',
'Port': str(randint(49152,65535)),
'Protocol': 'tcp'},
{'LocalPort': '2376',
'Name': 'Docker-SSL',
'Port': str(randint(49152,65535)),
'Protocol': 'tcp'}]}
default_algorithm = 'SHA1'
default_chef_autoupdate_client = True
default_chef_delete_config = False
default_vmaop = 'ResetPassword'
default_pwd_expiry = 365
default_patching_reboot_after = 'Auto'
default_patching_interval = 1
default_patching_day = 'Everyday'
default_patching_starttime = ''
default_patching_category = 'ImportantAndRecommended'
default_patching_duration = '03:00'
default_host_caching = 'ReadWrite'
default_post_capture_action = 'Reprovision'
default_os_state = 'Specialized'
default_start_deployment = False
default_ignore_warinings = False
default_account_type = 'Standard_GRS'
default_key_type = 'Primary'
default_mode = 'auto'
default_blobtype = 'page'
default_namespace = 'Microsoft.Resources'
default_type = 'Microsoft.ClassicCompute/domainNames'
def __init__(self, subscription_id=None, management_certificate=None,
aad_app=None, client_id=None, client_key=None, tenant_id=None):
try:
self.subscription_id = subscription_id or self.default_subscription_id
self.management_certificate = management_certificate or self.default_management_certificate
self.aad_app = aad_app or self.default_aad_app
self.client_id = client_id or self.default_client_id
self.client_key = client_key or self.default_client_key
self.tenant_id = tenant_id or self.default_tenant_id
if not self.subscription_id or not self.management_certificate:
for psf in os.listdir("."):
if psf.endswith(".publishsettings"):
self.publish_settings = psf
break
if self.publish_settings:
self.management_certificate = 'management_certificate.pem'
self.subscription_id = get_certificate_from_publish_settings(self.publish_settings,
path_to_write_certificate=self.management_certificate,
subscription_id=None)
self.cp.set('AzureConfig', 'subscription_id', self.subscription_id)
self.cp.set('AzureConfig', 'management_certificate', self.management_certificate)
try:
with open(self.config_file, 'wb') as cf:
self.cp.write(cf)
except IOError:
logger('%s: failed to update configuration file %s' % (inspect.stack()[0][3],
self.config_file))
sys.exit(1)
if not self.subscription_id:
logger('%s: failed to extract management certificate fom PublishSettings' % inspect.stack()[0][3])
sys.exit(1)
else:
logger('%s: written Azure management_certificate.pem for subscription_id %s' % (inspect.stack()[0][3], self.subscription_id))
else:
logger('%s: requires an Azure subscription_id and management_certificate (PublishSettings file not found)' % inspect.stack()[0][3])
sys.exit(1)
else:
self.sms = ServiceManagementService(self.subscription_id,
self.management_certificate,
request_session=self.get_request_session())
if not self.aad_app or not self.client_id or not self.client_key or not self.tenant_id:
logger('%s: Azure Resource Management APIs authentication credentials missing' % inspect.stack()[0][3])
self.arm_sess = None
pass
else:
token_url = 'https://login.microsoftonline.com/%s/oauth2/token' % self.tenant_id
self.arm_sess = self.get_request_session()
self.arm_sess.headers.update({'Accept': 'application/json'})
data = {'grant_type': 'client_credentials',
'client_id': self.client_id,
'client_secret': self.client_key,
'resource': 'https://management.azure.com/'}
response = self.arm_sess.post(token_url, data=data)
d = json.loads(response.text)
self.arm_access_token = d['access_token']
self.arm_token_type = d['token_type']
self.arm_expires = d['expires_on']
self.arm_auth = {'Authorization': '%s %s' % (self.arm_token_type,
self.arm_access_token)}
data = {'grant_type': 'client_credentials',
'client_id': self.client_id,
'client_secret': self.client_key,
'resource': 'https://graph.windows.net/'}
response = self.arm_sess.post(token_url, data=data)
d = json.loads(response.text)
self.graph_access_token = d['access_token']
self.graph_token_type = d['token_type']
self.graph_expires = d['expires_on']
self.graph_auth = {'Authorization': '%s %s' % (self.graph_token_type,
self.graph_access_token)}
except Exception as e:
logger(message=traceback.print_exc())
return False
def get_virtual_machines_instance_properties(self, *args):
try:
if not args: return False
arg = self.verify_params(method=inspect.stack()[0][3], params=args[0])
if not arg: return False
self.subscription_id = self.get_params(key='subscription_id', params=arg, default=self.default_subscription_id)
self.api_version = self.get_params(key='api_version', params=arg, default='2015-06-15')
self.name = self.get_params(key='name', params=arg, default=None)
if isinstance(self.name, list): self.name = self.name[0]
self.group = self.get_params(key='group', params=arg, default=None)
verbose = self.get_params(key='verbose', params=arg, default=None)
if verbose: pprint.pprint(self.__dict__)
url = 'https://management.azure.com/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/virtualMachines/%s/InstanceView?api-version=%s' % (self.subscription_id,
self.group,
self.name,
self.api_version)
if self.arm_sess:
self.arm_sess.headers.update(self.arm_auth)
response = self.arm_sess.get(url)
d = json.loads(response.text)
return d
else:
return False
except Exception as e:
logger(message=traceback.print_exc())
return False
def get_virtual_machines_model_properties(self, *args):
try:
if not args: return False
arg = self.verify_params(method=inspect.stack()[0][3], params=args[0])
if not arg: return False
self.subscription_id = self.get_params(key='subscription_id', params=arg, default=self.default_subscription_id)
self.api_version = self.get_params(key='api_version', params=arg, default='2015-06-15')
self.name = self.get_params(key='name', params=arg, default=None)
if isinstance(self.name, list): self.name = self.name[0]
self.group = self.get_params(key='group', params=arg, default=None)
verbose = self.get_params(key='verbose', params=arg, default=None)
if verbose: pprint.pprint(self.__dict__)
url = 'https://management.azure.com/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/virtualMachines/%s?api-version=%s' % (self.subscription_id,
self.group,
self.name,
self.api_version)
if self.arm_sess:
self.arm_sess.headers.update(self.arm_auth)
response = self.arm_sess.get(url)
d = json.loads(response.text)
return d
else:
return False
except Exception as e:
logger(message=traceback.print_exc())
return False
def get_service_principal_id_by_aad_app_name(self, *args):
try:
if not args: return False
arg = self.verify_params(method=inspect.stack()[0][3], params=args[0])
if not arg: return False
self.aad_app = self.get_params(key='aad_app', params=arg, default=self.default_aad_app)
self.api_version = self.get_params(key='api_version', params=arg, default='1.5')
url = "https://graph.windows.net/%s/servicePrincipals?$filter=servicePrincipalNames/any(c:c eq '%s')&api-version=%s" % (self.tenant_id,
self.client_id,
self.api_version)
if self.arm_sess:
self.arm_sess.headers.update(self.graph_auth)
response = self.arm_sess.get(url)
d = json.loads(response.text)
return d['value'][0]['objectId']
else:
return False
except Exception as e:
logger(message=traceback.print_exc())
return False
def add_resource_extension(self, *args):
try:
if not args: return False
arg = self.verify_params(method=inspect.stack()[0][3], params=args[0])
if not arg: return False
self.service = self.get_params(key='service', params=arg, default=None)
self.deployment = self.get_params(key='deployment', params=arg, default=None)
self.name = self.get_params(key='name', params=arg, default=None)
if isinstance(self.name, list): self.name = self.name[0]
self.extension = self.get_params(key='extension', params=arg, default=None)
verbose = self.get_params(key='verbose', params=arg, default=None)
self.os = self.get_params(key='os', params=arg, default=self.get_role({'service': self.service,
'deployment': self.deployment,
'name': self.name,
'verbose': False})['os_virtual_hard_disk']['os'])
if self.os:
arg['os'] = self.os
rextrs = list()
for extension in self.extension:
if extension == 'ChefClient':
rextrs.append(self.build_chefclient_resource_extension(arg))
if extension == 'CustomScript':
rextrs.append(self.build_customscript_resource_extension(arg))
if extension == 'VMAccessAgent':
rextrs.append(self.build_vmaccess_resource_extension(arg))
if extension == 'OSPatching':
rextrs.append(self.build_ospatching_resource_extension(arg))
if extension == 'DockerExtension':
rextrs.append(self.build_docker_resource_extension(arg))
if extension == 'DSC':
rextrs.append(self.build_dsc_resource_extension(arg))
if extension == 'PuppetEnterpriseAgent':
rextrs.append(self.build_puppet_resource_extension(arg))
if extension == 'BGInfo':
rextrs.append(self.build_bginfo_resource_extension(arg))
if extension == 'OctopusDeploy':
rextrs.append(self.build_octopusdeploy_resource_extension(arg))
arg['rextrs'] = self.build_resource_extensions_xml_from_dict(rextrs=rextrs)
if verbose: pprint.pprint(self.__dict__)
return self.update_role(arg)
else:
return False
except Exception as e:
logger(message=traceback.print_exc())
return False
def add_role(self, *args):
try:
if not args: return False
arg = self.verify_params(method=inspect.stack()[0][3], params=args[0])
if not arg: return False
self.service = self.get_params(key='service', params=arg, default=None)
self.deployment = self.get_params(key='deployment', params=arg, default=None)
self.name = self.get_params(key='name', params=arg, default=None)
if isinstance(self.name, list): self.name = self.name[0]
self.os = self.get_params(key='os', params=arg, default=None)
self.blob = self.get_params(key='blob', params=arg, default=None)
if isinstance(self.blob, list): self.blob = self.blob[0]
self.account = self.get_params(key='account', params=arg, default=None)
self.subnet = self.get_params(key='subnet', params=arg, default=None)
self.container = self.get_params(key='container', params=arg, default=self.default_storage_container)
self.label = self.get_params(key='label', params=arg, default=self.name)
self.availset = self.get_params(key='availset', params=arg, default=None)
self.password = self.get_params(key='password', params=arg, default=generate_random_password(length=11))
self.slot = self.get_params(key='slot', params=arg, default=self.default_deployment_slot)
self.size = self.get_params(key='size', params=arg, default=self.default_size)
self.username = self.get_params(key='username', params=arg, default=self.default_user_name)
self.eps = self.get_params(key='eps', params=arg, default=self.default_endpoints)
self.extension = self.get_params(key='extension', params=arg, default=None)
self.certificate = self.get_params(key='certificate', params=arg, default=self.default_certificate)
self.algorithm = self.get_params(key='algorithm', params=arg, default=self.default_algorithm)
self.async = self.get_params(key='async', params=arg, default=None)
readonly = self.get_params(key='readonly', params=arg, default=None)
self.ssh_auth = self.get_params(key='ssh_auth', params=arg, default=None)
self.disable_pwd_auth = self.get_params(key='disable_pwd_auth', params=arg, default=None)
verbose = self.get_params(key='verbose', params=arg, default=None)
if self.os == 'Windows':
self.custom_data_file = self.get_params(key='custom_data_file', params=arg, default=self.default_windows_custom_data_file)
try:
self.custom_data = None
with open(self.custom_data_file, 'rb') as cf:
self.custom_data = b64encode(cf.read())
except IOError:
logger('%s: unable to read %s' % (inspect.stack()[0][3], self.custom_data_file))
pass
if self.os == 'Linux':
self.custom_data_file = self.get_params(key='custom_data_file', params=arg, default=self.default_linux_custom_data_file)
try:
self.custom_data = None
with open(self.custom_data_file, 'rb') as cf:
self.custom_data = cf.read()
except IOError:
logger('%s: unable to read %s' % (inspect.stack()[0][3], self.custom_data_file))
pass
net_config = ConfigurationSet()
net_config.configuration_set_type = 'NetworkConfiguration'
net_config.subnet_names = self.subnet
endpoints = []
if self.os in ['Windows']:
self.os_config = WindowsConfigurationSet(computer_name=self.name,
admin_password=self.password,
reset_password_on_first_logon=None,
enable_automatic_updates=None,
time_zone=None,
admin_username=self.username,
custom_data=self.custom_data)
self.os_config.domain_join = None
self.os_config.win_rm = None
self.os_config.stored_certificate_settings = None
self.os_config.additional_unattend_content = None
for ep in self.eps[self.os]:
endpoints.append(ConfigurationSetInputEndpoint(name=ep['Name'],
protocol=ep['Protocol'],
port=ep['Port'],
local_port=ep['LocalPort'],
load_balanced_endpoint_set_name=None,
enable_direct_server_return=False))
eps = ConfigurationSetInputEndpoints()
eps.input_endpoints = endpoints
net_config.input_endpoints = eps
if self.os in ['Linux']:
if self.disable_pwd_auth:
self.password = None
self.ssh_auth = True
self.os_config = LinuxConfigurationSet(host_name=self.name,
user_name=self.username,
user_password=self.password,
disable_ssh_password_authentication=self.ssh_auth,
custom_data=self.custom_data)
if self.ssh_auth:
ssh = SSH()
pks = PublicKeys()
pk = PublicKey()
pk.path = '/home/%s/.ssh/authorized_keys' % self.username
result = self.get_pub_key_and_thumbprint_from_x509_cert(certificate=self.certificate, algorithm=self.algorithm)
self.thumbprint = result['thumbprint']
pk.fingerprint = self.thumbprint
pks.public_keys.append(pk)
ssh.public_keys = pks
self.os_config.ssh = ssh
for ep in self.eps[self.os]:
endpoints.append(ConfigurationSetInputEndpoint(name=ep['Name'],
protocol=ep['Protocol'],
port=ep['Port'],
local_port=ep['LocalPort'],
load_balanced_endpoint_set_name=None,
enable_direct_server_return=False))
eps = ConfigurationSetInputEndpoints()
eps.input_endpoints = endpoints
net_config.input_endpoints = eps
self.net_config = net_config
ts = mkdate(datetime.now(), '%Y-%m-%d-%H-%M-%S-%f')
self.media_link = 'https://%s.blob.core.windows.net/%s/%s-%s-%s-0.vhd' % (self.account,
self.container,
self.service,
self.name,
ts)
self.disk_config = OSVirtualHardDisk(source_image_name=self.blob,
media_link=self.media_link,
host_caching=None,
disk_label=None,
disk_name=None,
os=None,
remote_source_image_link=None)
if self.extension:
rextrs = list()
for extension in self.extension:
if extension == 'ChefClient':
rextrs.append(self.build_chefclient_resource_extension(arg))
if extension == 'CustomScript':
rextrs.append(self.build_customscript_resource_extension(arg))
if extension == 'VMAccessAgent':
rextrs.append(self.build_vmaccess_resource_extension(arg))
if extension == 'OSPatching':
rextrs.append(self.build_ospatching_resource_extension(arg))
if extension == 'DockerExtension':
rextrs.append(self.build_docker_resource_extension(arg))
if extension == 'DSC':
rextrs.append(self.build_dsc_resource_extension(arg))
if extension == 'PuppetEnterpriseAgent':
rextrs.append(self.build_puppet_resource_extension(arg))
if extension == 'BGInfo':
rextrs.append(self.build_bginfo_resource_extension(arg))
if extension == 'OctopusDeploy':
rextrs.append(self.build_octopusdeploy_resource_extension(arg))
self.rextrs = self.build_resource_extensions_xml_from_dict(rextrs=rextrs)
else:
self.rextrs = self.get_params(key='rextrs', params=args, default=None)
if verbose: pprint.pprint(self.__dict__)
if not readonly:
try:
d = dict()
result = self.sms.add_role(self.service, self.deployment, self.name,
self.os_config, self.disk_config, network_config=self.net_config,
availability_set_name=self.availset, data_virtual_hard_disks=None, role_size=self.size,
role_type='PersistentVMRole', resource_extension_references=self.rextrs,
provision_guest_agent=True, vm_image_name=None, media_location=None)
d['result'] = result.__dict__
if not self.async:
operation = self.sms.get_operation_status(result.request_id)
d['operation'] = operation.__dict__
d['operation_result'] = self.wait_for_operation_status(request_id=result.request_id)
self.wait_for_vm_provisioning_completion({'service': self.service,
'deployment': self.deployment,
'name': self.name})
return d
else:
return
except (AzureConflictHttpError) as e:
logger('%s: operation in progress or resource exists, try again..' % inspect.stack()[0][3])
return False
else:
logger('%s: limited to read-only operations' % inspect.stack()[0][3])
except Exception as e:
logger(message=traceback.print_exc())
return False
def add_data_disk(self, *args):
try:
if not args: return False
arg = self.verify_params(method=inspect.stack()[0][3], params=args[0])
if not arg: return False
self.service = self.get_params(key='service', params=arg, default=None)
self.deployment = self.get_params(key='deployment', params=arg, default=None)
self.name = self.get_params(key='name', params=arg, default=None)
if isinstance(self.name, list): self.name = self.name[0]
self.lun = self.get_params(key='lun',
params=arg,
default=len(self.get_disk_by_role_name({'service': self.service,
'deployment': self.deployment,
'name': self.name,