Skip to content

Commit fc54b2f

Browse files
m-strzelczykkweinmeisterdandhlee
authored
docs(samples): Changing machine type sample (#9042)
* docs(samples): Changing machine type sample * Applying suggestions * Wording fix * Update compute/client_library/ingredients/instances/change_machine_type.py Co-authored-by: Dan Lee <[email protected]> * Applying suggestions --------- Co-authored-by: Karl Weinmeister <[email protected]> Co-authored-by: Dan Lee <[email protected]>
1 parent 4d50fb1 commit fc54b2f

File tree

4 files changed

+207
-0
lines changed

4 files changed

+207
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Copyright 2023 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+
# This is an ingredient file. It is not meant to be run directly. Check the samples/snippets
16+
# folder for complete code samples that are ready to be used.
17+
# Disabling flake8 for the ingredients file, as it would fail F821 - undefined name check.
18+
# flake8: noqa
19+
20+
from google.cloud import compute_v1
21+
22+
23+
# <INGREDIENT change_machine_type>
24+
def change_machine_type(
25+
project_id: str,
26+
zone: str,
27+
instance_name: str,
28+
new_machine_type: str
29+
) -> None:
30+
"""
31+
Changes the machine type of VM. The VM needs to be in the 'TERMINATED' state for this operation to be successful.
32+
33+
Args:
34+
project_id: project ID or project number of the Cloud project you want to use.
35+
zone: name of the zone your instance belongs to.
36+
instance_name: name of the VM you want to modify.
37+
new_machine_type: the new machine type you want to use for the VM.
38+
For example: `e2-standard-8`, `e2-custom-4-2048` or `m1-ultramem-40`
39+
More about machine types: https://cloud.google.com/compute/docs/machine-resource
40+
"""
41+
client = compute_v1.InstancesClient()
42+
instance = client.get(project=project_id, zone=zone, instance=instance_name)
43+
44+
if instance.status != compute_v1.Instance.Status.TERMINATED.name:
45+
raise RuntimeError(f"Only machines in TERMINATED state can have their machine type changed. "
46+
f"{instance.name} is in {instance.status}({instance.status_message}) state.")
47+
48+
machine_type = compute_v1.InstancesSetMachineTypeRequest()
49+
machine_type.machine_type = f"projects/{project_id}/zones/{zone}/machineTypes/{new_machine_type}"
50+
operation = client.set_machine_type(
51+
project=project_id,
52+
zone=zone,
53+
instance=instance_name,
54+
instances_set_machine_type_request_resource=machine_type,
55+
)
56+
57+
wait_for_extended_operation(operation, "changing machine type")
58+
# </INGREDIENT>
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Copyright 2023 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_change_machine_type>
17+
# <IMPORTS/>
18+
19+
# <INGREDIENT wait_for_extended_operation />
20+
21+
# <INGREDIENT change_machine_type />
22+
# </REGION compute_change_machine_type>
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
# Copyright 2023 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_change_machine_type]
23+
import sys
24+
from typing import Any
25+
26+
from google.api_core.extended_operation import ExtendedOperation
27+
from google.cloud import compute_v1
28+
29+
30+
def wait_for_extended_operation(
31+
operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
32+
) -> Any:
33+
"""
34+
This method will wait for the extended (long-running) operation to
35+
complete. If the operation is successful, it will return its result.
36+
If the operation ends with an error, an exception will be raised.
37+
If there were any warnings during the execution of the operation
38+
they will be printed to sys.stderr.
39+
40+
Args:
41+
operation: a long-running operation you want to wait on.
42+
verbose_name: (optional) a more verbose name of the operation,
43+
used only during error and warning reporting.
44+
timeout: how long (in seconds) to wait for operation to finish.
45+
If None, wait indefinitely.
46+
47+
Returns:
48+
Whatever the operation.result() returns.
49+
50+
Raises:
51+
This method will raise the exception received from `operation.exception()`
52+
or RuntimeError if there is no exception set, but there is an `error_code`
53+
set for the `operation`.
54+
55+
In case of an operation taking longer than `timeout` seconds to complete,
56+
a `concurrent.futures.TimeoutError` will be raised.
57+
"""
58+
result = operation.result(timeout=timeout)
59+
60+
if operation.error_code:
61+
print(
62+
f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
63+
file=sys.stderr,
64+
flush=True,
65+
)
66+
print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
67+
raise operation.exception() or RuntimeError(operation.error_message)
68+
69+
if operation.warnings:
70+
print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
71+
for warning in operation.warnings:
72+
print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)
73+
74+
return result
75+
76+
77+
def change_machine_type(
78+
project_id: str, zone: str, instance_name: str, new_machine_type: str
79+
) -> None:
80+
"""
81+
Changes the machine type of VM. The VM needs to be in the 'TERMINATED' state for this operation to be successful.
82+
83+
Args:
84+
project_id: project ID or project number of the Cloud project you want to use.
85+
zone: name of the zone your instance belongs to.
86+
instance_name: name of the VM you want to modify.
87+
new_machine_type: the new machine type you want to use for the VM.
88+
For example: `e2-standard-8`, `e2-custom-4-2048` or `m1-ultramem-40`
89+
More about machine types: https://cloud.google.com/compute/docs/machine-resource
90+
"""
91+
client = compute_v1.InstancesClient()
92+
instance = client.get(project=project_id, zone=zone, instance=instance_name)
93+
94+
if instance.status != compute_v1.Instance.Status.TERMINATED.name:
95+
raise RuntimeError(
96+
f"Only machines in TERMINATED state can have their machine type changed. "
97+
f"{instance.name} is in {instance.status}({instance.status_message}) state."
98+
)
99+
100+
machine_type = compute_v1.InstancesSetMachineTypeRequest()
101+
machine_type.machine_type = (
102+
f"projects/{project_id}/zones/{zone}/machineTypes/{new_machine_type}"
103+
)
104+
operation = client.set_machine_type(
105+
project=project_id,
106+
zone=zone,
107+
instance=instance_name,
108+
instances_set_machine_type_request_resource=machine_type,
109+
)
110+
111+
wait_for_extended_operation(operation, "changing machine type")
112+
113+
114+
# [END compute_change_machine_type]

compute/client_library/snippets/tests/test_instance_start_stop.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323

2424
from ..disks.clone_encrypted_disk import create_disk_from_customer_encrypted_disk
2525
from ..disks.delete import delete_disk
26+
from ..instances.change_machine_type import change_machine_type
27+
from ..instances.get import get_instance
2628
from ..instances.start import start_instance
2729
from ..instances.start_encrypted import start_instance_with_encryption_key
2830
from ..instances.stop import stop_instance
@@ -187,3 +189,14 @@ def test_clone_encrypted_disk(autodelete_disk_name, compute_encrypted_instance):
187189
encryption_key=KEY_B64)
188190

189191
assert new_disk.name == autodelete_disk_name
192+
193+
194+
def test_change_machine_type(compute_instance):
195+
assert _get_status(compute_instance) == "RUNNING"
196+
197+
stop_instance(PROJECT, INSTANCE_ZONE, compute_instance.name)
198+
199+
assert not get_instance(PROJECT, INSTANCE_ZONE, compute_instance.name).machine_type.endswith("e2-standard-2")
200+
change_machine_type(PROJECT, INSTANCE_ZONE, compute_instance.name, "e2-standard-2")
201+
202+
assert get_instance(PROJECT, INSTANCE_ZONE, compute_instance.name).machine_type.endswith("e2-standard-2")

0 commit comments

Comments
 (0)