Skip to content

Commit 781e792

Browse files
docs(samples): Adding samples for image creation and deletion (#270)
* chore(samples): Create image function Co-authored-by: Anthonios Partheniou <[email protected]>
1 parent ce1816e commit 781e792

File tree

7 files changed

+448
-0
lines changed

7 files changed

+448
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# Copyright 2022 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
16+
# This is an ingredient file. It is not meant to be run directly. Check the samples/snippets
17+
# folder for complete code samples that are ready to be used.
18+
# Disabling flake8 for the ingredients file, as it would fail F821 - undefined name check.
19+
# flake8: noqa
20+
import time
21+
22+
from google.cloud import compute_v1
23+
import warnings
24+
25+
# <INGREDIENT create_image>
26+
STOPPED_MACHINE_STATUS = (
27+
compute_v1.Instance.Status.TERMINATED.name,
28+
compute_v1.Instance.Status.STOPPED.name
29+
)
30+
31+
32+
def create_image(project_id: str, zone: str, source_disk_name: str, image_name: str,
33+
storage_location: str = None, force_create: bool = False) -> compute_v1.Image:
34+
"""
35+
Creates a new disk image.
36+
37+
Args:
38+
project_id: project ID or project number of the Cloud project you use.
39+
zone: zone of the disk you copy from.
40+
source_disk_name: name of the source disk you copy from.
41+
image_name: name of the image you want to create.
42+
storage_location: storage location for the image. If the value is undefined,
43+
function will store the image in the multi-region closest to your image's
44+
source location.
45+
force_create: create the image even if the source disk is attached to a
46+
running instance.
47+
"""
48+
image_client = compute_v1.ImagesClient()
49+
disk_client = compute_v1.DisksClient()
50+
instance_client = compute_v1.InstancesClient()
51+
52+
# Get source disk
53+
disk = disk_client.get(project=project_id, zone=zone, disk=source_disk_name)
54+
55+
for disk_user in disk.users:
56+
instance = instance_client.get(project=project_id, zone=zone, instance=disk_user)
57+
if instance.status in STOPPED_MACHINE_STATUS:
58+
continue
59+
if not force_create:
60+
raise RuntimeError(f"Instance {disk_user} should be stopped. For Windows instances please "
61+
f"stop the instance using `GCESysprep` command. For Linux instances just "
62+
f"shut it down normally. You can supress this error and create an image of"
63+
f"the disk by setting `force_create` parameter to true (not recommended). \n"
64+
f"More information here: \n"
65+
f" * https://cloud.google.com/compute/docs/instances/windows/creating-windows-os-image#api \n"
66+
f" * https://cloud.google.com/compute/docs/images/create-delete-deprecate-private-images#prepare_instance_for_image")
67+
else:
68+
warnings.warn(f"Warning: The `force_create` option may compromise the integrity of your image. "
69+
f"Stop the {disk_user} instance before you create the image if possible.")
70+
71+
# Create image
72+
image = compute_v1.Image()
73+
image.source_disk = disk.self_link
74+
image.name = image_name
75+
if storage_location:
76+
image.storage_locations = [storage_location]
77+
78+
operation = image_client.insert(project=project_id, image_resource=image)
79+
80+
wait_for_extended_operation(operation, "image creation")
81+
82+
return image_client.get(project=project_id, image=image_name)
83+
# </INGREDIENT>
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Copyright 2022 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
16+
# This is an ingredient file. It is not meant to be run directly. Check the samples/snippets
17+
# folder for complete code samples that are ready to be used.
18+
# Disabling flake8 for the ingredients file, as it would fail F821 - undefined name check.
19+
# flake8: noqa
20+
from typing import NoReturn
21+
22+
from google.cloud import compute_v1
23+
24+
25+
# <INGREDIENT delete_image>
26+
def delete_image(project_id: str, image_name: str) -> NoReturn:
27+
"""
28+
Deletes a disk image.
29+
30+
Args:
31+
project_id: project ID or project number of the Cloud project you use.
32+
image_name: name of the image you want to delete.
33+
"""
34+
image_client = compute_v1.ImagesClient()
35+
operation = image_client.delete(project=project_id, image=image_name)
36+
wait_for_extended_operation(operation, "image deletion")
37+
# </INGREDIENT>
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Copyright 2022 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
# flake8: noqa
15+
16+
# <REGION compute_windows_image_create>
17+
# <REGION compute_images_create>
18+
# <IMPORTS/>
19+
20+
# <INGREDIENT wait_for_extended_operation />
21+
22+
# <INGREDIENT create_image />
23+
# </REGION compute_images_create>
24+
# </REGION compute_windows_image_create>
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Copyright 2022 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
# flake8: noqa
15+
16+
# <REGION compute_images_delete>
17+
# <IMPORTS/>
18+
19+
# <INGREDIENT wait_for_extended_operation />
20+
21+
# <INGREDIENT delete_image />
22+
# </REGION compute_images_delete>
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
# Copyright 2022 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
# flake8: noqa
15+
16+
17+
# This file is automatically generated. Please do not modify it directly.
18+
# Find the relevant recipe file in the samples/recipes or samples/ingredients
19+
# directory and apply your changes there.
20+
21+
22+
# [START compute_windows_image_create]
23+
# [START compute_images_create]
24+
import sys
25+
import time
26+
from typing import Any
27+
import warnings
28+
29+
from google.api_core.extended_operation import ExtendedOperation
30+
from google.cloud import compute_v1
31+
32+
33+
def wait_for_extended_operation(
34+
operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
35+
) -> Any:
36+
"""
37+
This method will wait for the extended (long-running) operation to
38+
complete. If the operation is successful, it will return its result.
39+
If the operation ends with an error, an exception will be raised.
40+
If there were any warnings during the execution of the operation
41+
they will be printed to sys.stderr.
42+
43+
Args:
44+
operation: a long-running operation you want to wait on.
45+
verbose_name: (optional) a more verbose name of the operation,
46+
used only during error and warning reporting.
47+
timeout: how long (in seconds) to wait for operation to finish.
48+
If None, wait indefinitely.
49+
50+
Returns:
51+
Whatever the operation.result() returns.
52+
53+
Raises:
54+
This method will raise the exception received from `operation.exception()`
55+
or RuntimeError if there is no exception set, but there is an `error_code`
56+
set for the `operation`.
57+
58+
In case of an operation taking longer than `timeout` seconds to complete,
59+
a `concurrent.futures.TimeoutError` will be raised.
60+
"""
61+
result = operation.result(timeout=timeout)
62+
63+
if operation.error_code:
64+
print(
65+
f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
66+
file=sys.stderr,
67+
)
68+
print(f"Operation ID: {operation.name}")
69+
raise operation.exception() or RuntimeError(operation.error_message)
70+
71+
if operation.warnings:
72+
print(f"Warnings during {verbose_name}:\n", file=sys.stderr)
73+
for warning in operation.warnings:
74+
print(f" - {warning.code}: {warning.message}", file=sys.stderr)
75+
76+
return result
77+
78+
79+
STOPPED_MACHINE_STATUS = (
80+
compute_v1.Instance.Status.TERMINATED.name,
81+
compute_v1.Instance.Status.STOPPED.name,
82+
)
83+
84+
85+
def create_image(
86+
project_id: str,
87+
zone: str,
88+
source_disk_name: str,
89+
image_name: str,
90+
storage_location: str = None,
91+
force_create: bool = False,
92+
) -> compute_v1.Image:
93+
"""
94+
Creates a new disk image.
95+
96+
Args:
97+
project_id: project ID or project number of the Cloud project you use.
98+
zone: zone of the disk you copy from.
99+
source_disk_name: name of the source disk you copy from.
100+
image_name: name of the image you want to create.
101+
storage_location: storage location for the image. If the value is undefined,
102+
function will store the image in the multi-region closest to your image's
103+
source location.
104+
force_create: create the image even if the source disk is attached to a
105+
running instance.
106+
"""
107+
image_client = compute_v1.ImagesClient()
108+
disk_client = compute_v1.DisksClient()
109+
instance_client = compute_v1.InstancesClient()
110+
111+
# Get source disk
112+
disk = disk_client.get(project=project_id, zone=zone, disk=source_disk_name)
113+
114+
for disk_user in disk.users:
115+
instance = instance_client.get(
116+
project=project_id, zone=zone, instance=disk_user
117+
)
118+
if instance.status in STOPPED_MACHINE_STATUS:
119+
continue
120+
if not force_create:
121+
raise RuntimeError(
122+
f"Instance {disk_user} should be stopped. For Windows instances please "
123+
f"stop the instance using `GCESysprep` command. For Linux instances just "
124+
f"shut it down normally. You can supress this error and create an image of"
125+
f"the disk by setting `force_create` parameter to true (not recommended). \n"
126+
f"More information here: \n"
127+
f" * https://cloud.google.com/compute/docs/instances/windows/creating-windows-os-image#api \n"
128+
f" * https://cloud.google.com/compute/docs/images/create-delete-deprecate-private-images#prepare_instance_for_image"
129+
)
130+
else:
131+
warnings.warn(
132+
f"Warning: The `force_create` option may compromise the integrity of your image. "
133+
f"Stop the {disk_user} instance before you create the image if possible."
134+
)
135+
136+
# Create image
137+
image = compute_v1.Image()
138+
image.source_disk = disk.self_link
139+
image.name = image_name
140+
if storage_location:
141+
image.storage_locations = [storage_location]
142+
143+
operation = image_client.insert(project=project_id, image_resource=image)
144+
145+
wait_for_extended_operation(operation, "image creation")
146+
147+
return image_client.get(project=project_id, image=image_name)
148+
149+
150+
# [END compute_images_create]
151+
# [END compute_windows_image_create]

0 commit comments

Comments
 (0)