-
Notifications
You must be signed in to change notification settings - Fork 3
/
ntp_policy_maker.py
1276 lines (1186 loc) · 64.2 KB
/
ntp_policy_maker.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
"""
NTP Policy Maker for Cisco Intersight, v2.0
Author: Ugo Emekauwa
Contact: [email protected], [email protected]
Summary: The NTP Policy Maker for Cisco Intersight automates the creation
of NTP Policies.
GitHub Repository: https://github.com/ugo-emekauwa/cisco-imm-automation-tools
"""
########################
# MODULE REQUIREMENT 1 #
########################
"""
For the following variable below named key_id, please fill in between
the quotes your Intersight API Key ID.
Here is an example:
key_id = "5c89885075646127773ec143/5c82fc477577712d3088eb2f/5c8987b17577712d302eaaff"
"""
key_id = ""
########################
# MODULE REQUIREMENT 2 #
########################
"""
For the following variable below named key, please fill in between
the quotes your system's file path to your Intersight API key "SecretKey.txt"
file.
Here is an example:
key = "C:\\Users\\demouser\\Documents\\SecretKey.txt"
"""
key = ""
########################
# MODULE REQUIREMENT 3 #
########################
"""
Provide the required configuration settings to create the
NTP Policy on Cisco Intersight. Remove the sample
values and replace them with your own, where applicable.
"""
####### Start Configuration Settings - Provide values for the variables listed below. #######
# General Settings
ntp_policy_name = "NTP-Policy-1"
ntp_policy_description = "A Cisco Intersight NTP Policy generated by the NTP Policy Maker."
ntp_policy_organization = "default"
ntp_policy_tags = {"Org": "IT", "Dept": "DevOps"} # Empty the ntp_policy_tags dictionary if no tags are needed, for example: ntp_policy_tags = {}
# Policy Detail Settings
enable_ntp = True
ntp_servers = ["192.168.128.1",]
timezone = "America/New_York" # Options: Timezone options can be found at https://intersight.com/apidocs/apirefs/ntp/Policies/model
# Intersight Base URL Setting (Change only if using the Intersight Virtual Appliance)
intersight_base_url = "https://www.intersight.com/api/v1"
url_certificate_verification = True
# UCS Domain Profile Attachment Settings
ucs_domain_profile_name = ""
####### Finish Configuration Settings - The required value entries are complete. #######
#############################################################################################################################
#############################################################################################################################
import sys
import traceback
import json
import copy
import intersight
import re
import urllib3
# Suppress InsecureRequestWarning error messages
urllib3.disable_warnings()
# Function to get Intersight API client as specified in the Intersight Python SDK documentation for OpenAPI 3.x
## Modified to align with overall formatting, try/except blocks added for additional error handling, certificate verification option added
def get_api_client(api_key_id,
api_secret_file,
endpoint="https://intersight.com",
url_certificate_verification=True
):
try:
with open(api_secret_file, 'r') as f:
api_key = f.read()
if re.search('BEGIN RSA PRIVATE KEY', api_key):
# API Key v2 format
signing_algorithm = intersight.signing.ALGORITHM_RSASSA_PKCS1v15
signing_scheme = intersight.signing.SCHEME_RSA_SHA256
hash_algorithm = intersight.signing.HASH_SHA256
elif re.search('BEGIN EC PRIVATE KEY', api_key):
# API Key v3 format
signing_algorithm = intersight.signing.ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979
signing_scheme = intersight.signing.SCHEME_HS2019
hash_algorithm = intersight.signing.HASH_SHA256
configuration = intersight.Configuration(
host=endpoint,
signing_info=intersight.signing.HttpSigningConfiguration(
key_id=api_key_id,
private_key_path=api_secret_file,
signing_scheme=signing_scheme,
signing_algorithm=signing_algorithm,
hash_algorithm=hash_algorithm,
signed_headers=[
intersight.signing.HEADER_REQUEST_TARGET,
intersight.signing.HEADER_HOST,
intersight.signing.HEADER_DATE,
intersight.signing.HEADER_DIGEST,
]
)
)
if not url_certificate_verification:
configuration.verify_ssl = False
except Exception:
print("\nA configuration error has occurred!\n")
print("Unable to access the Intersight API Key.")
print("Exiting due to the Intersight API Key being unavailable.\n")
print("Please verify that the correct API Key ID and API Key have "
"been entered, then re-attempt execution.\n")
print("Exception Message: ")
traceback.print_exc()
sys.exit(0)
return intersight.ApiClient(configuration)
# Establish function to test for the availability of the Intersight API and Intersight account
def test_intersight_api_service(intersight_api_key_id,
intersight_api_key,
intersight_base_url="https://www.intersight.com/api/v1",
preconfigured_api_client=None
):
"""This is a function to test the availability of the Intersight API and
Intersight account. The tested Intersight account contains the user who is
the owner of the provided Intersight API Key and Key ID.
Args:
intersight_api_key_id (str):
The ID of the Intersight API key.
intersight_api_key (str):
The system file path of the Intersight API key.
intersight_base_url (str):
Optional; The base URL for Intersight API paths. The default value
is "https://www.intersight.com/api/v1". This value typically only
needs to be changed if using the Intersight Virtual Appliance. The
default value is "https://www.intersight.com/api/v1".
preconfigured_api_client ("ApiClient"):
Optional; An ApiClient class instance which handles
Intersight client-server communication through the use of API keys.
The default value is None. If a preconfigured_api_client argument
is provided, empty strings ("") or None can be provided for the
intersight_api_key_id, intersight_api_key, and intersight_base_url
arguments.
Returns:
A string of the name for the Intersight account tested, verifying the
Intersight API service is up and the Intersight account is accessible.
Raises:
Exception:
An exception occurred due to an issue with the provided API Key
and/or API Key ID.
"""
# Define Intersight SDK ApiClient variable
if preconfigured_api_client is None:
api_client = get_api_client(api_key_id=intersight_api_key_id,
api_secret_file=intersight_api_key,
endpoint=intersight_base_url
)
else:
api_client = preconfigured_api_client
try:
# Check that Intersight Account is accessible
print("Testing access to the Intersight API by verifying the "
"Intersight account information...")
api_client.call_api(resource_path="/iam/Accounts",
method="GET",
auth_settings=['cookieAuth', 'http_signature', 'oAuth2', 'oAuth2']
)
response = api_client.last_response.data
iam_account = json.loads(response)
if api_client.last_response.status != 200:
print("\nThe Intersight API and Account Availability Test did not "
"pass.")
print("The Intersight account information could not be verified.")
print("Exiting due to the Intersight account being unavailable.\n")
print("Please verify that the correct API Key ID and API Key have "
"been entered, then re-attempt execution.\n")
sys.exit(0)
else:
intersight_account_name = iam_account["Results"][0]["Name"]
print("The Intersight API and Account Availability Test has "
"passed.\n")
print(f"The Intersight account named '{intersight_account_name}' "
"has been found.")
return intersight_account_name
except Exception:
print("\nA configuration error has occurred!\n")
print("Unable to access the Intersight API.")
print("Exiting due to the Intersight API being unavailable.\n")
print("Please verify that the correct API Key ID and API Key have "
"been entered, then re-attempt execution.\n")
print("Exception Message: ")
traceback.print_exc()
sys.exit(0)
# Establish function to retrieve the MOID of a specific Intersight API object by name
def intersight_object_moid_retriever(intersight_api_key_id,
intersight_api_key,
object_name,
intersight_api_path,
object_type="object",
organization="default",
intersight_base_url="https://www.intersight.com/api/v1",
preconfigured_api_client=None
):
"""This is a function to retrieve the MOID of Intersight objects
using the Intersight API.
Args:
intersight_api_key_id (str):
The ID of the Intersight API key.
intersight_api_key (str):
The system file path of the Intersight API key.
object_name (str):
The name of the Intersight object.
intersight_api_path (str):
The Intersight API path of the Intersight object.
object_type (str):
Optional; The type of Intersight object. The default value is
"object".
organization (str):
Optional; The Intersight organization of the Intersight object.
The default value is "default".
intersight_base_url (str):
Optional; The base URL for Intersight API paths. The default value
is "https://www.intersight.com/api/v1". This value typically only
needs to be changed if using the Intersight Virtual Appliance.
preconfigured_api_client ("ApiClient"):
Optional; An ApiClient class instance which handles
Intersight client-server communication through the use of API keys.
The default value is None. If a preconfigured_api_client argument
is provided, empty strings ("") or None can be provided for the
intersight_api_key_id, intersight_api_key, and intersight_base_url
arguments.
Returns:
A string of the MOID for the provided Intersight object.
Raises:
Exception:
An exception occurred due to an issue accessing the Intersight API
path. The status code or error message will be specified.
"""
# Define Intersight SDK ApiClient variable
if preconfigured_api_client is None:
api_client = get_api_client(api_key_id=intersight_api_key_id,
api_secret_file=intersight_api_key,
endpoint=intersight_base_url
)
else:
api_client = preconfigured_api_client
try:
# Retrieve the Intersight Account name
api_client.call_api(resource_path="/iam/Accounts",
method="GET",
auth_settings=['cookieAuth', 'http_signature', 'oAuth2', 'oAuth2']
)
response = api_client.last_response.data
iam_account = json.loads(response)
if api_client.last_response.status != 200:
print("The provided Intersight account information could not be "
"accessed.")
print("Exiting due to the Intersight account being unavailable.\n")
print("Please verify that the correct API Key ID and API Key have "
"been entered, then re-attempt execution.\n")
sys.exit(0)
else:
intersight_account_name = iam_account["Results"][0]["Name"]
except Exception:
print("\nA configuration error has occurred!\n")
print("Unable to access the Intersight API.")
print("Exiting due to the Intersight API being unavailable.\n")
print("Please verify that the correct API Key ID and API Key have "
"been entered, then re-attempt execution.\n")
sys.exit(0)
# Retrieving the provided object from Intersight...
full_intersight_api_path = f"/{intersight_api_path}"
try:
api_client.call_api(resource_path=full_intersight_api_path,
method="GET",
auth_settings=['cookieAuth', 'http_signature', 'oAuth2', 'oAuth2']
)
response = api_client.last_response.data
intersight_objects = json.loads(response)
# The Intersight API resource path has been accessed successfully.
except Exception:
print("\nA configuration error has occurred!\n")
print("There was an issue retrieving the "
f"{object_type} from Intersight.")
print("Unable to access the provided Intersight API resource path "
f"'{intersight_api_path}'.")
print("Please review and resolve any error messages, then re-attempt "
"execution.\n")
print("Exception Message: ")
traceback.print_exc()
sys.exit(0)
if intersight_objects.get("Results"):
for intersight_object in intersight_objects.get("Results"):
if intersight_object.get("Organization"):
provided_organization_moid = intersight_object_moid_retriever(intersight_api_key_id=None,
intersight_api_key=None,
object_name=organization,
intersight_api_path="organization/Organizations",
object_type="Organization",
preconfigured_api_client=api_client
)
if intersight_object.get("Organization", {}).get("Moid") == provided_organization_moid:
if intersight_object.get("Name") == object_name:
intersight_object_moid = intersight_object.get("Moid")
# The provided object and MOID has been identified and retrieved.
return intersight_object_moid
else:
if intersight_object.get("Name") == object_name:
intersight_object_moid = intersight_object.get("Moid")
# The provided object and MOID has been identified and retrieved.
return intersight_object_moid
else:
print("\nA configuration error has occurred!\n")
print(f"The provided {object_type} named '{object_name}' was not "
"found.")
print("Please check the Intersight Account named "
f"{intersight_account_name}.")
print("Verify through the API or GUI that the needed "
f"{object_type} is present.")
print(f"If the needed {object_type} is missing, please create it.")
print("Once the issue has been resolved, re-attempt execution.\n")
sys.exit(0)
else:
print("\nA configuration error has occurred!\n")
print(f"The provided {object_type} named '{object_name}' was not "
"found.")
print(f"No requested {object_type} instance is currently available in "
f"the Intersight account named {intersight_account_name}.")
print("Please check the Intersight Account named "
f"{intersight_account_name}.")
print(f"Verify through the API or GUI that the needed {object_type} "
"is present.")
print(f"If the needed {object_type} is missing, please create it.")
print("Once the issue has been resolved, re-attempt execution.\n")
sys.exit(0)
# Establish function to retrieve all instances of a particular Intersight API object type
def get_intersight_objects(intersight_api_key_id,
intersight_api_key,
intersight_api_path,
object_type="object",
intersight_base_url="https://www.intersight.com/api/v1",
preconfigured_api_client=None
):
"""This is a function to perform an HTTP GET on all objects under an
available Intersight API type.
Args:
intersight_api_key_id (str):
The ID of the Intersight API key.
intersight_api_key (str):
The system file path of the Intersight API key.
intersight_api_path (str):
The path to the targeted Intersight API object type. For example,
to specify the Intersight API type for adapter configuration
policies, enter "adapter/ConfigPolicies". More API types can be
found in the Intersight API reference library at
https://intersight.com/apidocs/introduction/overview/.
object_type (str):
Optional; The type of Intersight object. The default value is
"object".
intersight_base_url (str):
Optional; The base URL for Intersight API paths. The default value
is "https://www.intersight.com/api/v1". This value typically only
needs to be changed if using the Intersight Virtual Appliance.
preconfigured_api_client ("ApiClient"):
Optional; An ApiClient class instance which handles
Intersight client-server communication through the use of API keys.
The default value is None. If a preconfigured_api_client argument
is provided, empty strings ("") or None can be provided for the
intersight_api_key_id, intersight_api_key, and intersight_base_url
arguments.
Returns:
A dictionary containing all objects of the specified API type. If the
API type is inaccessible, an implicit value of None will be returned.
Raises:
Exception:
An exception occurred due to an issue accessing the Intersight API
path. The status code or error message will be specified.
"""
# Define Intersight SDK ApiClient variable
if preconfigured_api_client is None:
api_client = get_api_client(api_key_id=intersight_api_key_id,
api_secret_file=intersight_api_key,
endpoint=intersight_base_url
)
else:
api_client = preconfigured_api_client
# Retrieving the provided object from Intersight...
full_intersight_api_path = f"/{intersight_api_path}"
try:
api_client.call_api(resource_path=full_intersight_api_path,
method="GET",
auth_settings=['cookieAuth', 'http_signature', 'oAuth2', 'oAuth2']
)
response = api_client.last_response.data
intersight_objects = json.loads(response)
# The Intersight API resource path has been accessed successfully.
return intersight_objects
except Exception:
print("\nA configuration error has occurred!\n")
print(f"There was an issue retrieving the requested {object_type} "
"instances from Intersight.")
print("Unable to access the provided Intersight API resource path "
f"'{intersight_api_path}'.")
print("Please review and resolve any error messages, then re-attempt "
"execution.\n")
print("Exception Message: ")
traceback.print_exc()
sys.exit(0)
# Establish function to retrieve a particular instance of a particular Intersight API object type
def get_single_intersight_object(intersight_api_key_id,
intersight_api_key,
intersight_api_path,
object_moid,
object_type="object",
intersight_base_url="https://www.intersight.com/api/v1",
preconfigured_api_client=None
):
"""This is a function to perform an HTTP GET on a single object under an
available Intersight API type.
Args:
intersight_api_key_id (str):
The ID of the Intersight API key.
intersight_api_key (str):
The system file path of the Intersight API key.
intersight_api_path (str):
The path to the targeted Intersight API object type. For example,
to specify the Intersight API type for adapter configuration
policies, enter "adapter/ConfigPolicies". More API types can be
found in the Intersight API reference library at
https://intersight.com/apidocs/introduction/overview/.
object_moid (str):
The MOID of the single Intersight object.
object_type (str):
Optional; The type of Intersight object. The default value is
"object".
intersight_base_url (str):
Optional; The base URL for Intersight API paths. The default value
is "https://www.intersight.com/api/v1". This value typically only
needs to be changed if using the Intersight Virtual Appliance.
preconfigured_api_client ("ApiClient"):
Optional; An ApiClient class instance which handles
Intersight client-server communication through the use of API keys.
The default value is None. If a preconfigured_api_client argument
is provided, empty strings ("") or None can be provided for the
intersight_api_key_id, intersight_api_key, and intersight_base_url
arguments.
Returns:
A dictionary containing all objects of the specified API type. If the
API type is inaccessible, an implicit value of None will be returned.
Raises:
Exception:
An exception occurred due to an issue accessing the Intersight API
path. The status code or error message will be specified.
"""
# Define Intersight SDK ApiClient variable
if preconfigured_api_client is None:
api_client = get_api_client(api_key_id=intersight_api_key_id,
api_secret_file=intersight_api_key,
endpoint=intersight_base_url
)
else:
api_client = preconfigured_api_client
# Retrieving the provided object from Intersight...
full_intersight_api_path = f"/{intersight_api_path}/{object_moid}"
try:
api_client.call_api(resource_path=full_intersight_api_path,
method="GET",
auth_settings=['cookieAuth', 'http_signature', 'oAuth2', 'oAuth2']
)
response = api_client.last_response.data
single_intersight_object = json.loads(response)
# The Intersight API resource path has been accessed successfully.
return single_intersight_object
except Exception:
print("\nA configuration error has occurred!\n")
print(f"There was an issue retrieving the requested {object_type} "
"instance from Intersight.")
print("Unable to access the provided Intersight API resource path "
f"'{intersight_api_path}'.")
print("Please review and resolve any error messages, then re-attempt "
"execution.\n")
print("Exception Message: ")
traceback.print_exc()
sys.exit(0)
# Establish Maker specific classes and functions
class UcsPolicy:
"""This class is used to configure a UCS Policy in Intersight.
"""
object_type = "UCS Policy"
intersight_api_path = None
subobject_types = None
subobject_attribute_maps = None
object_variable_value_maps = None
def __init__(self,
intersight_api_key_id,
intersight_api_key,
policy_name,
policy_description="",
organization="default",
intersight_base_url="https://www.intersight.com/api/v1",
tags=None,
preconfigured_api_client=None
):
self.intersight_api_key_id = intersight_api_key_id
self.intersight_api_key = intersight_api_key
self.policy_name = policy_name
self.policy_description = policy_description
self.organization = organization
self.intersight_base_url = intersight_base_url
if tags is None:
self.tags = {}
else:
self.tags = tags
if preconfigured_api_client is None:
self.api_client = get_api_client(api_key_id=intersight_api_key_id,
api_secret_file=intersight_api_key,
endpoint=intersight_base_url
)
else:
self.api_client = preconfigured_api_client
self.intersight_api_body = {
"Name": self.policy_name,
"Description": self.policy_description
}
def __repr__(self):
return (
f"{self.__class__.__name__}"
f"('{self.intersight_api_key_id}', "
f"'{self.intersight_api_key}', "
f"'{self.policy_name}', "
f"'{self.policy_description}', "
f"'{self.organization}', "
f"'{self.intersight_base_url}', "
f"{self.tags}, "
f"{self.api_client})"
)
def __str__(self):
return f"{self.__class__.__name__} class object for '{self.policy_name}'"
def _post_intersight_object(self):
"""This is a function to configure an Intersight object by
performing a POST through the Intersight API.
Returns:
A string with a statement indicating whether the POST method
was successful or failed.
Raises:
Exception:
An exception occurred while performing the API call.
The status code or error message will be specified.
"""
full_intersight_api_path = f"/{self.intersight_api_path}"
try:
self.api_client.call_api(resource_path=full_intersight_api_path,
method="POST",
body=self.intersight_api_body,
auth_settings=['cookieAuth', 'http_signature', 'oAuth2', 'oAuth2']
)
print(f"The configuration of the base {self.object_type} "
"has completed.")
return "The POST method was successful."
except intersight.exceptions.ApiException as error:
if error.status == 409:
existing_intersight_object_name = self.intersight_api_body.get("Name", "object")
print(f"The targeted {self.object_type} appears to already "
"exist.")
print("An attempt will be made to update the pre-existing "
f"{existing_intersight_object_name}...")
try:
existing_intersight_object_moid = intersight_object_moid_retriever(intersight_api_key_id=None,
intersight_api_key=None,
object_name=existing_intersight_object_name,
intersight_api_path=self.intersight_api_path,
object_type=self.object_type,
preconfigured_api_client=self.api_client
)
# Update full Intersight API path with the MOID of the existing object
full_intersight_api_path_with_moid = f"/{self.intersight_api_path}/{existing_intersight_object_moid}"
self.api_client.call_api(resource_path=full_intersight_api_path_with_moid,
method="POST",
body=self.intersight_api_body,
auth_settings=['cookieAuth', 'http_signature', 'oAuth2', 'oAuth2']
)
print(f"The update of the {self.object_type} has "
"completed.")
print(f"The pre-existing {existing_intersight_object_name} "
"has been updated.")
return "The POST method was successful."
except Exception:
print("\nA configuration error has occurred!\n")
print(f"Unable to update the {self.object_type} under the "
"Intersight API resource path "
f"'{full_intersight_api_path_with_moid}'.\n")
print(f"The pre-existing {existing_intersight_object_name} "
"could not be updated.")
print("Exception Message: ")
traceback.print_exc()
return "The POST method failed."
else:
print("\nA configuration error has occurred!\n")
print(f"Unable to configure the {self.object_type} under the "
"Intersight API resource path "
f"'{full_intersight_api_path}'.\n")
print("Exception Message: ")
traceback.print_exc()
return "The POST method failed."
except Exception:
print("\nA configuration error has occurred!\n")
print(f"Unable to configure the {self.object_type} under the "
"Intersight API resource path "
f"'{full_intersight_api_path}'.\n")
print("Exception Message: ")
traceback.print_exc()
return "The POST method failed."
def _update_api_body_general_attributes(self):
"""This function updates the Intersight API body with general
attributes for the Intersight object.
"""
# Retrieve the Intersight Organization MOID
policy_organization_moid = intersight_object_moid_retriever(intersight_api_key_id=None,
intersight_api_key=None,
object_name=self.organization,
intersight_api_path="organization/Organizations",
object_type="Organization",
preconfigured_api_client=self.api_client
)
# Update the API body with the Intersight Organization MOID
self.intersight_api_body["Organization"] = {"Moid": policy_organization_moid}
# Create the Intersight Tags dictionary list
tags_dictionary_list = []
if self.tags:
for key in self.tags:
tags_dictionary_list_entry = {
"Key": key,
"Value": self.tags.get(key)
}
tags_dictionary_list.append(tags_dictionary_list_entry)
# Update the API body with the Intersight Tags dictionary list
self.intersight_api_body["Tags"] = tags_dictionary_list
def _update_api_body_subobject_attributes(self):
"""This function updates the Intersight API body with individual
attributes for subobjects of the Intersight object.
Raises:
Exception:
An exception occurred while reformatting a provided value for
an attribute. The issue will likely be due to the provided
value not being in string format. Changing the value to string
format should resolve the exception.
"""
def attribute_map_handler(attribute_map_dictionary):
"""This is a function to handle attributes with a mismatch in the
Front-End Name and Back-End Name.
Args:
attribute_map_dictionary (dict):
A dictionary containing attribute data, including front-end
(GUI) to back-end (API) mapped values.
"""
# Establish default automatic insertion status of current attribute
automatic_insertion_of_attribute_value_performed = False
# Check if current attribute is mandatory
if attribute_map_dictionary.get("Mandatory"):
if not any(
attribute_name_key in
staged_subobject_dictionary for
attribute_name_key in
(attribute_map_dictionary["FrontEndName"],
attribute_map_dictionary["BackEndName"]
)
):
if attribute_map_dictionary.get("AutomaticInsertion"):
staged_subobject_dictionary[attribute_map_dictionary["BackEndName"]] = attribute_map_dictionary.get("AutomaticInsertionValue")
automatic_insertion_of_attribute_value_performed = True
else:
print("\nA configuration error has occurred!\n")
print("During the configuration of the "
f"{subobject_type_dictionary['Description']} "
f"settings for the {self.object_type} named "
f"{self.policy_name}, there was an issue "
"accessing the value for the "
f"{attribute_map_dictionary['Description']}.")
print("Please verify the following key exists in the "
"appropriate dictionary of the "
f"{subobject_type_dictionary['Description']} "
f"list variable for the {self.object_type}, then "
"re-attempt execution:\n")
if attribute_map_dictionary['FrontEndName']:
print(f"'{attribute_map_dictionary['FrontEndName']}'\n")
else:
print(f"'{attribute_map_dictionary['BackEndName']}'\n")
sys.exit(0)
# Check for attribute front-end name key in the dictionary
if attribute_map_dictionary["FrontEndName"] in staged_subobject_dictionary:
# If the attribute back-end name key is not present in the dictionary, insert the back-end name key with the front-end name key value
if attribute_map_dictionary["BackEndName"] not in staged_subobject_dictionary:
staged_subobject_dictionary[attribute_map_dictionary["BackEndName"]] = staged_subobject_dictionary.get(attribute_map_dictionary["FrontEndName"])
# Remove the front-end name key from the dictionary
staged_subobject_dictionary.pop(attribute_map_dictionary["FrontEndName"])
# Check for front-end to back-end value mapping
if attribute_map_dictionary.get("FronttoBackEndValueMaps"):
if (
attribute_map_dictionary["BackEndName"] in
staged_subobject_dictionary and
not automatic_insertion_of_attribute_value_performed
):
# Retrieve the provided attribute value
provided_attribute_value = staged_subobject_dictionary.get(attribute_map_dictionary["BackEndName"])
# Reformat the provided attribute value to lowercase and remove spaces to prevent potential format issues
try:
provided_attribute_value_reformatted = "".join(provided_attribute_value.lower().split())
except Exception:
print("\nA configuration error has occurred!\n")
print("During the configuration of the "
f"{subobject_type_dictionary['Description']} "
f"settings for the {self.object_type} named "
f"{self.policy_name}, there was an issue with "
"the value for the "
f"{attribute_map_dictionary['Description']}.")
print("The value provided was "
f"{provided_attribute_value}.")
print("Please verify that the value has been provided "
"in an accepted string format.")
print("Please review and resolve any error messages, "
"then re-attempt execution.\n")
sys.exit(0)
# Create list of known and mapped front-end to back-end values
front_to_backend_value_maps_key_list = list(attribute_map_dictionary["FronttoBackEndValueMaps"])
# Replace known and reformatted front-end value with known and mapped back-end value
if provided_attribute_value_reformatted in front_to_backend_value_maps_key_list:
provided_attribute_value_mapped = attribute_map_dictionary["FronttoBackEndValueMaps"][provided_attribute_value_reformatted]
staged_subobject_dictionary[attribute_map_dictionary["BackEndName"]] = provided_attribute_value_mapped
else:
print("\nWARNING: An unknown "
f"{attribute_map_dictionary['Description']} "
f"value of '{provided_attribute_value}' has been "
"provided for the "
f"{subobject_type_dictionary['Description']} "
"settings!")
print("An attempt will be made to configure the "
"unknown "
f"{attribute_map_dictionary['Description']} "
"value.")
print("If there is an error, please use one of the "
"following known values for the "
f"{attribute_map_dictionary['Description']}, "
"then re-attempt execution:\n")
print(*attribute_map_dictionary["FixedFrontEndValues"],
sep=", "
)
# Check for subobject types that may need configuration
if self.subobject_types:
for subobject_type_dictionary in self.subobject_types:
subobject_list = getattr(self,
subobject_type_dictionary.get("SubobjectList")
)
if subobject_list:
converted_subobject_list = []
for subobject_dictionary in subobject_list:
staged_subobject_dictionary = copy.deepcopy(subobject_dictionary)
returned_subobject_type = subobject_type_dictionary["SubobjectType"]
# Set 'ClassId' attribute
staged_subobject_dictionary["ClassId"] = returned_subobject_type
# Set 'ObjectType' attribute
staged_subobject_dictionary["ObjectType"] = returned_subobject_type
# Handle setting of attributes which have mismatched Front-End and Back-End names
for attribute_map_dictionary in self.subobject_attribute_maps.get(returned_subobject_type):
attribute_map_handler(attribute_map_dictionary)
converted_subobject_dictionary = staged_subobject_dictionary
converted_subobject_list.append(converted_subobject_dictionary)
# Update Intersight API body with the converted sub-objects list
self.intersight_api_body[subobject_type_dictionary["AttributeName"]] = converted_subobject_list
def _update_api_body_mapped_object_attributes(self):
"""This function updates the Intersight API body with individual
attributes that require mapping frontend to backend values for
compatibility with the Intersight API.
Raises:
Exception:
An exception occurred while reformatting a provided value for
an attribute. The issue will likely be due to the provided
value not being in string format. Changing the value to string
format should resolve the exception.
"""
# Check for object variables with value maps that need configuration
if self.object_variable_value_maps:
for object_variable in self.object_variable_value_maps:
# Create list of all known and accepted frontend values
all_known_and_accepted_frontend_values = (object_variable_value["FrontEndValue"]
for
object_variable_value
in
object_variable["Values"]
)
# Retrieve the user provided object variable value
provided_object_variable_value = getattr(self,
object_variable["VariableName"]
)
# Reformat the user provided object variable value to lowercase and remove spaces to prevent potential format issues
try:
reformatted_object_variable_value = "".join(provided_object_variable_value.lower().split())
except Exception:
print("\nA configuration error has occurred!\n")
print(f"During the configuration of the {self.object_type} named "
f"{self.policy_name}, there was an issue with the value "
f"provided for the {object_variable['Description']} setting.")
print(f"The value provided was {provided_object_variable_value}.")
print("To proceed, the value provided for the "
f"{object_variable['Description']} setting should be updated to "
"an accepted string format.")
print("The recommended values are the following:\n")
# Print list of all known and accepted frontend values for user
print(*all_known_and_accepted_frontend_values,
sep=", "
)
print("\nPlease update the configuration, then re-attempt "
"execution.\n")
sys.exit(0)
# Cycle through known values and match provided object variable value to backend value
for object_variable_value in object_variable["Values"]:
# Create list of all known and accepted frontend and backend values
current_known_frontend_and_backend_value_options = (object_variable_value.values())
# Retrieve the current known backend value
current_known_backend_value = object_variable_value["BackEndValue"]
if (
reformatted_object_variable_value
in
("".join(current_known_frontend_or_backend_value.lower().split())
for
current_known_frontend_or_backend_value
in
current_known_frontend_and_backend_value_options
)
):
backend_object_variable_value = current_known_backend_value
break
else:
# If no backend match is found with the user provided object variable value, pass on the user provided object variable value to Intersight to decide
print(f"\nWARNING: An unknown {self.object_type} value of "
f"'{provided_object_variable_value}' has been "
f"provided for the {object_variable['Description']} "
"settings!")
print("An attempt will be made to configure the unknown "
f"{object_variable['Description']} value.")
print("If there is an error, please use one of the "
"following known values for the "
f"{object_variable['Description']} settings, then "
"re-attempt execution:\n")
print(*all_known_and_accepted_frontend_values,
sep=", "
)
backend_object_variable_value = provided_object_variable_value
# Update Intersight API body with the converted object variable value
self.intersight_api_body[object_variable["AttributeName"]] = backend_object_variable_value
def object_maker(self):
"""This function makes the targeted policy object.
"""
print(f"\nConfiguring the {self.object_type} named "
f"{self.policy_name}...")
# Update the API body with general attributes
self._update_api_body_general_attributes()
# Update the API body with individual subobject attributes
self._update_api_body_subobject_attributes()
# Update the API body with individual mapped object attributes
self._update_api_body_mapped_object_attributes()
# POST the API body to Intersight
self._post_intersight_object()
class DirectlyAttachedUcsDomainPolicy(UcsPolicy):
"""This class is used to configure a UCS Domain Policy in Intersight that
is logically directly attached to UCS Fabric Interconnects through UCS
Domain Profiles.
"""
object_type = "Directly Attached UCS Domain Policy"
intersight_api_path = None
def __init__(self,
intersight_api_key_id,
intersight_api_key,
policy_name,
policy_description="",
organization="default",
intersight_base_url="https://www.intersight.com/api/v1",
tags=None,
preconfigured_api_client=None,
ucs_domain_profile_name="",
fabric_interconnect="AB"
):
super().__init__(intersight_api_key_id,
intersight_api_key,
policy_name,
policy_description,
organization,
intersight_base_url,
tags,
preconfigured_api_client
)
self.ucs_domain_profile_name = ucs_domain_profile_name
self.fabric_interconnect = fabric_interconnect
def __repr__(self):
return (
f"{self.__class__.__name__}"
f"('{self.intersight_api_key_id}', "
f"'{self.intersight_api_key}', "
f"'{self.policy_name}', "
f"'{self.policy_description}', "
f"'{self.organization}', "
f"'{self.intersight_base_url}', "
f"{self.tags}, "
f"{self.api_client}, "
f"'{self.ucs_domain_profile_name}', "
f"'{self.fabric_interconnect}')"
)
def _attach_ucs_domain_profile(self):
"""This is a function to attach an Intersight UCS Domain Profile to an
Intersight Policy.
Returns:
A dictionary for the API body of the policy object to be posted on
Intersight.
"""
# Attach UCS Domain Profile
if self.ucs_domain_profile_name:
print("Attaching the UCS Domain Profile named "
f"{self.ucs_domain_profile_name}...")
# Get UCS Domain Profile MOID
ucs_domain_profile_moid = intersight_object_moid_retriever(intersight_api_key_id=None,
intersight_api_key=None,
object_name=self.ucs_domain_profile_name,
intersight_api_path="fabric/SwitchClusterProfiles",
object_type="UCS Domain Profile",
organization=self.organization,
preconfigured_api_client=self.api_client
)
# Get UCS Domain Profile object dictionary attributes
ucs_domain_profile_object = get_single_intersight_object(intersight_api_key_id=None,
intersight_api_key=None,
intersight_api_path="fabric/SwitchClusterProfiles",
object_moid=ucs_domain_profile_moid,
object_type="UCS Domain Profile",
preconfigured_api_client=self.api_client
)
# Get Switch Profiles that are attached to the UCS Domain Profile
ucs_domain_profile_list_of_attached_switch_profiles = ucs_domain_profile_object.get("SwitchProfiles")