/
deploy_ovf.py
executable file
·218 lines (187 loc) · 7.17 KB
/
deploy_ovf.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
#!/usr/bin/env python
"""
Written by Tony Allen
Github: https://github.com/stormbeard
Blog: https://stormbeard.net/
This code has been released under the terms of the Apache 2 licenses
http://www.apache.org/licenses/LICENSE-2.0.html
Script to deploy VM via a single .ovf and a single .vmdk file.
"""
from os import system, path
from sys import exit
from threading import Thread
from time import sleep
from argparse import ArgumentParser
from getpass import getpass
from pyVim import connect
from pyVmomi import vim
def get_args():
"""
Get CLI arguments.
"""
parser = ArgumentParser(description='Arguments for talking to vCenter')
parser.add_argument('-s', '--host',
required=True,
action='store',
help='vSphere service to connect to.')
parser.add_argument('-o', '--port',
type=int,
default=443,
action='store',
help='Port to connect on.')
parser.add_argument('-u', '--user',
required=True,
action='store',
help='Username to use.')
parser.add_argument('-p', '--password',
required=False,
action='store',
help='Password to use.')
parser.add_argument('--datacenter_name',
required=False,
action='store',
default=None,
help='Name of the Datacenter you\
wish to use. If omitted, the first\
datacenter will be used.')
parser.add_argument('--datastore_name',
required=False,
action='store',
default=None,
help='Datastore you wish the VM to be deployed to. \
If left blank, VM will be put on the first \
datastore found.')
parser.add_argument('--cluster_name',
required=False,
action='store',
default=None,
help='Name of the cluster you wish the VM to\
end up on. If left blank the first cluster found\
will be used')
parser.add_argument('-v', '--vmdk_path',
required=True,
action='store',
default=None,
help='Path of the VMDK file to deploy.')
parser.add_argument('-f', '--ovf_path',
required=True,
action='store',
default=None,
help='Path of the OVF file to deploy.')
args = parser.parse_args()
if not args.password:
args.password = getpass(prompt='Enter password: ')
return args
def get_ovf_descriptor(ovf_path):
"""
Read in the OVF descriptor.
"""
if path.exists(ovf_path):
with open(ovf_path, 'r') as f:
try:
ovfd = f.read()
f.close()
return ovfd
except:
print "Could not read file: %s" % ovf_path
exit(1)
def get_obj_in_list(obj_name, obj_list):
"""
Gets an object out of a list (obj_list) whos name matches obj_name.
"""
for o in obj_list:
if o.name == obj_name:
return o
print("Unable to find object by the name of %s in list:\n%s" %
(obj_name, map(lambda o: o.name, obj_list)))
exit(1)
def get_objects(si, args):
"""
Return a dict containing the necessary objects for deployment.
"""
# Get datacenter object.
datacenter_list = si.content.rootFolder.childEntity
if args.datacenter_name:
datacenter_obj = get_obj_in_list(args.datacenter_name, datacenter_list)
else:
datacenter_obj = datacenter_list[0]
# Get datastore object.
datastore_list = datacenter_obj.datastoreFolder.childEntity
if args.datastore_name:
datastore_obj = get_obj_in_list(args.datastore_name, datastore_list)
elif len(datastore_list) > 0:
datastore_obj = datastore_list[0]
else:
print "No datastores found in DC (%s)." % datacenter_obj.name
# Get cluster object.
cluster_list = datacenter_obj.hostFolder.childEntity
if args.cluster_name:
cluster_obj = get_obj_in_list(args.cluster_name, cluster_list)
elif len(cluster_list) > 0:
cluster_obj = cluster_list[0]
else:
print "No clusters found in DC (%s)." % datacenter_obj.name
# Generate resource pool.
resource_pool_obj = cluster_obj.resourcePool
return {"datacenter": datacenter_obj,
"datastore": datastore_obj,
"resource pool": resource_pool_obj}
def keep_lease_alive(lease):
"""
Keeps the lease alive while POSTing the VMDK.
"""
while(True):
sleep(5)
try:
# Choosing arbitrary percentage to keep the lease alive.
lease.HttpNfcLeaseProgress(50)
if (lease.state == vim.HttpNfcLease.State.done):
return
# If the lease is released, we get an exception.
# Returning to kill the thread.
except:
return
def main():
args = get_args()
ovfd = get_ovf_descriptor(args.ovf_path)
try:
si = connect.SmartConnect(host=args.host,
user=args.user,
pwd=args.password,
port=args.port)
except:
print "Unable to connect to %s" % args.host
exit(1)
objs = get_objects(si, args)
manager = si.content.ovfManager
spec_params = vim.OvfManager.CreateImportSpecParams()
import_spec = manager.CreateImportSpec(ovfd,
objs["resource pool"],
objs["datastore"],
spec_params)
lease = objs["resource pool"].ImportVApp(import_spec.importSpec,
objs["datacenter"].vmFolder)
while(True):
if (lease.state == vim.HttpNfcLease.State.ready):
# Assuming single VMDK.
url = lease.info.deviceUrl[0].url.replace('*', args.host)
# Spawn a dawmon thread to keep the lease active while POSTing
# VMDK.
keepalive_thread = Thread(target=keep_lease_alive, args=(lease,))
keepalive_thread.start()
# POST the VMDK to the host via curl. Requests library would work
# too.
curl_cmd = (
"curl -Ss -X POST --insecure -T %s -H 'Content-Type: \
application/x-vnd.vmware-streamVmdk' %s" %
(args.vmdk_path, url))
system(curl_cmd)
lease.HttpNfcLeaseComplete()
keepalive_thread.join()
return 0
elif (lease.state == vim.HttpNfcLease.State.error):
print "Lease error: " + lease.state.error
exit(1)
connect.Disconnect(si)
if __name__ == "__main__":
exit(main())