forked from scotttyso/intersight_iac
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheasy_functions.py
1698 lines (1586 loc) · 81.6 KB
/
easy_functions.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
from git import cmd, Repo
from openpyxl import load_workbook
from ordered_set import OrderedSet
import itertools
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import stdiomask
import validating
# from class_policies_domain import policies_domain
from textwrap import fill
# Log levels 0 = None, 1 = Class only, 2 = Line
log_level = 2
# Exception Classes
class InsufficientArgs(Exception):
pass
class ErrException(Exception):
pass
class InvalidArg(Exception):
pass
class LoginFailed(Exception):
pass
#======================================================
# Function - Prompt User for the api_key
#======================================================
def api_key(args):
if args.api_key_id == None:
key_loop = False
while key_loop == False:
question = stdiomask.getpass(f'The Intersight API Key was not entered as a command line option.\n'\
'Please enter the Version 2 Intersight API key to use: ')
if len(question) == 74:
args.api_key_id = question
key_loop = True
else:
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' Error!! Invalid Value. The API key length should be 74 characters. Please Re-Enter.')
print(f'\n-------------------------------------------------------------------------------------------\n')
return args.api_key_id
#======================================================
# Function - Prompt User for the api_secret
#======================================================
def api_secret(args):
secret_loop = False
while secret_loop == False:
if '~' in args.api_key_file:
secret_path = os.path.expanduser(args.api_key_file)
else:
secret_path = args.api_key_file
if not os.path.isfile(secret_path):
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' Error!! api_key_file not found.')
print(f'\n-------------------------------------------------------------------------------------------\n')
args.api_key_file = input(f'Please Enter the Path to the File containing the Intersight API Secret: ')
else:
secret_file = open(secret_path, 'r')
if 'RSA PRIVATE KEY' in secret_file.read():
secret_loop = True
else:
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' Error!! api_key_file does not seem to contain the Private Key.')
print(f'\n-------------------------------------------------------------------------------------------\n')
return secret_path
#======================================================
# Function - Format Policy Description
#======================================================
def choose_policy(policy, **templateVars):
if 'policies' in policy:
policy_short = policy.replace('policies', 'policy')
elif 'pools' in policy:
policy_short = policy.replace('pools', 'pool')
elif 'templates' in policy:
policy_short = policy.replace('templates', 'template')
x = policy_short.split('_')
policy_description = []
for y in x:
y = y.capitalize()
policy_description.append(y)
policy_description = " ".join(policy_description)
policy_description = policy_description.replace('Ip', 'IP')
policy_description = policy_description.replace('Ntp', 'NTP')
policy_description = policy_description.replace('Snmp', 'SNMP')
policy_description = policy_description.replace('Wwnn', 'WWNN')
policy_description = policy_description.replace('Wwpn', 'WWPN')
if len(policy) > 0:
templateVars["policy"] = policy_description
policy_short = policies_list(templateVars["policies"], **templateVars)
else:
policy_short = ""
return policy_short
#======================================================
# Function - Count the Number of Keys
#======================================================
def countKeys(ws, func):
count = 0
for i in ws.rows:
if any(i):
if str(i[0].value) == func:
count += 1
return count
#======================================================
# Function - Prompt User with question - default No
#======================================================
def exit_default_no(policy_type):
valid_exit = False
while valid_exit == False:
exit_answer = input(f'Would You like to Configure another {policy_type}? Enter "Y" or "N" [N]: ')
if exit_answer == '' or exit_answer == 'N':
policy_loop = True
configure_loop = True
valid_exit = True
elif exit_answer == 'Y':
policy_loop = False
configure_loop = False
valid_exit = True
else:
print(f'\n------------------------------------------------------\n')
print(f' Error!! Invalid Value. Please enter "Y" or "N".')
print(f'\n------------------------------------------------------\n')
return configure_loop, policy_loop
#======================================================
# Function - Prompt User with question - default Yes
#======================================================
def exit_default_yes(policy_type):
valid_exit = False
while valid_exit == False:
exit_answer = input(f'Would You like to Configure another {policy_type}? Enter "Y" or "N" [Y]: ')
if exit_answer == '' or exit_answer == 'Y':
policy_loop = False
configure_loop = False
valid_exit = True
elif exit_answer == 'N':
policy_loop = True
configure_loop = True
valid_exit = True
else:
print(f'\n------------------------------------------------------\n')
print(f' Error!! Invalid Value. Please enter "Y" or "N".')
print(f'\n------------------------------------------------------\n')
return configure_loop, policy_loop
#======================================================
# Function - Prompt User with question
#======================================================
def exit_loop_default_yes(loop_count, policy_type):
valid_exit = False
while valid_exit == False:
if loop_count % 2 == 0:
exit_answer = input(f'Would You like to Configure another {policy_type}? Enter "Y" or "N" [Y]: ')
else:
exit_answer = input(f'Would You like to Configure another {policy_type}? Enter "Y" or "N" [N]: ')
if (loop_count % 2 == 0 and exit_answer == '') or exit_answer == 'Y':
policy_loop = False
configure_loop = False
loop_count += 1
valid_exit = True
elif not loop_count % 2 == 0 and exit_answer == '':
policy_loop = True
configure_loop = True
valid_exit = True
elif exit_answer == 'N':
policy_loop = True
configure_loop = True
valid_exit = True
else:
print(f'\n------------------------------------------------------\n')
print(f' Error!! Invalid Value. Please enter "Y" or "N".')
print(f'\n------------------------------------------------------\n')
return configure_loop, loop_count, policy_loop
#======================================================
# Function - find the Keys for each Section
#======================================================
def findKeys(ws, func_regex):
func_list = OrderedSet()
for i in ws.rows:
if any(i):
if re.search(func_regex, str(i[0].value)):
func_list.add(str(i[0].value))
return func_list
#======================================================
# Function - Assign the Variables to the Keys
#======================================================
def findVars(ws, func, rows, count):
var_list = []
var_dict = {}
for i in range(1, rows + 1):
if (ws.cell(row=i, column=1)).value == func:
try:
for x in range(2, 34):
if (ws.cell(row=i - 1, column=x)).value:
var_list.append(str(ws.cell(row=i - 1, column=x).value))
else:
x += 1
except Exception as e:
e = e
pass
break
vcount = 1
while vcount <= count:
var_dict[vcount] = {}
var_count = 0
for z in var_list:
var_dict[vcount][z] = ws.cell(row=i + vcount - 1, column=2 + var_count).value
var_count += 1
var_dict[vcount]['row'] = i + vcount - 1
vcount += 1
return var_dict
#======================================================
# Function - ipmi_key Function
#======================================================
def ipmi_key_function(**templateVars):
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' The ipmi_key Must be in Hexidecimal Format [a-fA-F0-9] and no longer than 40 characters.')
print(f'\n-------------------------------------------------------------------------------------------\n')
valid = False
while valid == False:
password1 = stdiomask.getpass(prompt='Enter the ipmi_key: ')
password2 = stdiomask.getpass(prompt='Please re-enter ipmi_key: ')
if not password1 == '':
if password1 == password2:
TF_VAR = 'TF_VAR_ipmi_key_1'
os.environ[TF_VAR] = '%s' % (password1)
templateVars["ipmi_key"] = 1
valid = validating.ipmi_key_check(password1)
else:
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' Error!! The Keys did not match. Please Re-enter the IPMI Key.')
print(f'\n-------------------------------------------------------------------------------------------\n')
else:
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' Error!! Invalid Value. Please Re-enter the IPMI Key.')
print(f'\n-------------------------------------------------------------------------------------------\n')
return templateVars["ipmi_key"]
#======================================================
# Function - Local User Policy
#======================================================
def local_users_function(jsonData, easy_jsonData, inner_loop_count, **templateVars):
local_users = []
valid_users = False
while valid_users == False:
templateVars["multi_select"] = False
jsonVars = jsonData['components']['schemas']['iam.EndPointUser']['allOf'][1]['properties']
templateVars["Description"] = jsonVars['Name']['description']
templateVars["varDefault"] = 'admin'
templateVars["varInput"] = 'What is the Local username?'
templateVars["varName"] = 'Local User'
templateVars["varRegex"] = jsonVars['Name']['pattern']
templateVars["minLength"] = 1
templateVars["maxLength"] = jsonVars['Name']['maxLength']
username = varStringLoop(**templateVars)
templateVars["multi_select"] = False
jsonVars = easy_jsonData['policies']['iam.LocalUserPasswordPolicy']
templateVars["var_description"] = jsonVars['role']['description']
templateVars["jsonVars"] = sorted(jsonVars['role']['enum'])
templateVars["defaultVar"] = jsonVars['role']['default']
templateVars["varType"] = 'User Role'
role = variablesFromAPI(**templateVars)
if templateVars["enforce_strong_password"] == True:
print(f'\n-------------------------------------------------------------------------------------------\n')
print('Enforce Strong Password is enabled so the following rules must be followed:')
print(' - The password must have a minimum of 8 and a maximum of 20 characters.')
print(" - The password must not contain the User's Name.")
print(' - The password must contain characters from three of the following four categories.')
print(' * English uppercase characters (A through Z).')
print(' * English lowercase characters (a through z).')
print(' * Base 10 digits (0 through 9).')
print(' * Non-alphabetic characters (! , @, #, $, %, ^, &, *, -, _, +, =)\n\n')
valid = False
while valid == False:
password1 = stdiomask.getpass(f'What is the password for {username}? ')
password2 = stdiomask.getpass(f'Please re-enter the password for {username}? ')
if not password1 == '':
if password1 == password2:
if templateVars["enforce_strong_password"] == True:
valid = validating.strong_password(f"{username}'s password", password1, 8, 20)
else:
valid = validating.string_length(f'{username} password', password1, 1, 127)
else:
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' Error!! The Passwords did not match. Please Re-enter the password for {username}.')
print(f'\n-------------------------------------------------------------------------------------------\n')
else:
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' Error!! Invalid Value. Please Re-enter the password for {username}.')
print(f'\n-------------------------------------------------------------------------------------------\n')
TF_VAR = 'TF_VAR_local_user_password_%s' % (inner_loop_count)
os.environ[TF_VAR] = '%s' % (password1)
password1 = inner_loop_count
user_attributes = {
'enabled':True,
'password':inner_loop_count,
'role':role,
'username':username
}
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' enabled = True')
print(f' password = "Sensitive"')
print(f' role = "{role}"')
print(f' username = "{username}"')
print(f'\n-------------------------------------------------------------------------------------------\n')
valid_confirm = False
while valid_confirm == False:
question = input('Do you want to accept the above configuration? Enter "Y" or "N" [Y]: ')
if question == 'Y' or question == '':
local_users.append(user_attributes)
valid_exit = False
while valid_exit == False:
loop_exit = input(f'Would You like to Configure another Local User? Enter "Y" or "N" [N]: ')
if loop_exit == 'Y':
inner_loop_count += 1
valid_confirm = True
valid_exit = True
elif loop_exit == 'N' or loop_exit == '':
user_loop = True
valid_confirm = True
valid_exit = True
valid_users = True
else:
print(f'\n------------------------------------------------------\n')
print(f' Error!! Invalid Value. Please enter "Y" or "N".')
print(f'\n------------------------------------------------------\n')
elif question == 'N':
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' Starting Local User Configuration Over.')
print(f'\n-------------------------------------------------------------------------------------------\n')
valid_confirm = True
else:
print(f'\n------------------------------------------------------\n')
print(f' Error!! Invalid Value. Please enter "Y" or "N".')
print(f'\n------------------------------------------------------\n')
return local_users,user_loop
#======================================================
# Function - Merge Easy IMM Repository to Dest Folder
#======================================================
def merge_easy_imm_repository(args, easy_jsonData, org):
baseRepo = args.dir
# Setup Operating Environment
opSystem = platform.system()
tfe_dir = 'tfe_modules'
if opSystem == 'Windows': path_sep = '\\'
else: path_sep = '/'
git_url = "https://github.com/terraform-cisco-modules/terraform-intersight-easy-imm"
if not os.path.isdir(tfe_dir):
os.mkdir(tfe_dir)
Repo.clone_from(git_url, tfe_dir)
else:
g = cmd.Git(tfe_dir)
g.pull()
folder_list = [
f'{baseRepo}{path_sep}{org}{path_sep}policies',
f'{baseRepo}{path_sep}{org}{path_sep}pools',
f'{baseRepo}{path_sep}{org}{path_sep}profiles',
f'{baseRepo}{path_sep}{org}{path_sep}ucs_domain_profiles'
]
removeList = [
'data_sources.tf',
'locals.tf',
'main.tf',
'output.tf',
'outputs.tf',
'provider.tf',
'README.md',
'variables.tf',
]
# Now Loop over the folders and merge the module files
module_folders = ['policies', 'pools', 'profiles', 'ucs_domain_profiles']
for folder in folder_list:
for mod in module_folders:
fsplit = folder.split(path_sep)
if fsplit[-1] == mod:
src_dir = os.path.join(tfe_dir, 'modules', mod)
copy_files = os.listdir(src_dir)
for fname in copy_files:
if not os.path.isdir(os.path.join(src_dir, fname)):
shutil.copy2(os.path.join(src_dir, fname), folder)
# Identify the files
files = easy_jsonData['wizard']['files'][mod]
for xRemove in removeList:
if xRemove in files:
files.remove(xRemove)
terraform_fmt(files, folder, path_sep)
#======================================================
# Function - Naming Rule
#======================================================
def naming_rule(name_prefix, name_suffix, org):
if not name_prefix == '':
name = '%s_%s' % (name_prefix, name_suffix)
else:
name = '%s_%s' % (org, name_suffix)
return name
#======================================================
# Function - Naming Rule Fabric Policy
#======================================================
def naming_rule_fabric(loop_count, name_prefix, org):
if loop_count % 2 == 0:
if not name_prefix == '':
name = '%s_A' % (name_prefix)
elif not org == 'default':
name = '%s_A' % (org)
else:
name = 'Fabric_A'
else:
if not name_prefix == '':
name = '%s_B' % (name_prefix)
elif not org == 'default':
name = '%s_B' % (org)
else:
name = 'Fabric_B'
return name
#======================================================
# Function - NTP
#======================================================
def ntp_alternate():
valid = False
while valid == False:
alternate_true = input('Do you want to Configure an Alternate NTP Server? Enter "Y" or "N" [Y]: ')
if alternate_true == 'Y' or alternate_true == '':
alternate_ntp = input('What is your Alternate NTP Server? [1.north-america.pool.ntp.org]: ')
if alternate_ntp == '':
alternate_ntp = '1.north-america.pool.ntp.org'
if re.search(r'[a-zA-Z]+', alternate_ntp):
valid = validating.dns_name('Alternate NTP Server', alternate_ntp)
else:
valid = validating.ip_address('Alternate NTP Server', alternate_ntp)
elif alternate_true == 'N':
alternate_ntp = ''
valid = True
else:
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' Error!! Invalid Value. Please enter "Y" or "N".')
print(f'\n-------------------------------------------------------------------------------------------\n')
return alternate_ntp
#======================================================
# Function - NTP
#======================================================
def ntp_primary():
valid = False
while valid == False:
primary_ntp = input('What is your Primary NTP Server [0.north-america.pool.ntp.org]: ')
if primary_ntp == "":
primary_ntp = '0.north-america.pool.ntp.org'
if re.search(r'[a-zA-Z]+', primary_ntp):
valid = validating.dns_name('Primary NTP Server', primary_ntp)
else:
valid = validating.ip_address('Primary NTP Server', primary_ntp)
return primary_ntp
def policies_list(policies_list, **templateVars):
valid = False
while valid == False:
print(f'\n-------------------------------------------------------------------------------------------\n')
if templateVars.get('optional_message'):
print(templateVars["optional_message"])
print(f' {templateVars["policy"]} Options:')
for i, v in enumerate(policies_list):
i += 1
if i < 10:
print(f' {i}. {v}')
else:
print(f' {i}. {v}')
if templateVars["allow_opt_out"] == True:
print(f' 99. Do not assign a(n) {templateVars["policy"]}.')
print(f' 100. Create a New {templateVars["policy"]}.')
print(f'\n-------------------------------------------------------------------------------------------\n')
policyOption = input(f'Select the Option Number for the {templateVars["policy"]} to Assign to {templateVars["name"]}: ')
if re.search(r'^[0-9]{1,3}$', policyOption):
for i, v in enumerate(policies_list):
i += 1
if int(policyOption) == i:
policy = v
valid = True
return policy
elif int(policyOption) == 99:
policy = ''
valid = True
return policy
elif int(policyOption) == 100:
policy = 'create_policy'
valid = True
return policy
if int(policyOption) == 99:
policy = ''
valid = True
return policy
elif int(policyOption) == 100:
policy = 'create_policy'
valid = True
return policy
else:
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' Error!! Invalid Selection. Please Select a valid Index from the List.')
print(f'\n-------------------------------------------------------------------------------------------\n')
def policies_parse(org, policy_type, policy):
if os.environ.get('TF_DEST_DIR') is None:
tfDir = 'Intersight'
else:
tfDir = os.environ.get('TF_DEST_DIR')
policies = []
opSystem = platform.system()
if opSystem == 'Windows':
policy_file = f'.\{tfDir}\{org}\{policy_type}\{policy}.auto.tfvars'
else:
policy_file = f'./{tfDir}/{org}/{policy_type}/{policy}.auto.tfvars'
if os.path.isfile(policy_file):
if len(policy_file) > 0:
if opSystem == 'Windows':
cmd = 'hcl2json.exe %s' % (policy_file)
else:
cmd = 'hcl2json %s' % (policy_file)
# cmd = 'json2hcl -reverse < %s' % (policy_file)
p = subprocess.run(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
if 'unable to parse' in p.stdout.decode('utf-8'):
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' !!!! Encountered Error in Attempting to read file !!!!')
print(f' - {policy_file}')
print(f' Error was:')
print(f' - {p.stdout.decode("utf-8")}')
print(f'\n-------------------------------------------------------------------------------------------\n')
json_data = {}
return policies,json_data
else:
json_data = json.loads(p.stdout.decode('utf-8'))
for i in json_data[policy]:
policies.append(i)
return policies,json_data
else:
json_data = {}
return policies,json_data
def policy_descr(name, policy_type):
valid = False
while valid == False:
descr = input(f'What is the Description for the {policy_type}? [{name} {policy_type}]: ')
if descr == '':
descr = '%s %s' % (name, policy_type)
valid = validating.description(f'{policy_type} templateVars["descr"]', descr, 1, 62)
if valid == True:
return descr
def policy_name(namex, policy_type):
valid = False
while valid == False:
name = input(f'What is the Name for the {policy_type}? [{namex}]: ')
if name == '':
name = '%s' % (namex)
valid = validating.name_rule(f'{policy_type} Name', name, 1, 62)
if valid == True:
return name
# Function to validate input for each method
def process_kwargs(required_args, optional_args, **kwargs):
# Validate all required kwargs passed
# if all(item in kwargs for item in required_args.keys()) is not True:
# error_ = '\n***ERROR***\nREQUIRED Argument Not Found in Input:\n "%s"\nInsufficient required arguments.' % (item)
# raise InsufficientArgs(error_)
error_count = 0
error_list = []
for item in required_args:
if item not in kwargs.keys():
error_count =+ 1
error_list += [item]
if error_count > 0:
error_ = '\n\n***Begin ERROR***\n\n - The Following REQUIRED Key(s) Were Not Found in kwargs: "%s"\n\n****End ERROR****\n' % (error_list)
raise InsufficientArgs(error_)
error_count = 0
error_list = []
for item in optional_args:
if item not in kwargs.keys():
error_count =+ 1
error_list += [item]
if error_count > 0:
error_ = '\n\n***Begin ERROR***\n\n - The Following Optional Key(s) Were Not Found in kwargs: "%s"\n\n****End ERROR****\n' % (error_list)
raise InsufficientArgs(error_)
# Load all required args values from kwargs
error_count = 0
error_list = []
for item in kwargs:
if item in required_args.keys():
required_args[item] = kwargs[item]
if required_args[item] == None:
error_count =+ 1
error_list += [item]
if error_count > 0:
error_ = '\n\n***Begin ERROR***\n\n - The Following REQUIRED Key(s) Argument(s) are Blank:\nPlease Validate "%s"\n\n****End ERROR****\n' % (error_list)
raise InsufficientArgs(error_)
for item in kwargs:
if item in optional_args.keys():
optional_args[item] = kwargs[item]
# Combine option and required dicts for Jinja template render
templateVars = {**required_args, **optional_args}
return(templateVars)
def process_method(wr_method, dest_dir, dest_file, template, **templateVars):
opSystem = platform.system()
if opSystem == 'Windows':
if os.environ.get('TF_DEST_DIR') is None:
tfDir = 'Intersight'
else:
tfDir = os.environ.get('TF_DEST_DIR')
if re.search(r'^\\.*\\$', tfDir):
dest_dir = '%s%s\%s' % (tfDir, templateVars["org"], dest_dir)
elif re.search(r'^\\.*\w', tfDir):
dest_dir = '%s\%s\%s' % (tfDir, templateVars["org"], dest_dir)
else:
dest_dir = '.\%s\%s\%s' % (tfDir, templateVars["org"], dest_dir)
if not os.path.isdir(dest_dir):
mk_dir = 'mkdir %s' % (dest_dir)
os.system(mk_dir)
dest_file_path = '%s\%s' % (dest_dir, dest_file)
if not os.path.isfile(dest_file_path):
create_file = 'type nul >> %s' % (dest_file_path)
os.system(create_file)
tf_file = dest_file_path
wr_file = open(tf_file, wr_method)
else:
if os.environ.get('TF_DEST_DIR') is None:
tfDir = 'Intersight'
else:
tfDir = os.environ.get('TF_DEST_DIR')
if re.search(r'^\/.*\/$', tfDir):
dest_dir = '%s%s/%s' % (tfDir, templateVars["org"], dest_dir)
elif re.search(r'^\/.*\w', tfDir):
dest_dir = '%s/%s/%s' % (tfDir, templateVars["org"], dest_dir)
else:
dest_dir = './%s/%s/%s' % (tfDir, templateVars["org"], dest_dir)
if not os.path.isdir(dest_dir):
mk_dir = 'mkdir -p %s' % (dest_dir)
os.system(mk_dir)
dest_file_path = '%s/%s' % (dest_dir, dest_file)
if not os.path.isfile(dest_file_path):
create_file = 'touch %s' % (dest_file_path)
os.system(create_file)
tf_file = dest_file_path
wr_file = open(tf_file, wr_method)
# Render Payload and Write to File
payload = template.render(templateVars)
wr_file.write(payload)
wr_file.close()
# Function to Read Excel Workbook Data
def read_in(excel_workbook):
try:
wb = load_workbook(excel_workbook)
print("Workbook Loaded.")
except Exception as e:
print(f"Something went wrong while opening the workbook - {excel_workbook}... ABORT!")
sys.exit(e)
return wb
def sensitive_var_value(jsonData, **templateVars):
sensitive_var = 'TF_VAR_%s' % (templateVars['Variable'])
# -------------------------------------------------------------------------------------------------------------------------
# Check to see if the Variable is already set in the Environment, and if not prompt the user for Input.
#--------------------------------------------------------------------------------------------------------------------------
if os.environ.get(sensitive_var) is None:
print(f"\n----------------------------------------------------------------------------------\n")
print(f" The Script did not find {sensitive_var} as an 'environment' variable.")
print(f" To not be prompted for the value of {templateVars['Variable']} each time")
print(f" add the following to your local environemnt:\n")
print(f" - Linux: export {sensitive_var}='{templateVars['Variable']}_value'")
print(f" - Windows: $env:{sensitive_var}='{templateVars['Variable']}_value'")
print(f"\n----------------------------------------------------------------------------------\n")
if os.environ.get(sensitive_var) is None:
valid = False
while valid == False:
varValue = input('press enter to continue: ')
if varValue == '':
valid = True
valid = False
while valid == False:
if templateVars.get('Multi_Line_Input'):
print(f'Enter the value for {templateVars["Variable"]}:')
lines = []
while True:
# line = input('')
line = stdiomask.getpass(prompt='')
if line:
lines.append(line)
else:
break
if not re.search('(certificate|private_key)', sensitive_var):
secure_value = '\\n'.join(lines)
else:
secure_value = '\n'.join(lines)
else:
valid_pass = False
while valid_pass == False:
password1 = stdiomask.getpass(prompt=f'Enter the value for {templateVars["Variable"]}: ')
password2 = stdiomask.getpass(prompt=f'Re-Enter the value for {templateVars["Variable"]}: ')
if password1 == password2:
secure_value = password1
valid_pass = True
else:
print('!!!Error!!! Sensitive Values did not match. Please re-enter...')
# Validate Sensitive Passwords
cert_regex = re.compile(r'^\-{5}BEGIN (CERTIFICATE|PRIVATE KEY)\-{5}.*\-{5}END (CERTIFICATE|PRIVATE KEY)\-{5}$')
if re.search('(certificate|private_key)', sensitive_var):
if not re.search(cert_regex, secure_value):
valid = True
else:
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' Error!!! Invalid Value for the {sensitive_var}. Please re-enter the {sensitive_var}.')
print(f'\n-------------------------------------------------------------------------------------------\n')
elif re.search('(apikey|secretkey)', sensitive_var):
if not sensitive_var == '':
valid = True
elif 'bind' in sensitive_var:
jsonVars = jsonData['components']['schemas']['iam.LdapBaseProperties']['allOf'][1]['properties']
minLength = 1
maxLength = 254
rePattern = jsonVars['Password']['pattern']
varName = 'SNMP Community'
valid = validating.length_and_regex_sensitive(rePattern, varName, secure_value, minLength, maxLength)
elif 'community' in sensitive_var:
jsonVars = jsonData['components']['schemas']['snmp.Policy']['allOf'][1]['properties']
minLength = 1
maxLength = jsonVars['TrapCommunity']['maxLength']
rePattern = '^[\\S]+$'
varName = 'SNMP Community'
valid = validating.length_and_regex_sensitive(rePattern, varName, secure_value, minLength, maxLength)
elif 'ipmi_key' in sensitive_var:
jsonVars = jsonData['components']['schemas']['ipmioverlan.Policy']['allOf'][1]['properties']
minLength = 2
maxLength = jsonVars['EncryptionKey']['maxLength']
rePattern = jsonVars['EncryptionKey']['pattern']
varName = 'IPMI Encryption Key'
valid = validating.length_and_regex_sensitive(rePattern, varName, secure_value, minLength, maxLength)
elif 'iscsi_boot' in sensitive_var:
jsonVars = jsonData['components']['schemas']['vnic.IscsiAuthProfile']['allOf'][1]['properties']
minLength = 12
maxLength = 16
rePattern = jsonVars['Password']['pattern']
varName = 'iSCSI Boot Password'
valid = validating.length_and_regex_sensitive(rePattern, varName, secure_value, minLength, maxLength)
elif 'local' in sensitive_var:
jsonVars = jsonData['components']['schemas']['iam.EndPointUserRole']['allOf'][1]['properties']
minLength = jsonVars['Password']['minLength']
maxLength = jsonVars['Password']['maxLength']
rePattern = jsonVars['Password']['pattern']
varName = 'Local User Password'
if templateVars.get('enforce_strong_password'):
enforce_pass = templateVars['enforce_strong_password']
else:
enforce_pass = False
if enforce_pass == True:
minLength = 8
maxLength = 20
valid = validating.strong_password(templateVars['Variable'], secure_value, minLength, maxLength)
else:
valid = validating.length_and_regex_sensitive(rePattern, varName, secure_value, minLength, maxLength)
elif 'secure_passphrase' in sensitive_var:
jsonVars = jsonData['components']['schemas']['memory.PersistentMemoryLocalSecurity']['allOf'][1]['properties']
minLength = jsonVars['SecurePassphrase']['minLength']
maxLength = jsonVars['SecurePassphrase']['maxLength']
rePattern = jsonVars['SecurePassphrase']['pattern']
varName = 'Persistent Memory Secure Passphrase'
valid = validating.length_and_regex_sensitive(rePattern, varName, secure_value, minLength, maxLength)
elif 'snmp' in sensitive_var:
jsonVars = jsonData['components']['schemas']['snmp.Policy']['allOf'][1]['properties']
minLength = 1
maxLength = jsonVars['TrapCommunity']['maxLength']
rePattern = '^[\\S]+$'
if 'auth' in sensitive_var:
varName = 'SNMP Authorization Password'
else:
varName = 'SNMP Privacy Password'
valid = validating.length_and_regex_sensitive(rePattern, varName, secure_value, minLength, maxLength)
elif 'vmedia' in sensitive_var:
jsonVars = jsonData['components']['schemas']['vmedia.Mapping']['allOf'][1]['properties']
minLength = 1
maxLength = jsonVars['Password']['maxLength']
rePattern = '^[\\S]+$'
varName = 'vMedia Mapping Password'
valid = validating.length_and_regex_sensitive(rePattern, varName, secure_value, minLength, maxLength)
# Add the Variable to the Environment
os.environ[sensitive_var] = '%s' % (secure_value)
var_value = secure_value
else:
# Add the Variable to the Environment
if templateVars.get('Multi_Line_Input'):
var_value = os.environ.get(sensitive_var)
var_value = var_value.replace('\n', '\\n')
else:
var_value = os.environ.get(sensitive_var)
return var_value
def snmp_trap_servers(jsonData, inner_loop_count, snmp_user_list, **templateVars):
trap_servers = []
valid_traps = False
while valid_traps == False:
templateVars["multi_select"] = False
jsonVars = jsonData['components']['schemas']['snmp.Trap']['allOf'][1]['properties']
if len(snmp_user_list) == 0:
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' There are no valid SNMP Users so Trap Destinations can only be set to SNMPv2.')
print(f'\n-------------------------------------------------------------------------------------------\n')
snmp_version = 'V2'
else:
templateVars["var_description"] = jsonVars['Version']['description']
templateVars["jsonVars"] = sorted(jsonVars['Version']['enum'])
templateVars["defaultVar"] = jsonVars['Version']['default']
templateVars["varType"] = 'SNMP Version'
snmp_version = variablesFromAPI(**templateVars)
if snmp_version == 'V2':
valid = False
while valid == False:
community_string = stdiomask.getpass(f'What is the Community String for the Destination? ')
if not community_string == '':
valid = validating.snmp_string('SNMP Community String', community_string)
else:
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' Error!! Invalid Value. Please Re-enter the SNMP Community String.')
print(f'\n-------------------------------------------------------------------------------------------\n')
TF_VAR = 'TF_VAR_snmp_community_string_%s' % (inner_loop_count)
os.environ[TF_VAR] = '%s' % (community_string)
community_string = inner_loop_count
if snmp_version == 'V3':
templateVars["multi_select"] = False
templateVars["var_description"] = ' Please Select the SNMP User to assign to this Destination:\n'
templateVars["var_type"] = 'SNMP User'
snmp_users = []
for item in snmp_user_list:
snmp_users.append(item['name'])
snmp_user = vars_from_list(snmp_users, **templateVars)
snmp_user = snmp_user[0]
if snmp_version == 'V2':
templateVars["var_description"] = jsonVars['Type']['description']
templateVars["jsonVars"] = sorted(jsonVars['Type']['enum'])
templateVars["defaultVar"] = jsonVars['Type']['default']
templateVars["varType"] = 'SNMP Trap Type'
trap_type = variablesFromAPI(**templateVars)
else:
trap_type = 'Trap'
valid = False
while valid == False:
destination_address = input(f'What is the SNMP Trap Destination Hostname/Address? ')
if not destination_address == '':
if re.search(r'^[0-9a-fA-F]+[:]+[0-9a-fA-F]$', destination_address) or \
re.search(r'^(\d{1,3}\.){3}\d{1,3}$', destination_address):
valid = validating.ip_address('SNMP Trap Destination', destination_address)
else:
valid = validating.dns_name('SNMP Trap Destination', destination_address)
else:
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' Error!! Invalid Value. Please Re-enter the SNMP Trap Destination Hostname/Address.')
print(f'\n-------------------------------------------------------------------------------------------\n')
valid = False
while valid == False:
port = input(f'Enter the Port to Assign to this Destination. Valid Range is 1-65535. [162]: ')
if port == '':
port = 162
if re.search(r'[0-9]{1,4}', str(port)):
valid = validating.snmp_port('SNMP Port', port, 1, 65535)
else:
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' Invalid Entry! Please Enter a valid Port in the range of 1-65535.')
print(f'\n-------------------------------------------------------------------------------------------\n')
if snmp_version == 'V3':
snmp_destination = {
'destination_address':destination_address,
'enabled':True,
'port':port,
'trap_type':trap_type,
'user':snmp_user,
'version':snmp_version
}
else:
snmp_destination = {
'community':community_string,
'destination_address':destination_address,
'enabled':True,
'port':port,
'trap_type':trap_type,
'version':snmp_version
}
print(f'\n-------------------------------------------------------------------------------------------\n')
if snmp_version == 'V2':
print(f' community_string = "Sensitive"')
print(f' destination_address = "{destination_address}"')
print(f' enable = True')
print(f' trap_type = "{trap_type}"')
print(f' snmp_version = "{snmp_version}"')
if snmp_version == 'V3':
print(f' user = "{snmp_user}"')
print(f'\n-------------------------------------------------------------------------------------------\n')
valid_confirm = False
while valid_confirm == False:
confirm_v = input('Do you want to accept the above configuration? Enter "Y" or "N" [Y]: ')
if confirm_v == 'Y' or confirm_v == '':
trap_servers.append(snmp_destination)
valid_exit = False
while valid_exit == False:
loop_exit = input(f'Would You like to Configure another SNMP Trap Destination? Enter "Y" or "N" [N]: ')
if loop_exit == 'Y':
inner_loop_count += 1
valid_confirm = True
valid_exit = True
elif loop_exit == 'N' or loop_exit == '':
snmp_loop = True
valid_confirm = True
valid_exit = True
valid_traps = True
else:
print(f'\n------------------------------------------------------\n')
print(f' Error!! Invalid Value. Please enter "Y" or "N".')
print(f'\n------------------------------------------------------\n')
elif confirm_v == 'N':
print(f'\n-------------------------------------------------------------------------------------------\n')
print(f' Starting Remote Host Configuration Over.')
print(f'\n-------------------------------------------------------------------------------------------\n')
valid_confirm = True
else:
print(f'\n------------------------------------------------------\n')
print(f' Error!! Invalid Value. Please enter "Y" or "N".')
print(f'\n------------------------------------------------------\n')
return trap_servers,snmp_loop
def snmp_users(jsonData, inner_loop_count, **templateVars):
snmp_user_list = []
valid_users = False
while valid_users == False:
templateVars["multi_select"] = False
jsonVars = jsonData['components']['schemas']['snmp.User']['allOf'][1]['properties']
snmpUser = False
while snmpUser == False:
templateVars["Description"] = jsonVars['Name']['description']
templateVars["varDefault"] = 'admin'