-
Notifications
You must be signed in to change notification settings - Fork 8
/
gcloud_util.py
103 lines (89 loc) · 3.16 KB
/
gcloud_util.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
import os
import time
import googleapiclient.discovery
def list_instances(compute, project, zone):
result = compute.instances().list(project=project, zone=zone).execute()
return result["items"] if "items" in result else None
def create_instance(compute, project, zone, name):
# Get the latest Debian Jessie image.
image_response = (
compute.images()
.getFromFamily(project="debian-cloud", family="debian-9")
.execute()
)
source_disk_image = image_response["selfLink"]
# Configure the machine
machine_type = "zones/%s/machineTypes/n1-standard-1" % zone
# startup_script = open(
# os.path.join(
# os.path.dirname(__file__), 'startup-script.sh'), 'r').read()
# image_url = "http://storage.googleapis.com/gce-demo-input/photo.jpg"
# image_caption = "Ready for dessert?"
config = {
"name": name,
"machineType": machine_type,
# Specify the boot disk and the image to use as a source.
"disks": [
{
"boot": True,
"autoDelete": True,
"initializeParams": {
"sourceImage": source_disk_image,
"diskSizeGb": "40",
},
}
],
# Specify a network interface with NAT to access the public
# internet.
"networkInterfaces": [
{
"network": "global/networks/default",
"accessConfigs": [{"type": "ONE_TO_ONE_NAT", "name": "External NAT"}],
}
],
# Allow the instance to access cloud storage and logging.
"serviceAccounts": [
{
"email": "default",
"scopes": ["https://www.googleapis.com/auth/cloud-platform"],
}
],
# Metadata is readable from the instance and allows you to
# pass configuration from deployment scripts to instances.
# 'metadata': {
# 'items': [{
# # Startup script is automatically executed by the
# # instance upon startup.
# 'key': 'startup-script',
# 'value': startup_script
# }, {
# 'key': 'url',
# 'value': image_url
# }, {
# 'key': 'text',
# 'value': image_caption
# }, {
# 'key': 'bucket',
# 'value': bucket
# }]
# }
}
return compute.instances().insert(project=project, zone=zone, body=config).execute()
def delete_instance(compute, project, zone, name):
return (
compute.instances().delete(project=project, zone=zone, instance=name).execute()
)
def wait_for_operation(compute, project, zone, operation):
print("Waiting for operation to finish...")
while True:
result = (
compute.zoneOperations()
.get(project=project, zone=zone, operation=operation)
.execute()
)
if result["status"] == "DONE":
print("done.")
if "error" in result:
raise Exception(result["error"])
return result
time.sleep(1)