forked from nutanixdev/code-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_image_v2.0.py
More file actions
executable file
·99 lines (87 loc) · 3.54 KB
/
Copy pathcreate_image_v2.0.py
File metadata and controls
executable file
·99 lines (87 loc) · 3.54 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
'''
use the Prism REST API v2.0 to create an Image Services image
without modification, the script will create an image sourced from any HTTP-accessible URL
'''
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['cluster_ip']}:9440/api/nutanix/v2.0/images"
# setup the JSON payload that will be used for this request
payload = f'{{ \
"annotation":"{json_data["""image_annotation"""]}", \
"image_import_spec":{{ \
"storage_container_name":"{json_data["""ctr_name"""]}", \
"storage_container_uuid":"{json_data["""ctr_uuid"""]}", \
"url":"{json_data["""iso_url"""]}" \
}}, \
"image_type":"ISO_IMAGE", \
"name":"{json_data["""image_name"""]}" \
}}'
'''
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["cluster_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["cluster_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.')