-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcategories.py
166 lines (146 loc) · 5.49 KB
/
categories.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
"""
use the Prism REST API v3 to create Prism Central Categories
"""
import requests
import urllib3
import json
import os
import sys
from dotenv import load_dotenv
from pathlib import Path
from requests.auth import HTTPBasicAuth
def main():
"""
main entry point into the 'app'
every function needs a Docstring in order to follow best
practices
"""
# load the script configuration
env_path = Path(".") / ".env"
load_dotenv(dotenv_path=env_path)
PC_IP = os.getenv("PC_IP")
PC_PORT = os.getenv("PC_PORT")
PC_USERNAME = os.getenv("PC_USERNAME")
PC_PASSWORD = os.getenv("PC_PASSWORD")
print(f"Prism Central IP: {PC_IP}")
print(f"Prism Central Port: {PC_PORT}")
"""
disable insecure connection warnings
please be advised and aware of the implications of doing this
in a production environment!
"""
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# setup a variable that can be used to store our JSON configuration
raw_json = {}
# grab and decode the category details from the included JSON file
with open("./categories.json", "r") as f:
raw_json = json.loads(f.read())
# start building the BATCH request
print(
"Building the BATCH request payload that will " "create the category keys ..."
)
batch_payload = {
"action_on_failure": "CONTINUE",
"execution_order": "SEQUENTIAL",
"api_request_list": [],
"api_version": "3.1",
}
for key in raw_json["categories"][0]["keys"]:
# do something with the keys here
# probably use the API to create the keys, as shown below
category_key_payload = {
"operation": "PUT",
"path_and_params": f"/api/nutanix/v3/categories/{key}",
"body": {
"name": key,
"description": key,
"capabilities": {"cardinality": 64},
"api_version": "3.1",
},
}
# add the new API request to the batch payload's BODY
batch_payload["api_request_list"].append(category_key_payload)
# submit the BATCH request that will create the category keys
print("Creating the category keys via API BATCH request ...")
endpoint = f"https://{PC_IP}:{PC_PORT}/api/nutanix/v3/batch"
request_headers = {"Content-Type": "application/json", "charset": "utf-8"}
# submit the BATCH request that will create the category keys
try:
results = requests.post(
endpoint,
data=json.dumps(batch_payload),
headers=request_headers,
verify=False,
auth=HTTPBasicAuth(PC_USERNAME, PC_PASSWORD),
)
# check the results of the request
print(f"BATCH request HTTP status code: {results.status_code}")
json_response = results.json()
print(
f"There are {len(json_response['api_response_list'])} "
"responses from this request."
)
for response in json_response["api_response_list"]:
print(
f"Response code: {response['status']} | "
f"path_and_params: {response['path_and_params']}"
)
except Exception as error:
print(f"An unhandled exception has occurred: {error}")
print(f"Exception: {error.__class__.__name__}")
sys.exit()
# start building the next BATCH request
print("Building the BATCH request payload that will create the category values ...")
batch_payload = {
"action_on_failure": "CONTINUE",
"execution_order": "SEQUENTIAL",
"api_request_list": [],
"api_version": "3.1",
}
for value in raw_json["categories"][0]["values"]:
# do something with the values here
# probably use the API to create values, as shown below
category_value_payload = {
"operation": "PUT",
"path_and_params": "/api/nutanix/v3/categories/"
f"{value['key']}/{value['value']}",
"body": {
"value": value["value"],
"description": value["value"],
"assignment_rule": {
"name": "assignment rule name created by API",
"description": "assignment rule value created by API",
"selection_criteria_list": [],
},
"api_version": "3.1",
},
}
# add the new API request to the batch payload's BODY
batch_payload["api_request_list"].append(category_value_payload)
# submit the BATCH request that will create the category keys
try:
results = requests.post(
endpoint,
data=json.dumps(batch_payload),
headers=request_headers,
verify=False,
auth=HTTPBasicAuth(PC_USERNAME, PC_PASSWORD),
)
# check the results of the request
print(f"BATCH request HTTP status code: {results.status_code}")
json_response = results.json()
print(
f"There are {len(json_response['api_response_list'])} "
"responses from this request."
)
for response in json_response["api_response_list"]:
print(
f"Response code: {response['status']} | "
f"path_and_params: {response['path_and_params']}"
)
except Exception as error:
print(f"An unhandled exception has occurred: {error}")
print(f"Exception: {error.__class__.__name__}")
sys.exit()
if __name__ == "__main__":
main()