Skip to content

Commit 61f707d

Browse files
Sample for creating VM with no consuming reservations.
1 parent 742375b commit 61f707d

File tree

4 files changed

+262
-0
lines changed

4 files changed

+262
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# Copyright 2024 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+
# https://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 create_compute_not_consume_reservation>
24+
25+
26+
def create_vm_not_consume_reservation(
27+
project_id: str, zone: str, instance_name: str, machine_type: str = "n2-standard-2"
28+
) -> compute_v1.Instance:
29+
"""Creates a VM that explicitly doesn't consume reservations
30+
Args:
31+
project_id (str): The ID of the Google Cloud project.
32+
zone (str): The zone where the VM will be created.
33+
instance_name (str): The name of the instance to create.
34+
machine_type (str, optional): The machine type for the instance.
35+
Returns:
36+
compute_v1.Instance: The created instance.
37+
"""
38+
instance = compute_v1.Instance()
39+
instance.name = instance_name
40+
instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
41+
instance.zone = zone
42+
43+
instance.disks = [
44+
compute_v1.AttachedDisk(
45+
boot=True, # Indicates that this is a boot disk
46+
auto_delete=True, # The disk will be deleted when the instance is deleted
47+
initialize_params=compute_v1.AttachedDiskInitializeParams(
48+
source_image="projects/debian-cloud/global/images/family/debian-11",
49+
disk_size_gb=10,
50+
),
51+
)
52+
]
53+
54+
instance.network_interfaces = [
55+
compute_v1.NetworkInterface(
56+
network="global/networks/default", # The network to use
57+
access_configs=[
58+
compute_v1.AccessConfig(
59+
name="External NAT", # Name of the access configuration
60+
type="ONE_TO_ONE_NAT", # Type of access configuration
61+
)
62+
],
63+
)
64+
]
65+
66+
# Set the reservation affinity to not consume any reservation
67+
instance.reservation_affinity = compute_v1.ReservationAffinity(
68+
consume_reservation_type="NO_RESERVATION", # Prevents the instance from consuming reservations
69+
)
70+
71+
# Create a request to insert the instance
72+
request = compute_v1.InsertInstanceRequest()
73+
request.zone = zone
74+
request.project = project_id
75+
request.instance_resource = instance
76+
77+
vm_client = compute_v1.InstancesClient()
78+
operation = vm_client.insert(request)
79+
wait_for_extended_operation(operation, "Instance creation")
80+
81+
print(f"Creating the {instance_name} instance in {zone}...")
82+
83+
return vm_client.get(project=project_id, zone=zone, instance=instance_name)
84+
85+
86+
# </INGREDIENT>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Copyright 2024 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+
# https://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+
# <REGION compute_instance_not_consume_reservation>
16+
# <IMPORTS/>
17+
18+
# <INGREDIENT wait_for_extended_operation />
19+
20+
# <INGREDIENT create_compute_not_consume_reservation />
21+
# </REGION compute_instance_not_consume_reservation>
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
# Copyright 2024 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+
# https://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 file is automatically generated. Please do not modify it directly.
17+
# Find the relevant recipe file in the samples/recipes or samples/ingredients
18+
# directory and apply your changes there.
19+
20+
21+
# [START compute_instance_not_consume_reservation]
22+
from __future__ import annotations
23+
24+
import sys
25+
from typing import Any
26+
27+
from google.api_core.extended_operation import ExtendedOperation
28+
from google.cloud import compute_v1
29+
30+
31+
def wait_for_extended_operation(
32+
operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
33+
) -> Any:
34+
"""
35+
Waits for the extended (long-running) operation to complete.
36+
37+
If the operation is successful, it will return its result.
38+
If the operation ends with an error, an exception will be raised.
39+
If there were any warnings during the execution of the operation
40+
they will be printed to sys.stderr.
41+
42+
Args:
43+
operation: a long-running operation you want to wait on.
44+
verbose_name: (optional) a more verbose name of the operation,
45+
used only during error and warning reporting.
46+
timeout: how long (in seconds) to wait for operation to finish.
47+
If None, wait indefinitely.
48+
49+
Returns:
50+
Whatever the operation.result() returns.
51+
52+
Raises:
53+
This method will raise the exception received from `operation.exception()`
54+
or RuntimeError if there is no exception set, but there is an `error_code`
55+
set for the `operation`.
56+
57+
In case of an operation taking longer than `timeout` seconds to complete,
58+
a `concurrent.futures.TimeoutError` will be raised.
59+
"""
60+
result = operation.result(timeout=timeout)
61+
62+
if operation.error_code:
63+
print(
64+
f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
65+
file=sys.stderr,
66+
flush=True,
67+
)
68+
print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
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, flush=True)
73+
for warning in operation.warnings:
74+
print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)
75+
76+
return result
77+
78+
79+
def create_vm_not_consume_reservation(
80+
project_id: str, zone: str, instance_name: str, machine_type: str = "n2-standard-2"
81+
) -> compute_v1.Instance:
82+
"""Creates a VM that explicitly doesn't consume reservations
83+
Args:
84+
project_id (str): The ID of the Google Cloud project.
85+
zone (str): The zone where the VM will be created.
86+
instance_name (str): The name of the instance to create.
87+
machine_type (str, optional): The machine type for the instance.
88+
Returns:
89+
compute_v1.Instance: The created instance.
90+
"""
91+
instance = compute_v1.Instance()
92+
instance.name = instance_name
93+
instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
94+
instance.zone = zone
95+
96+
instance.disks = [
97+
compute_v1.AttachedDisk(
98+
boot=True, # Indicates that this is a boot disk
99+
auto_delete=True, # The disk will be deleted when the instance is deleted
100+
initialize_params=compute_v1.AttachedDiskInitializeParams(
101+
source_image="projects/debian-cloud/global/images/family/debian-11",
102+
disk_size_gb=10,
103+
),
104+
)
105+
]
106+
107+
instance.network_interfaces = [
108+
compute_v1.NetworkInterface(
109+
network="global/networks/default", # The network to use
110+
access_configs=[
111+
compute_v1.AccessConfig(
112+
name="External NAT", # Name of the access configuration
113+
type="ONE_TO_ONE_NAT", # Type of access configuration
114+
)
115+
],
116+
)
117+
]
118+
119+
# Set the reservation affinity to not consume any reservation
120+
instance.reservation_affinity = compute_v1.ReservationAffinity(
121+
consume_reservation_type="NO_RESERVATION", # Prevents the instance from consuming reservations
122+
)
123+
124+
# Create a request to insert the instance
125+
request = compute_v1.InsertInstanceRequest()
126+
request.zone = zone
127+
request.project = project_id
128+
request.instance_resource = instance
129+
130+
vm_client = compute_v1.InstancesClient()
131+
operation = vm_client.insert(request)
132+
wait_for_extended_operation(operation, "Instance creation")
133+
134+
print(f"Creating the {instance_name} instance in {zone}...")
135+
136+
return vm_client.get(project=project_id, zone=zone, instance=instance_name)
137+
138+
139+
# [END compute_instance_not_consume_reservation]

