forked from vmware/python-client-for-vmware-cloud-on-aws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyvmc_fxns.py
5813 lines (5148 loc) · 236 KB
/
pyvmc_fxns.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 python3
# The shebang above is to tell the shell which interpreter to use. This make the file executable without "python3" in front of it (otherwise I had to use python3 pyvmc.py)
# I also had to change the permissions of the file to make it run. "chmod +x pyVMC.py" did the trick.
# I also added "export PATH="MY/PYVMC/DIRECTORY":$PATH" (otherwise I had to use ./pyvmc.y)
# For git BASH on Windows, you can use something like this #!/C/Users/usr1/AppData/Local/Programs/Python/Python38/python.exe
# Python Client for VMware Cloud on AWS
################################################################################
### Copyright (C) 2019-2022 VMware, Inc. All rights reserved.
### SPDX-License-Identifier: BSD-2-Clause
################################################################################
from random import choices
import re
import requests # need this for Get/Post/Delete
import configparser # parsing config file
import operator
import os
import time
import json
import sys
import ipaddress
import pandas as pd
from deepdiff import DeepDiff
from os.path import exists
from os import makedirs
from pathlib import Path
from prettytable import PrettyTable
from requests.sessions import session
from datetime import datetime, timezone
from requests.auth import HTTPBasicAuth
from re import search
from pyvmc_csp import *
from pyvmc_nsx import *
from pyvmc_vmc import *
from pyvmc_vcdr import *
from pyvmc_flexcomp import *
# ============================
# Read CONFIG.INI file
# ============================
def read_config():
if not exists("./config.ini"):
print()
print('config.ini is missing')
response = input("Would you like to build a default config.ini now? (please type 'yes' or 'no')")
if response.lower() == 'no' or response.lower() == 'n':
print()
print('You may rename config.ini.example to config.ini and manually populate the required values inside the file.')
sys.exit(0)
elif response.lower() == 'yes' or response.lower() == 'y':
build_initial_config()
sys.exit(0)
else:
config_params = {}
try:
config = configparser.ConfigParser()
config.read("./config.ini")
auth_info = False
Refresh_Token = ""
clientId = ""
clientSecret = ""
strProdURL = config.get("vmcConfig", "strProdURL")
strCSPProdURL = config.get("vmcConfig", "strCSPProdURL")
ORG_ID = config.get("vmcConfig", "org_id")
SDDC_ID = config.get("vmcConfig", "sddc_id")
strVCDRProdURL = config.get("vmcConfig", "strVCDRProdURL")
config_params.update({"strProdURL": strProdURL})
config_params.update({"strCSPProdURL": strCSPProdURL})
config_params.update({"ORG_ID": ORG_ID})
config_params.update({"SDDC_ID": SDDC_ID})
config_params.update({"strVCDRProdURL": strVCDRProdURL})
if config.has_option("vmcConfig", "refresh_Token"):
Refresh_Token = config.get("vmcConfig", "refresh_Token")
config_params.update({"Refresh_Token": Refresh_Token})
auth_info = True
if config.has_option("vmcConfig", "oauth_clientSecret") and config.has_option("vmcConfig", "oauth_clientId"):
clientId = config.get("vmcConfig", "oauth_clientId")
clientSecret = config.get("vmcConfig", "oauth_clientSecret")
config_params.update({"clientId": clientId})
config_params.update({"clientSecret": clientSecret})
auth_info = True
if len(strProdURL) == 0 or len(strCSPProdURL) == 0 or not auth_info or len(ORG_ID) == 0 or len(SDDC_ID) == 0 or len(strVCDRProdURL) == 0:
print()
print('strProdURL, strCSPProdURL, Refresh_Token, ORG_ID, and SDDC_ID must all be populated in config.ini')
print()
sys.exit(1)
if "x-x-x-x" in strVCDRProdURL or " " in strVCDRProdURL:
print()
print("Please correct the entry for strVCDRProdURL in config.ini before proceeding.")
print()
sys.exit(1)
except:
print(
'''There are problems with your config.ini file.
Please be sure you have the latest version and ensure at least the following values are populated:
- strProdURL - this should read: "https://vmc.vmware.com"
- strCSPProdURL - this should read: "https://console.cloud.vmware.com"
- Refresh_Token - this should be a properly scoped refresh refresh token from the VMware Cloud Services Console.
- oauth_clientId - this should be OAuth Client ID properly scoped from VMware Cloud Services Console.
- oauth_clientSecret - this should be OAuth Client Secret.
- ORG_ID - this should be the ID of your VMware Cloud Organization, found in the VMware Cloud Services Portal.
- SDDC_ID - if applicable, this should be the ID of the VMware Cloud SDDC (Software Defined Datacenter) you wish to work with.
- strVCDRProdURL - if applicable, this should be the URL of your VMware Cloud DR Orchestrator.
''')
sys.exit(1)
return config_params
def build_initial_config(**kwargs):
config = configparser.ConfigParser()
config['vmcConfig'] = {
'strProdURL':'https://vmc.vmware.com',
'strCSPProdURL':'https://console.cloud.vmware.com',
'strVCDRProdURL':'https://vcdr-xxx-xxx-xxx-xxx.app.vcdr.vmware.com/',
'refresh_Token':'',
'oauth_clientId':'',
'oauth_clientSecret':'',
'org_id':'',
'sddc_id': ''
}
rt = input('Please enter your refresh token:')
oid = input('Please enter your organization ID:')
sid = input('Please enter your SDDC ID:')
config['vmcConfig']['refresh_token'] = rt
config['vmcConfig']['org_id'] = oid
config['vmcConfig']['sddc_id'] = sid
with open('config.ini', 'w') as configfile:
config.write(configfile)
show_config()
print()
print("Your config.ini has been populated with the default URLs necessary for basic functionality,")
print(" as well as your Org and SDDC IDs, and your refresh token (if you chose to do so).")
print()
print("Please confirm your config.ini file using ./pyVMC.py config show or review your file manually, then try your command again.")
return
def show_config(**kwargs):
if not exists("./config.ini"):
print('config.ini is missing - rename config.ini.example to config.ini and populate the required values inside the file.')
sys.exit(1)
try:
config_file=open("./config.ini","r")
content=config_file.read()
print("content of the config file is:")
print(content)
except:
print('There are problems with your config.ini file.')
sys.exit(1)
# https://developer.vmware.com/ap is/csp/csp-iam/latest/csp/gateway/am/api/auth/api-tokens/authorize/post/
def getAccessToken(**kwargs):
auth_method = kwargs['auth_method']
strCSPProdURL = kwargs['strCSPProdURL']
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = None
match auth_method:
case 'oauth':
oauth_clientSecret = kwargs['oauth_clientSecret']
oauth_clientId = kwargs['oauth_clientId']
auth_string = "/csp/gateway/am/api/auth/authorize"
payload = {'grant_type': 'client_credentials'}
response = requests.post(f'{strCSPProdURL}{auth_string}', headers=headers, data=payload, auth=(oauth_clientId, oauth_clientSecret))
case 'refresh_token':
myKey = kwargs['myKey']
auth_string = "/csp/gateway/am/api/auth/api-tokens/authorize"
params = {'api_token': myKey}
response = requests.post(f'{strCSPProdURL}{auth_string}', params=params, headers=headers)
if response.status_code != 200:
print(f'Error received on api token: {response.status_code}.')
if response.status_code == 400:
print("Invalid request body | In case of expired refresh_token or bad token in config.ini")
elif response.status_code == 404:
print("The requested resource could not be found")
elif response.status_code == 409:
print("The request could not be processed due to a conflict")
elif response.status_code == 429:
print("The user has sent too many requests")
elif response.status_code == 500:
print("An unexpected error has occurred while processing the request")
else:
print(f"Unexpected error code {response.status_code}")
return None
jsonResponse = response.json()
access_token = jsonResponse['access_token']
return access_token
DEBUG_MODE = False
def generate_table(results):
"""Generates a 'prettytable' using a JSON payload; automatically uses the dictionary keys in the payload as column headers."""
keyslist = list(results[0].keys())
table = PrettyTable(keyslist)
for dct in results:
table.add_row([dct.get(c, "") for c in keyslist])
return table
def create_directory(dir_name):
# checking if the directory demo_folder exist or not.
if not exists(dir_name):
# if the demo_folder directory is not present then create it.
makedirs(dir_name)
print(f'Created directory:{dir_name}')
else:
print(f'Directory already exists: {dir_name}')
def validate_ip_address(ip_addr):
"""Validates if a provided IP address is a valide format"""
try:
ip_object = ipaddress.ip_address(ip_addr)
return True
except ValueError:
return False
# ============================
# CSP - Service Definitions
# ============================
def getServiceDefinitions(**kwargs):
"""Gets services and URI for associated access token and Org ID"""
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strCSPProdURL = kwargs['strCSPProdURL']
json_response = get_services_json(strCSPProdURL, ORG_ID, sessiontoken)
if json_response == None:
print("API Error")
sys.exit(1)
services= json_response['servicesList']
table = PrettyTable(['Service Name', 'Access type', 'Service URL'])
for i in services:
table.add_row([i['displayName'], i['serviceAccessType'], i['serviceUrls']['serviceHome']])
print(table)
def addUsersToCSPGroup(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strCSPProdURL = kwargs['strCSPProdURL']
group_id = kwargs['group_id']
email = kwargs['email']
params = {
'notifyUsers': 'false',
'usernamesToAdd': email
}
json_response = add_users_csp_group_json(strCSPProdURL, ORG_ID, sessiontoken, group_id, params)
if json_response == None:
print("API Error")
sys.exit(1)
print(f"Added: {json_response['succeeded']}" )
print(f"Failed: {json_response['failed']}" )
def findCSPUserByServiceRole(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strCSPProdURL = kwargs['strCSPProdURL']
if kwargs['service_role'] is None:
print("Please use -r or --service_role to specify the role name to search by. Use show-csp-service-roles to see entitled roles.")
sys.exit(1)
else:
service_role = kwargs['service_role']
json_response = get_csp_users_json(strCSPProdURL, ORG_ID, sessiontoken)
if json_response == None:
print("API Error")
sys.exit(1)
users = json_response['results']
table = PrettyTable(['Email','Service Role', 'Org Role'])
for user in users:
for servicedef in user['serviceRoles']:
for role in servicedef['serviceRoles']:
if role['name'] == service_role:
display_role = ''
for orgrole in user['organizationRoles']:
display_role = display_role + orgrole['name'] + ' '
table.add_row([user['user']['email'],service_role,display_role])
print(table)
def getCSPGroupDiff(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strCSPProdURL = kwargs['strCSPProdURL']
SKIP_MEMBERS = False
SKIP_OWNERS = False
if kwargs['group_id'] is None:
print('Usage: show-csp-group-diff --group-id <GROUP ID> --filter [showall|skipmembers|skipowners]')
sys.exit(1)
else:
group_id = kwargs['group_id']
if kwargs['filter'] == "skipmembers":
SKIP_MEMBERS = True
print('Skipping members...')
elif kwargs['filter'] == "skipowners":
SKIP_OWNERS = True
print('Skipping owners...')
else:
pass
json_response_groups = get_csp_group_info_json(strCSPProdURL, ORG_ID, sessiontoken, group_id)
if json_response_groups == None:
print("API Error")
sys.exit(1)
grouproles = json_response_groups['serviceRoles']
json_response_users = get_csp_users_json(strCSPProdURL, ORG_ID, sessiontoken)
if json_response_users == None:
print("API Error")
sys.exit(1)
users = json_response_users['results']
grouprolelist = []
for role in grouproles:
for rname in role['serviceRoleNames']:
grouprolelist.append(rname)
print('Group role list:')
print(grouprolelist)
i = 0
for user in users:
IS_OWNER = False
for orgrole in user['organizationRoles']:
if orgrole['name'] == 'org_owner':
IS_OWNER = True
break
IS_MEMBER = False
for orgrole in user['organizationRoles']:
if orgrole['name'] == 'org_member':
IS_MEMBER = True
break
if IS_OWNER and SKIP_OWNERS:
continue
if IS_MEMBER and SKIP_MEMBERS:
continue
i += 1
if i % 25 == 0:
wait = input("Press Enter to show more users, q to quit: ")
if wait == 'q':
sys.exit(0) # quiting is not an error
print('Group role list:')
print(grouprolelist)
print(user['user']['email'],f'({i} of {len(users)})')
print(f'Member: {IS_MEMBER}, Owner: {IS_OWNER}')
userrolelist = []
for servicedef in user['serviceRoles']:
for role in servicedef['serviceRoles']:
userrolelist.append(role['name'])
print('User role list:')
print(userrolelist)
diff = DeepDiff(grouprolelist,userrolelist,ignore_order=True)
print('Role Differences:')
print(diff)
print("------------- ")
def getCSPGroupMembers(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strCSPProdURL = kwargs['strCSPProdURL']
if kwargs['group_id'] is None:
print("Please use -gid or --group-id to specify the ID of the group you would like membership of.")
sys.exit()
else:
group_id = kwargs['group_id']
json_response = get_csp_users_group_json(strCSPProdURL, ORG_ID, sessiontoken, group_id)
if json_response == None:
print("API Error")
sys.exit(1)
users = json_response['results']
table = PrettyTable(['Username','First Name', 'Last Name','Email','userId'])
for user in users:
table.add_row([user['username'],user['firstName'],user['lastName'],user['email'],user['userId']])
print(table)
def getCSPGroups(**kwargs):
"""Get List of CSP groups from your Organization -- br"""
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strCSPProdURL = kwargs['strCSPProdURL']
if kwargs['search_term'] is None:
json_response = get_csp_groups_json(strCSPProdURL, ORG_ID, sessiontoken)
print("Got the groups")
if json_response is not None:
groups = json_response['results']
num_groups = len(groups)
if num_groups == 0:
print("No results returned.")
else:
print(str(num_groups) + " result" + ("s" if num_groups > 1 else "") + " returned:")
table = PrettyTable(['ID', 'Name', 'Group Type', 'User Count'])
for grp in groups:
table.add_row([grp['id'], grp['displayName'], grp['groupType'], grp['usersCount']])
print(table)
else:
search_term = kwargs['search_term']
json_response = get_csp_groups_searchterm_json(strCSPProdURL, ORG_ID, sessiontoken, search_term)
if json_response is not None:
groups = json_response['results']
num_groups = len(groups)
if num_groups == 0:
print("No results returned.")
else:
print(str(num_groups) + " result" + ("s" if num_groups > 1 else "") + " returned:")
table = PrettyTable(['ID', 'Name', 'Group Type', 'User Count'])
for grp in groups:
table.add_row([grp['id'], grp['displayName'], grp['groupType'], grp['usersCount']])
print(table)
else:
print("API Error")
sys.exit(1)
def searchCSPOrgUsers(**kwargs):
# for i, j in kwargs.items():
# print(i, j)
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strCSPProdURL = kwargs['strCSPProdURL']
if kwargs['search_term'] is None:
print("Plese enter a search term (--search-term). To simply show all ORG users, please use show-org-users")
sys.exit()
else:
searchTerm = kwargs['search_term']
params = {
'userSearchTerm': searchTerm
}
json_response = search_csp_users_json(strCSPProdURL, sessiontoken, params, ORG_ID)
if json_response == None:
print("API Error")
sys.exit(1)
users = json_response['results']
if len(users) >= 20:
print("Search API is limited to 20 results, refine your search term for accurate results.")
table = PrettyTable(['Username', 'First Name', 'Last Name', 'Email', 'userId'])
for user in users:
table.add_row([user['user']['username'], user['user']['firstName'], user['user']['lastName'], user['user']['email'], user['user']['userId']])
print(table)
def getCSPServiceRoles(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strCSPProdURL = kwargs['strCSPProdURL']
json_response = get_csp_service_roles_json(strCSPProdURL, ORG_ID, sessiontoken)
if json_response == None:
print("API Error")
sys.exit(1)
for svc_def in json_response['serviceRoles']:
for svc_role in svc_def['serviceRoleNames']:
print(svc_role)
def showORGusers(**kwargs):
"""Prints out all Org users, sorted by last name"""
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strCSPProdURL = kwargs['strCSPProdURL']
jsonResponse = get_csp_users_json(strCSPProdURL, ORG_ID, sessiontoken)
if jsonResponse == None:
print("API Error")
sys.exit(1)
users = jsonResponse['results']
table = PrettyTable(['First Name', 'Last Name', 'User Name'])
for i in users:
table.add_row([i['user']['firstName'],i['user']['lastName'],i['user']['username']])
print (table.get_string(sortby="Last Name"))
# ============================
# Cloud Flex Compute
# ============================
def showFlexcompActivityStatus(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strProdURL = kwargs["strProdURL"]
activity_id = kwargs['activityId']
jsonResponse = get_activity_status(strProdURL, session_token=sessiontoken, org_id=ORG_ID, activity_id=activity_id)
if jsonResponse is None:
print("API Error")
sys.exit(1)
table = PrettyTable(['Activity_ID', 'State', 'Activity'])
table.add_row([jsonResponse['id'], jsonResponse['state'], jsonResponse['activity_type_name']])
print(table)
def showFlexcompNamespaces(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strProdURL = kwargs["strProdURL"]
jsonResponse = get_flexcomp_namesapces(strProdURL, session_token=sessiontoken, org_id=ORG_ID)
if jsonResponse is None:
print("API Error")
sys.exit(1)
result = (jsonResponse['content'])
table = PrettyTable(['ID', 'Name', 'Provider', 'Region', 'State'])
for i in result:
table.add_row([i['id'], i['name'],i['provider'],i['region'],i['state']['display_name']])
print(table.get_string(sortby="Name"))
def showFlexcompRegions(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strProdURL = kwargs["strProdURL"]
jsonResponse = get_namespace_region(strProdURL, session_token=sessiontoken, org_id=ORG_ID)
if jsonResponse is None:
print("API Error")
sys.exit(1)
result = jsonResponse['region_profile_map']
table = PrettyTable(['Region Name', 'Region Description'])
for k,v in result.items():
table.add_row([k, v['region_description']])
print(table)
def showFlexcompTemplates(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strProdURL = kwargs["strProdURL"]
jsonResponse = get_namespace_profiles(strProdURL, session_token=sessiontoken, org_id=ORG_ID)
if jsonResponse is None:
print("API Error")
sys.exit(1)
result = jsonResponse['GENERAL_PURPOSE']['sizes']
# print(result)
table = PrettyTable(['id', 'Name', 'Capacity'])
for i in result:
cpu_cap = str(i['capacity']['cpu']['value']).split(".")[0]+i['capacity']['cpu']['unit']
mem_cap = str(i['capacity']['memory']['value']).split(".")[0]+i['capacity']['memory']['unit']
storage_cap = str(i['capacity']['storage']['value']).split(".")[0]+i['capacity']['storage']['unit']
capacity = cpu_cap + " " + mem_cap + " " + storage_cap
table.add_row([i['id'],i['name'],capacity])
print(table)
def validateNetworkFlexComp(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strProdURL = kwargs["strProdURL"]
cidr = kwargs["flexCompCIDR"]
seg_name = kwargs['segName']
seg_cidr = kwargs['segCIDR']
jsonResponse = flexcomp_validate_network(strProdURL, session_token=sessiontoken, org_id=ORG_ID, cidr=cidr, seg_name=seg_name, seg_cidr=seg_cidr)
if jsonResponse is None:
print("API Error")
sys.exit(1)
ens_result = jsonResponse["ens_cidr_config"]["result"]
seg_result = jsonResponse["segments_gateway_cidrs_configs"][0]["result"]
table = PrettyTable(['Field', 'Message', 'Status'])
table.add_row([ens_result["field_name"],ens_result["message"],ens_result["status"]])
table.add_row([seg_result[0]["field_name"],seg_result[0]["message"],seg_result[0]["status"]])
table.add_row([seg_result[1]["field_name"],seg_result[1]["message"],seg_result[1]["status"]])
print(table)
def createFlexcompNamespace(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strProdURL = kwargs["strProdURL"]
cidr = kwargs["flexCompCIDR"]
seg_name = kwargs['segName']
seg_cidr = kwargs['segCIDR']
namespace_name = kwargs['nsName']
namespace_desc = kwargs['nsDesc']
template_id = kwargs['templateId']
region = kwargs['region']
jsonResponse = create_flexcomp_namespace(strProdURL, session_token=sessiontoken, org_id=ORG_ID, name=namespace_name,
desc=namespace_desc, ens_size_id=template_id, region=region, cidr=cidr,
seg_name=seg_name,seg_cidr=seg_cidr)
if jsonResponse is None:
print("API Error")
sys.exit(1)
table = PrettyTable(['Activity_ID', 'State', 'Activity'])
table.add_row([jsonResponse['id'], jsonResponse['state'], jsonResponse['activity_type_name']])
print(table)
def deleteFlexcompNamespace(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strProdURL = kwargs["strProdURL"]
nsId = kwargs["nsId"]
jsonResponse = delete_flexcomp_namespace(strProdURL, session_token=sessiontoken, org_id=ORG_ID, nsId=nsId)
if jsonResponse is None:
print("API Error")
sys.exit(1)
table = PrettyTable(['Activity_ID', 'State', 'Activity'])
table.add_row([jsonResponse['id'], jsonResponse['state'], jsonResponse['activity_type_name']])
print(table)
# ===================================
# Cloud Flex Compute - VM operations
# ===================================
def showAllImagesFlexcomp(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strProdURL = kwargs["strProdURL"]
jsonResponse = get_all_images(strProdURL, session_token=sessiontoken, org_id=ORG_ID)
if jsonResponse is None:
print("API Error")
sys.exit(1)
result = jsonResponse['content']
# print(result)
table = PrettyTable(['id', 'Name', 'Type', 'State', 'OS'])
for i in result:
table.add_row([i['id'],i['name'],i['type'],i['state']['name'],i['os']])
print(table)
def showAllVMsFlexcomp(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strProdURL = kwargs["strProdURL"]
jsonResponse = get_all_vms(strProdURL, session_token=sessiontoken, org_id=ORG_ID)
if jsonResponse is None:
print("API Error")
sys.exit(1)
result = jsonResponse['content']
table = PrettyTable(['id', 'Name', 'Namespace', 'State', 'Power State'])
for i in result:
table.add_row([i['id'],i['name'],i['namespaceName'],i['state']['name'],i['vmMetadata']['powerState']])
print(table)
def vmPowerOperationsFlexcomp(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strProdURL = kwargs["strProdURL"]
vmId = kwargs['vmId']
powerOperation = kwargs['powerOperation']
jsonResponse = vm_power_operation(strProdURL, session_token=sessiontoken, org_id=ORG_ID, vmId=vmId, powerOperation=powerOperation)
if jsonResponse is None:
print("API Error")
sys.exit(1)
table = PrettyTable(['Activity_ID', 'State', 'Activity'])
table.add_row([jsonResponse['id'], jsonResponse['state'], jsonResponse['activity_type_name']])
print(table)
def createVMFlexcomp(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strProdURL = kwargs["strProdURL"]
vmName = kwargs['vmName']
vmNamespaceId = kwargs['vmNamespaceId']
vmCPU = kwargs['vmCPU']
vmMem = kwargs['vmMem']
vmStorage = kwargs['vmStorage']
networkSegName = kwargs['networkSegName']
# networkCIDR = kwargs['networkSegCIDR']
guestOS = kwargs['guestOS']
imageId = kwargs['imageId']
jsonResponse = create_vm_from_iso(strProdURL, session_token=sessiontoken, org_id=ORG_ID, name=vmName, namespace_name=vmNamespaceId, cpu=vmCPU, mem=vmMem, storage=vmStorage, network_seg_id=networkSegName, guestOS=guestOS, imageId=imageId)
if jsonResponse is None:
print("API Error")
sys.exit(1)
# print(jsonResponse)
table = PrettyTable(['Activity_ID', 'State', 'Activity'])
table.add_row([jsonResponse['id'], jsonResponse['state'], jsonResponse['activity_type_name']])
print(table)
def vmDeleteFlexcomp(**kwargs):
sessiontoken = kwargs['sessiontoken']
ORG_ID = kwargs['ORG_ID']
strProdURL = kwargs["strProdURL"]
vmId = kwargs['vmId']
jsonResponse = delete_vm(strProdURL, session_token=sessiontoken, org_id=ORG_ID, vmId=vmId)
if jsonResponse is None:
print("API Error")
sys.exit(1)
table = PrettyTable(['Activity_ID', 'State', 'Activity'])
table.add_row([jsonResponse['id'], jsonResponse['state'], jsonResponse['activity_type_name']])
print(table)
# ============================
# SDDC - Create/Delete/Task
# ============================
def printTask(event_name: str, task) -> None:
taskid = task['id']
print(f'{event_name} Task Started: {taskid}')
print(f'Created: {task["created"]}')
print(f'Updated: {task["updated"]}')
print(f'Updated by User ID: {task["updated_by_user_id"]}')
print(f'User ID: {task["user_id"]}')
print(f'User Name: {task["user_name"]}')
print(f'Version: {task["version"]}')
print(f'Updated by User Name: {task["updated_by_user_name"]}')
#
# Now the inline parts:
#
print(f"Status: {task['status']}")
print(f"Sub-Status: {task['sub_status']}")
print(f"Resource: {task['resource_type']}")
print(f"Resource ID: {task['resource_id']}")
print(f"Task Type: {task['task_type']}")
print(f"Error Message: {task['error_message']}")
return
def createSDDC(**kwargs) -> None:
"""Creates an SDDC based on the parameters. The caller should have permissions to do this."""
strProdURL = kwargs['strProdURL']
org_id = kwargs['ORG_ID']
sessiontoken = kwargs['sessiontoken']
name = kwargs['name']
linked_account_id = kwargs['aws_account_guid']
linked_account_num = kwargs['aws_account_num']
region = kwargs['region']
amount = kwargs['number']
host_type = kwargs['host_type']
subnetId = kwargs['aws_subnet_id']
mgt = kwargs['mgt_subnet']
size = kwargs['sddc_size']
validate_only = kwargs['validate_only']
if linked_account_id is None and linked_account_num is None:
print("You must supply either the GUID for the linked AWS account or the AWS account number. Please try again.")
sys.exit(1)
elif linked_account_id is None:
accounts = get_connected_accounts_json(strProdURL, org_id, sessiontoken)
for i in accounts:
if i['account_number'] == linked_account_num:
linked_account_id = i['id']
break
if amount > 1:
sddc_type = "DEFAULT"
elif amount == 1:
sddc_type = "1NODE"
else:
print("Invalid number of hosts entered. Please try again.")
json_data = {
'name': name,
'account_link_sddc_config': [
{
'connected_account_id': linked_account_id,
'customer_subnet_ids': [
subnetId
]
}
],
'provider': 'AWS',
'num_hosts': amount,
'deployment_type': 'SingleAZ',
'host_instance_type': host_type,
'sddc_type': sddc_type,
'size': size,
'region': region,
'vpc_cidr': mgt
}
json_response = create_sddc_json(strProdURL, sessiontoken, org_id, validate_only, json_data)
if json_response == None:
sys.exit(1) # an error
if 'input_validated' in json_response:
return
if not validate_only:
print("SDDC Creation:")
print(json.dumps(json_response, indent = 4))
return
def deleteSDDC(**kwargs) -> None:
"""deletes an SDDC based on the parameters. The caller should have permissions to do this."""
orgID = kwargs["ORG_ID"]
sessiontoken = kwargs["sessiontoken"]
strProdURL = kwargs["strProdURL"]
sddcID = kwargs["SDDCtoDelete"] #command line argument takes precedence over file, and -- arg.
force=kwargs['force']
json_response = delete_sddc_json(strProdURL, sessiontoken, orgID, sddcID,force)
if (json_response == None):
sys.exit(1)
print("SDDC Deletion info:")
print(json.dumps(json_response, indent=4))
return None
def watchSDDCTask(**kwargs):
"""watch task and print out status"""
strProdURL = kwargs['strProdURL']
orgID = kwargs["ORG_ID"]
sessiontoken = kwargs["sessiontoken"]
taskID = kwargs["taskID"]
json_response = watch_sddc_task_json(strProdURL, sessiontoken, orgID, taskID)
if json_response == None:
sys.exit(1)
# else, print out the task
task = json_response['id']
now_utc = datetime.now(timezone.utc)
print(f'Information on Task {task} @ {now_utc.isoformat().replace("+00:00", "Z")}')
printTask("Watch Task", json_response)
return None
def cancelSDDCTask(**kwargs):
"""cancel a task"""
strProdURL = kwargs['strProdURL']
orgID = kwargs["ORG_ID"]
sessiontoken = kwargs["sessiontoken"]
taskID = kwargs["taskID"]
json_response = cancel_sddc_task_json(strProdURL, sessiontoken, orgID, taskID)
if json_response == None:
sys.exit(1)
printTask("Cancel Task",json_response)
return None
# ============================
# SDDC - AWS Account and VPC
# ============================
def setSDDCConnectedServices(**kwargs):
"""Sets SDDC access to S3 to either internet or connected VPC via input value. tue = ENI, false = internet"""
proxy_url = kwargs["proxy"]
sessiontoken = kwargs["sessiontoken"]
value = kwargs["ENIorInternet"]
# pull the first connected VPC
json_response = get_conencted_vpc_json(proxy_url, sessiontoken)
if json_response == None:
sys.exit(1)
sddc_connected_vpc = json_response['results'][0]
# create the JSON
json_data = {
"name": "s3",
"enabled": value
}
json_response_status_code = set_connected_vpc_services_json(proxy_url, sessiontoken, sddc_connected_vpc['linked_vpc_id'], json_data)
if json_response_status_code == None:
sys.exit(1)
print(f'S3 connected via ENI is {value}')
def getCompatibleSubnets(**kwargs):
"""Lists all of the compatible subnets by Account ID and AWS Region"""
orgID = kwargs["ORG_ID"]
sessiontoken = kwargs["sessiontoken"]
SddcID = kwargs["SDDC_ID"]
linkedAccountId = kwargs["LinkedAccount"]
region = kwargs["Region"]
strProdURL = kwargs["strProdURL"]
jsonResponse = get_compatible_subnets_json(strProdURL, orgID, sessiontoken, linkedAccountId, region)
if jsonResponse == None:
print("API Error")
sys.exit(1)
vpc_map = jsonResponse['vpc_map']
table = PrettyTable(['vpc','description'])
subnet_table = PrettyTable(['vpc_id','subnet_id','subnet_cidr_block','name','compatible','connected_account_id'])
for i in vpc_map:
myvpc = jsonResponse['vpc_map'][i]
table.add_row([myvpc['vpc_id'],myvpc['description']])
for j in myvpc['subnets']:
subnet_table.add_row([j['vpc_id'],j['subnet_id'],j['subnet_cidr_block'],j['name'],j['compatible'],j['connected_account_id']])
print(f"VPC for {orgID} in region {region}")
print(table)
print(f"Compatible Subnets for Org {orgID}")
print(subnet_table)
def getConnectedAccounts(**kwargs):
"""Prints all connected AWS accounts"""
strProdURL = kwargs["strProdURL"]
orgID = kwargs["ORG_ID"]
sessiontoken = kwargs["sessiontoken"]
accounts = get_connected_accounts_json(strProdURL, orgID, sessiontoken)
orgtable = PrettyTable(['OrgID'])
orgtable.add_row([orgID])
print(str(orgtable))
table = PrettyTable(['Account Number','id'])
for i in accounts:
table.add_row([i['account_number'],i['id']])
print("Connected Accounts")
print(table)
def getSDDCConnectedVPC(**kwargs):
"""Prints table with Connected VPC and Services information - Compatible with M18+ SDDCs only"""
proxy_url = kwargs['proxy']
session_token = kwargs["sessiontoken"]
# NSX
json_response = get_conencted_vpc_json(proxy_url, session_token)
if json_response == None:
sys.exit(1)
sddc_connected_vpc = json_response['results'][0]
sddc_connected_vpc_services = get_connected_vpc_services_json(proxy_url, session_token, sddc_connected_vpc['linked_vpc_id'])
# The API changed for connected VPCs from M16 to M18 when the connected VPC prefix lists were added to M18.
# This if-else block should allow this function to work with both M16 and earlier as well as M18 and newer SDDCs.
if 'active_eni' in sddc_connected_vpc:
eni = sddc_connected_vpc['active_eni']
elif 'traffic_group_eni_mappings' in sddc_connected_vpc:
eni = sddc_connected_vpc['traffic_group_eni_mappings'][0]['eni']
else:
eni = "Unknown"
table = PrettyTable(['Customer-Owned Account', 'Connected VPC ID', 'Subnet', 'Availability Zone', 'ENI', 'Service Name', 'Service Access'])
table.add_row([sddc_connected_vpc['linked_account'], sddc_connected_vpc['linked_vpc_id'], sddc_connected_vpc['linked_vpc_subnets'][0]['cidr'], sddc_connected_vpc['linked_vpc_subnets'][0]['availability_zone'], eni, sddc_connected_vpc_services['results'][0]['name'],sddc_connected_vpc_services['results'][0]['enabled']])
print("Connected Services")
print(table)
def getSDDCShadowAccount(**kwargs):
"""Returns SDDC Shadow Account"""
proxy_url = kwargs["proxy"]
sessiontoken = kwargs["sessiontoken"]
#
json_response = get_sddc_shadow_account_json(proxy_url, sessiontoken)
if json_response == None:
sys.exit(1)
sddc_shadow_account = json_response['shadow_account']
print("Shadow Account is:")
print(sddc_shadow_account)
# ============================
# SDDC - SDDC
# ============================
def getSDDCState(**kwargs):
"""Prints out state of selected SDDC"""
org_id = kwargs["ORG_ID"]
sddc_id = kwargs["SDDC_ID"]
sessiontoken = kwargs["sessiontoken"]
strProdURL = kwargs["strProdURL"]
sddc_state = get_sddc_info_json(strProdURL, org_id, sessiontoken, sddc_id)
if sddc_state == None:
sys.exit(1)
table = PrettyTable(['Name', 'Id', 'Status', 'Type', 'Region', 'Deployment Type'])
table.add_row([sddc_state['name'], sddc_state['id'], sddc_state['sddc_state'], sddc_state['sddc_type'], sddc_state['resource_config']['region'], sddc_state['resource_config']['deployment_type']])
print("\nThis is your current environment:")
print (table)
def getSDDCS(**kwargs):
"""Prints all SDDCs in an Org with their clusters and number of hosts"""