Skip to content

Commit db6cba2

Browse files
feat: New Compute reservation Sample (#12781)
* Created new compute_template_not_consume_reservation
1 parent ec2af86 commit db6cba2

File tree

4 files changed

+259
-1
lines changed

4 files changed

+259
-1
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
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+
# <INGREDIENT create_template_not_consume_reservation>
23+
def create_instance_template_not_consume_reservation(
24+
project_id: str,
25+
template_name: str,
26+
machine_type: str = "n1-standard-1",
27+
) -> compute_v1.InstanceTemplate:
28+
"""
29+
Creates an instance template that creates VMs that don't explicitly consume reservations
30+
31+
Args:
32+
project_id: project ID or project number of the Cloud project you use.
33+
template_name: name of the new template to create.
34+
machine_type: machine type for the instance.
35+
Returns:
36+
InstanceTemplate object that represents the new instance template.
37+
"""
38+
39+
template = compute_v1.InstanceTemplate()
40+
template.name = template_name
41+
template.properties.machine_type = machine_type
42+
# The template describes the size and source image of the boot disk
43+
# to attach to the instance.
44+
template.properties.disks = [
45+
compute_v1.AttachedDisk(
46+
boot=True,
47+
auto_delete=True, # The disk will be deleted when the instance is deleted
48+
initialize_params=compute_v1.AttachedDiskInitializeParams(
49+
source_image="projects/debian-cloud/global/images/family/debian-11",
50+
disk_size_gb=10,
51+
),
52+
)
53+
]
54+
# The template connects the instance to the `default` network,
55+
template.properties.network_interfaces = [
56+
compute_v1.NetworkInterface(
57+
network="global/networks/default",
58+
access_configs=[
59+
compute_v1.AccessConfig(
60+
name="External NAT",
61+
type="ONE_TO_ONE_NAT",
62+
)
63+
],
64+
)
65+
]
66+
# The template doesn't explicitly consume reservations
67+
template.properties.reservation_affinity = compute_v1.ReservationAffinity(
68+
consume_reservation_type="NO_RESERVATION"
69+
)
70+
71+
template_client = compute_v1.InstanceTemplatesClient()
72+
operation = template_client.insert(
73+
project=project_id, instance_template_resource=template
74+
)
75+
76+
wait_for_extended_operation(operation, "instance template creation")
77+
78+
return template_client.get(project=project_id, instance_template=template_name)
79+
# </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_template_not_consume_reservation>
16+
# <IMPORTS/>
17+
18+
# <INGREDIENT wait_for_extended_operation />
19+
20+
# <INGREDIENT create_template_not_consume_reservation />
21+
# </REGION compute_template_not_consume_reservation>
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
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_template_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_instance_template_not_consume_reservation(
80+
project_id: str,
81+
template_name: str,
82+
machine_type: str = "n1-standard-1",
83+
) -> compute_v1.InstanceTemplate:
84+
"""
85+
Creates an instance template that creates VMs that don't explicitly consume reservations
86+
87+
Args:
88+
project_id: project ID or project number of the Cloud project you use.
89+
template_name: name of the new template to create.
90+
machine_type: machine type for the instance.
91+
Returns:
92+
InstanceTemplate object that represents the new instance template.
93+
"""
94+
95+
template = compute_v1.InstanceTemplate()
96+
template.name = template_name
97+
template.properties.machine_type = machine_type
98+
# The template describes the size and source image of the boot disk
99+
# to attach to the instance.
100+
template.properties.disks = [
101+
compute_v1.AttachedDisk(
102+
boot=True,
103+
auto_delete=True, # The disk will be deleted when the instance is deleted
104+
initialize_params=compute_v1.AttachedDiskInitializeParams(
105+
source_image="projects/debian-cloud/global/images/family/debian-11",
106+
disk_size_gb=10,
107+
),
108+
)
109+
]
110+
# The template connects the instance to the `default` network,
111+
template.properties.network_interfaces = [
112+
compute_v1.NetworkInterface(
113+
network="global/networks/default",
114+
access_configs=[
115+
compute_v1.AccessConfig(
116+
name="External NAT",
117+
type="ONE_TO_ONE_NAT",
118+
)
119+
],
120+
)
121+
]
122+
# The template doesn't explicitly consume reservations
123+
template.properties.reservation_affinity = compute_v1.ReservationAffinity(
124+
consume_reservation_type="NO_RESERVATION"
125+
)
126+
127+
template_client = compute_v1.InstanceTemplatesClient()
128+
operation = template_client.insert(
129+
project=project_id, instance_template_resource=template
130+
)
131+
132+
wait_for_extended_operation(operation, "instance template creation")
133+
134+
return template_client.get(project=project_id, instance_template=template_name)
135+
136+
137+
# [END compute_template_not_consume_reservation]

compute/client_library/snippets/tests/test_compute_reservation.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,13 @@
3939
from ..compute_reservations.create_not_consume_reservation import (
4040
create_vm_not_consume_reservation,
4141
)
42+
from ..compute_reservations.create_vm_template_not_consume_reservation import (
43+
create_instance_template_not_consume_reservation,
44+
)
4245
from ..compute_reservations.delete_compute_reservation import delete_compute_reservation
4346
from ..compute_reservations.get_compute_reservation import get_compute_reservation
4447
from ..compute_reservations.list_compute_reservation import list_compute_reservation
4548

46-
4749
from ..instances.create import create_instance
4850
from ..instances.delete import delete_instance
4951

@@ -223,6 +225,25 @@ def test_consume_shared_reservaton():
223225
delete_compute_reservation(PROJECT_ID, ZONE, RESERVATION_NAME)
224226

225227

228+
def test_create_template_not_consume_reservation():
229+
template_name = "test-template-" + uuid.uuid4().hex[:10]
230+
try:
231+
template = create_instance_template_not_consume_reservation(
232+
PROJECT_ID, template_name, MACHINE_TYPE
233+
)
234+
assert (
235+
template.properties.reservation_affinity.consume_reservation_type
236+
== "NO_RESERVATION"
237+
)
238+
finally:
239+
try:
240+
compute_v1.InstanceTemplatesClient().delete(
241+
project=PROJECT_ID, instance_template=template_name
242+
)
243+
except Exception as e:
244+
print(f"Failed to delete template: {e}")
245+
246+
226247
def test_create_vm_not_consume_reservations():
227248
instance = create_vm_not_consume_reservation(
228249
PROJECT_ID, ZONE, INSTANCE_NAME, MACHINE_TYPE

0 commit comments

Comments
 (0)