forked from nutanixdev/code-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_vm_v3_basic.py
More file actions
executable file
·121 lines (108 loc) · 3.85 KB
/
create_vm_v3_basic.py
File metadata and controls
executable file
·121 lines (108 loc) · 3.85 KB
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
'''
use the Prism REST API v3 to create a simple VM
'''
import requests
import urllib3
import argparse
import getpass
import json
from base64 import b64encode
import sys
import os
'''
suppress warnings about insecure connections
you probably shouldn't do this in production
'''
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
'''
setup our command line parameters
for this example we only require the a single parameter
- the name of the JSON file that contains our request parameters
this is a very clean way of passing parameters to this sort of
script, without the need for excessive parameters on the command line
'''
parser = argparse.ArgumentParser()
parser.add_argument('json',
help='JSON file containing query parameters')
args = parser.parse_args()
'''
try and read the JSON parameters from the supplied file
'''
json_data = ''
try:
script_dir = os.path.dirname(os.path.realpath(__file__))
with open(f'{script_dir}/{args.json}', 'r') as params:
json_data = json.load(params)
except FileNotFoundError:
print(f'{args.json} parameters file not found.')
sys.exit()
except json.decoder.JSONDecodeError:
print(f'{args.json} does not appear to contain valid JSON. \
Please check the file and try again.')
sys.exit()
# get the cluster password
cluster_password = getpass.getpass(prompt='Please enter your cluster \
password: ', stream=None)
try:
'''
setup the HTTP Basic Authorization header based on the
supplied username and password
done this way so that passwords are not supplied on the command line
'''
encoded_credentials = b64encode(bytes(
f'{json_data["username"]}:{cluster_password}',
encoding='ascii')).decode('ascii')
auth_header = f'Basic {encoded_credentials}'
# setup the URL that will be used for the API request
url = f'https://{json_data["pc_ip"]}:9440/api/nutanix/v3/vms'
# setup the JSON payload that will be used for this request
payload = f'{{ \
"spec":{{ \
"name":"{json_data["""vm_name"""]}", \
"resources":{{ \
}}, \
"cluster_reference":{{ \
"kind":"cluster", \
"name":"{json_data["""cluster_name"""]}", \
"uuid":"{json_data["""cluster_uuid"""]}" \
}}\
}}, \
"metadata":{{ \
"kind":"vm" \
}} \
}}'
'''
setup the request headers
note the use of {auth_header} i.e. the Basic Authorization
credentials we setup earlier
'''
headers = {
'Accept': "application/json",
'Content-Type': "application/json",
'Authorization': f"{auth_header}",
'cache-control': "no-cache"
}
# submit the request
try:
response = requests.request("POST", url, data=payload, headers=headers,
verify=False)
if(response.ok):
print(response.text)
else:
print(f'An error occurred while connecting to {json_data["pc_ip"]}.')
'''
the following line can be uncommented to show
detailed error information
'''
print(response.text)
except Exception as ex:
print(f'An {type(ex).__name__} exception occurred while \
connecting to {json_data["pc_ip"]}.\nArgument: {ex.args}.')
except KeyError:
print(f'{args.json} file does not appear to contain the required \
fields. Please check the file and try again.')
'''
wait for the enter key before continuing
this is to prevent terminal flashing if being run inside VS Code, for example
'''
input('Press ENTER to exit.')