This repository has been archived by the owner on Dec 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathsample_create_vm.py
421 lines (352 loc) · 16.9 KB
/
sample_create_vm.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from typing import List
# [START compute_instances_create_with_subnet]
# [START compute_instances_create_from_image_plus_snapshot_disk]
# [START compute_instances_create_from_snapshot]
# [START compute_instances_create_from_image_plus_empty_disk]
# [START compute_instances_create_from_custom_image]
# [START compute_instances_create_from_image ]
from google.cloud import compute_v1
# [END compute_instances_create_from_image ]
# [END compute_instances_create_from_custom_image]
# [END compute_instances_create_from_image_plus_empty_disk]
# [END compute_instances_create_from_snapshot]
# [END compute_instances_create_from_image_plus_snapshot_disk]
# [END compute_instances_create_with_subnet]
# [START compute_instances_create_with_subnet]
# [START compute_instances_create_from_image_plus_snapshot_disk]
# [START compute_instances_create_from_image_plus_empty_disk]
# [START compute_instances_create_from_custom_image]
# [START compute_instances_create_from_image]
def disk_from_image(
disk_type: str, disk_size_gb: int, boot: bool, source_image: str
) -> compute_v1.AttachedDisk:
"""
Create an AttachedDisk object to be used in VM instance creation. Uses an image as the
source for the new disk.
Args:
disk_type: the type of disk you want to create. This value uses the following format:
"zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".
For example: "zones/us-west3-b/diskTypes/pd-ssd"
disk_size_gb: size of the new disk in gigabytes
boot: boolean flag indicating whether this disk should be used as a boot disk of an instance
source_image: source image to use when creating this disk. You must have read access to this disk. This can be one
of the publicly available images or an image from one of your projects.
This value uses the following format: "projects/{project_name}/global/images/{image_name}"
Returns:
AttachedDisk object configured to be created using the specified image.
"""
boot_disk = compute_v1.AttachedDisk()
initialize_params = compute_v1.AttachedDiskInitializeParams()
initialize_params.source_image = source_image
initialize_params.disk_size_gb = disk_size_gb
initialize_params.disk_type = disk_type
boot_disk.initialize_params = initialize_params
# Remember to set auto_delete to True if you want the disk to be deleted when you delete
# your VM instance.
boot_disk.auto_delete = True
boot_disk.boot = boot
return boot_disk
# [END compute_instances_create_from_image]
# [END compute_instances_create_from_custom_image]
# [END compute_instances_create_from_image_plus_empty_disk]
# [END compute_instances_create_from_image_plus_snapshot_disk]
# [END compute_instances_create_with_subnet]
# [START compute_instances_create_from_image_plus_empty_disk]
def empty_disk(disk_type: str, disk_size_gb: int) -> compute_v1.AttachedDisk():
"""
Create an AttachedDisk object to be used in VM instance creation. The created disk contains
no data and requires formatting before it can be used.
Args:
disk_type: the type of disk you want to create. This value uses the following format:
"zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".
For example: "zones/us-west3-b/diskTypes/pd-ssd"
disk_size_gb: size of the new disk in gigabytes
Returns:
AttachedDisk object configured to be created as an empty disk.
"""
disk = compute_v1.AttachedDisk()
initialize_params = compute_v1.AttachedDiskInitializeParams()
initialize_params.disk_type = disk_type
initialize_params.disk_size_gb = disk_size_gb
disk.initialize_params = initialize_params
# Remember to set auto_delete to True if you want the disk to be deleted when you delete
# your VM instance.
disk.auto_delete = True
disk.boot = False
return disk
# [END compute_instances_create_from_image_plus_empty_disk]
# [START compute_instances_create_from_image_plus_snapshot_disk]
# [START compute_instances_create_from_snapshot]
def disk_from_snapshot(
disk_type: str, disk_size_gb: int, boot: bool, disk_snapshot: str
) -> compute_v1.AttachedDisk():
"""
Create an AttachedDisk object to be used in VM instance creation. Uses a disk snapshot as the
source for the new disk.
Args:
disk_type: the type of disk you want to create. This value uses the following format:
"zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".
For example: "zones/us-west3-b/diskTypes/pd-ssd"
disk_size_gb: size of the new disk in gigabytes
boot: boolean flag indicating whether this disk should be used as a boot disk of an instance
disk_snapshot: disk snapshot to use when creating this disk. You must have read access to this disk.
This value uses the following format: "projects/{project_name}/global/snapshots/{snapshot_name}"
Returns:
AttachedDisk object configured to be created using the specified snapshot.
"""
disk = compute_v1.AttachedDisk()
initialize_params = compute_v1.AttachedDiskInitializeParams()
initialize_params.source_snapshot = disk_snapshot
initialize_params.disk_type = disk_type
initialize_params.disk_size_gb = disk_size_gb
disk.initialize_params = initialize_params
# Remember to set auto_delete to True if you want the disk to be deleted when you delete
# your VM instance.
disk.auto_delete = True
disk.boot = boot
return disk
# [END compute_instances_create_from_snapshot]
# [END compute_instances_create_from_image_plus_snapshot_disk]
# [START compute_instances_create_with_subnet]
# [START compute_instances_create_from_image_plus_snapshot_disk]
# [START compute_instances_create_from_snapshot]
# [START compute_instances_create_from_image_plus_empty_disk]
# [START compute_instances_create_from_custom_image]
# [START compute_instances_create_from_image]
def create_with_disks(
project_id: str,
zone: str,
instance_name: str,
disks: List[compute_v1.AttachedDisk],
machine_type: str = "n1-standard-1",
network_link: str = "global/networks/default",
subnetwork_link: str = None,
) -> compute_v1.Instance:
"""
Send an instance creation request to the Compute Engine API and wait for it to complete.
Args:
project_id: project ID or project number of the Cloud project you want to use.
zone: name of the zone to create the instance in. For example: "us-west3-b"
instance_name: name of the new virtual machine (VM) instance.
machine_type: machine type of the VM being created. This value uses the
following format: "zones/{zone}/machineTypes/{type_name}".
For example: "zones/europe-west3-c/machineTypes/f1-micro"
disks: a list of compute_v1.AttachedDisk objects describing the disks
you want to attach to your new instance.
network_link: name of the network you want the new instance to use.
For example: "global/networks/default" represents the network
named "default", which is created automatically for each project.
subnetwork_link: name of the subnetwork you want the new instance to use.
This value uses the following format:
"regions/{region}/subnetworks/{subnetwork_name}"
Returns:
Instance object.
"""
instance_client = compute_v1.InstancesClient()
operation_client = compute_v1.ZoneOperationsClient()
# Use the network interface provided in the network_link argument.
network_interface = compute_v1.NetworkInterface()
network_interface.name = network_link
if subnetwork_link:
network_interface.subnetwork = subnetwork_link
# Collect information into the Instance object.
instance = compute_v1.Instance()
instance.name = instance_name
instance.disks = disks
full_machine_type_name = f"zones/{zone}/machineTypes/{machine_type}"
instance.machine_type = full_machine_type_name
instance.network_interfaces = [network_interface]
# Shielded Instance settings
# Values presented here are the defaults.
# instance.shielded_instance_config = compute_v1.ShieldedInstanceConfig()
# instance.shielded_instance_config.enable_secure_boot = False
# instance.shielded_instance_config.enable_vtpm = True
# instance.shielded_instance_config.enable_integrity_monitoring = True
# Prepare the request to insert an instance.
request = compute_v1.InsertInstanceRequest()
request.zone = zone
request.project = project_id
request.instance_resource = instance
# Wait for the create operation to complete.
print(f"Creating the {instance_name} instance in {zone}...")
operation = instance_client.insert(request=request)
while operation.status != compute_v1.Operation.Status.DONE:
operation = operation_client.wait(
operation=operation.name, zone=zone, project=project_id
)
if operation.error:
print("Error during creation:", operation.error, file=sys.stderr)
if operation.warnings:
print("Warning during creation:", operation.warnings, file=sys.stderr)
print(f"Instance {instance_name} created.")
return instance
# [END compute_instances_create_from_image]
# [END compute_instances_create_from_custom_image]
# [END compute_instances_create_from_image_plus_empty_disk]
# [END compute_instances_create_from_snapshot]
# [END compute_instances_create_from_image_plus_snapshot_disk]
# [END compute_instances_create_with_subnet]
# [START compute_instances_create_from_image]
def create_from_public_image(project_id: str, zone: str, instance_name: str):
"""
Create a new VM instance with Debian 10 operating system.
Args:
project_id: project ID or project number of the Cloud project you want to use.
zone: name of the zone to create the instance in. For example: "us-west3-b"
instance_name: name of the new virtual machine (VM) instance.
Returns:
Instance object.
"""
image_client = compute_v1.ImagesClient()
# List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-details
newest_debian = image_client.get_from_family(
project="debian-cloud", family="debian-10"
)
disk_type = f"zones/{zone}/diskTypes/pd-standard"
disks = [disk_from_image(disk_type, 10, True, newest_debian.self_link)]
instance = create_with_disks(project_id, zone, instance_name, disks)
return instance
# [END compute_instances_create_from_image]
# [START compute_instances_create_from_custom_image]
def create_from_custom_image(
project_id: str, zone: str, instance_name: str, custom_image_link: str
):
"""
Create a new VM instance with custom image used as its boot disk.
Args:
project_id: project ID or project number of the Cloud project you want to use.
zone: name of the zone to create the instance in. For example: "us-west3-b"
instance_name: name of the new virtual machine (VM) instance.
custom_image_link: link to the custom image you want to use in the form of:
"projects/{project_name}/global/images/{image_name}"
Returns:
Instance object.
"""
disk_type = f"zones/{zone}/diskTypes/pd-standard"
disks = [disk_from_image(disk_type, 10, True, custom_image_link)]
instance = create_with_disks(project_id, zone, instance_name, disks)
return instance
# [END compute_instances_create_from_custom_image]
# [START compute_instances_create_from_image_plus_empty_disk]
def create_with_additional_disk(project_id: str, zone: str, instance_name: str):
"""
Create a new VM instance with Debian 10 operating system and a 11 GB additional
empty disk.
Args:
project_id: project ID or project number of the Cloud project you want to use.
zone: name of the zone to create the instance in. For example: "us-west3-b"
instance_name: name of the new virtual machine (VM) instance.
Returns:
Instance object.
"""
image_client = compute_v1.ImagesClient()
# List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-details
newest_debian = image_client.get_from_family(
project="debian-cloud", family="debian-10"
)
disk_type = f"zones/{zone}/diskTypes/pd-standard"
disks = [
disk_from_image(disk_type, 10, True, newest_debian.self_link),
empty_disk(disk_type, 11),
]
instance = create_with_disks(project_id, zone, instance_name, disks)
return instance
# [END compute_instances_create_from_image_plus_empty_disk]
# [START compute_instances_create_from_snapshot]
def create_from_snapshot(
project_id: str, zone: str, instance_name: str, snapshot_link: str
):
"""
Create a new VM instance with Debian 10 operating system.
Args:
project_id: project ID or project number of the Cloud project you want to use.
zone: name of the zone to create the instance in. For example: "us-west3-b"
instance_name: name of the new virtual machine (VM) instance.
snapshot_link: link to the snapshot you want to use as the source of your
boot disk in the form of: "projects/{project_name}/global/snapshots/{snapshot_name}"
Returns:
Instance object.
"""
disk_type = f"zones/{zone}/diskTypes/pd-standard"
disks = [disk_from_snapshot(disk_type, 11, True, snapshot_link)]
instance = create_with_disks(project_id, zone, instance_name, disks)
return instance
# [END compute_instances_create_from_snapshot]
# [START compute_instances_create_from_image_plus_snapshot_disk]
def create_with_snapshotted_data_disk(
project_id: str, zone: str, instance_name: str, snapshot_link: str
):
"""
Create a new VM instance with Debian 10 operating system.
Args:
project_id: project ID or project number of the Cloud project you want to use.
zone: name of the zone to create the instance in. For example: "us-west3-b"
instance_name: name of the new virtual machine (VM) instance.
snapshot_link: link to the snapshot you want to use as the source of your
data disk in the form of: "projects/{project_name}/global/snapshots/{snapshot_name}"
Returns:
Instance object.
"""
image_client = compute_v1.ImagesClient()
# List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-details
newest_debian = image_client.get_from_family(
project="debian-cloud", family="debian-10"
)
disk_type = f"zones/{zone}/diskTypes/pd-standard"
disks = [
disk_from_image(disk_type, 10, True, newest_debian.self_link),
disk_from_snapshot(disk_type, 11, False, snapshot_link),
]
instance = create_with_disks(project_id, zone, instance_name, disks)
return instance
# [END compute_instances_create_from_image_plus_snapshot_disk]
# [START compute_instances_create_with_subnet]
def create_with_subnet(
project_id: str, zone: str, instance_name: str, network_link: str, subnet_link: str
):
"""
Create a new VM instance with Debian 10 operating system in specified network and subnetwork.
Args:
project_id: project ID or project number of the Cloud project you want to use.
zone: name of the zone to create the instance in. For example: "us-west3-b"
instance_name: name of the new virtual machine (VM) instance.
network_link: name of the network you want the new instance to use.
For example: "global/networks/default" represents the network
named "default", which is created automatically for each project.
subnetwork_link: name of the subnetwork you want the new instance to use.
This value uses the following format:
"regions/{region}/subnetworks/{subnetwork_name}"
Returns:
Instance object.
"""
image_client = compute_v1.ImagesClient()
# List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-details
newest_debian = image_client.get_from_family(
project="debian-cloud", family="debian-10"
)
disk_type = f"zones/{zone}/diskTypes/pd-standard"
disks = [disk_from_image(disk_type, 10, True, newest_debian.self_link)]
instance = create_with_disks(
project_id,
zone,
instance_name,
disks,
network_link=network_link,
subnetwork_link=subnet_link,
)
return instance
# [END compute_instances_create_with_subnet]