compute/client_library/snippets/tests/test_compute_reservation.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@
3636
from ..compute_reservations.create_compute_shared_reservation import (
3737
create_compute_shared_reservation,
3838
)
39+
from ..compute_reservations.create_not_consume_reservation import (
40+
create_vm_not_consume_reservation,
41+
)
3942
from ..compute_reservations.delete_compute_reservation import delete_compute_reservation
4043
from ..compute_reservations.get_compute_reservation import get_compute_reservation
4144
from ..compute_reservations.list_compute_reservation import list_compute_reservation
@@ -218,3 +221,16 @@ def test_consume_shared_reservaton():
218221
if instance:
219222
delete_instance(SHARED_PROJECT_ID, ZONE, instance.name)
220223
delete_compute_reservation(PROJECT_ID, ZONE, RESERVATION_NAME)
224+
225+
226+
def test_create_vm_not_consume_reservations():
227+
instance = create_vm_not_consume_reservation(
228+
PROJECT_ID, ZONE, INSTANCE_NAME, MACHINE_TYPE
229+
)
230+
try:
231+
assert (
232+
instance.reservation_affinity.consume_reservation_type == "NO_RESERVATION"
233+
)
234+
finally:
235+
if instance:
236+
delete_instance(PROJECT_ID, ZONE, instance.name)

0 commit comments

Comments
 (0)