Skip to content

Commit a4525c6

Browse files
feat: compute create reservation from template sample (#12541)
* feat: compute create reservation from template sample * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
1 parent 079d5d8 commit a4525c6

File tree

4 files changed

+295
-0
lines changed

4 files changed

+295
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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+
# 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 create_reservation_from_template>
24+
def create_reservation_from_template(
25+
project_id: str, reservation_name: str, template: str
26+
) -> compute_v1.Reservation:
27+
"""
28+
Create a new reservation based on an existing template.
29+
30+
Args:
31+
project_id: project ID or project number of the Cloud project you use.
32+
reservation_name: the name of new reservation.
33+
template: existing template path. Following formats are allowed:
34+
- projects/{project_id}/global/instanceTemplates/{template_name}
35+
- projects/{project_id}/regions/{region}/instanceTemplates/{template_name}
36+
- https://www.googleapis.com/compute/v1/projects/{project_id}/global/instanceTemplates/instanceTemplate
37+
- https://www.googleapis.com/compute/v1/projects/{project_id}/regions/{region}/instanceTemplates/instanceTemplate
38+
39+
Returns:
40+
Reservation object that represents the new reservation.
41+
"""
42+
43+
reservations_client = compute_v1.ReservationsClient()
44+
request = compute_v1.InsertReservationRequest()
45+
request.project = project_id
46+
request.zone = "us-central1-a"
47+
48+
specific_reservation = compute_v1.AllocationSpecificSKUReservation()
49+
specific_reservation.count = 1
50+
specific_reservation.source_instance_template = template
51+
52+
reservation = compute_v1.Reservation()
53+
reservation.name = reservation_name
54+
reservation.specific_reservation = specific_reservation
55+
56+
request.reservation_resource = reservation
57+
operation = reservations_client.insert(request)
58+
wait_for_extended_operation(operation, "Reservation creation")
59+
60+
return reservations_client.get(
61+
project=project_id, zone="us-central1-a", reservation=reservation_name
62+
)
63+
64+
65+
# </INGREDIENT>
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
# 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_reservation_create_template>
17+
# <IMPORTS/>
18+
19+
# <INGREDIENT wait_for_extended_operation />
20+
21+
# <INGREDIENT create_reservation_from_template />
22+
# </REGION compute_reservation_create_template>
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
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+
# 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_reservation_create_template]
23+
from __future__ import annotations
24+
25+
import sys
26+
from typing import Any
27+
28+
from google.api_core.extended_operation import ExtendedOperation
29+
from google.cloud import compute_v1
30+
31+
32+
def wait_for_extended_operation(
33+
operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
34+
) -> Any:
35+
"""
36+
Waits for the extended (long-running) operation to complete.
37+
38+
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+
flush=True,
68+
)
69+
print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
70+
raise operation.exception() or RuntimeError(operation.error_message)
71+
72+
if operation.warnings:
73+
print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
74+
for warning in operation.warnings:
75+
print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)
76+
77+
return result
78+
79+
80+
def create_reservation_from_template(
81+
project_id: str, reservation_name: str, template: str
82+
) -> compute_v1.Reservation:
83+
"""
84+
Create a new reservation based on an existing template.
85+
86+
Args:
87+
project_id: project ID or project number of the Cloud project you use.
88+
reservation_name: the name of new reservation.
89+
template: existing template path. Following formats are allowed:
90+
- projects/{project_id}/global/instanceTemplates/{template_name}
91+
- projects/{project_id}/regions/{region}/instanceTemplates/{template_name}
92+
- https://www.googleapis.com/compute/v1/projects/{project_id}/global/instanceTemplates/instanceTemplate
93+
- https://www.googleapis.com/compute/v1/projects/{project_id}/regions/{region}/instanceTemplates/instanceTemplate
94+
95+
Returns:
96+
Reservation object that represents the new reservation.
97+
"""
98+
99+
reservations_client = compute_v1.ReservationsClient()
100+
request = compute_v1.InsertReservationRequest()
101+
request.project = project_id
102+
request.zone = "us-central1-a"
103+
104+
specific_reservation = compute_v1.AllocationSpecificSKUReservation()
105+
specific_reservation.count = 1
106+
specific_reservation.source_instance_template = template
107+
108+
reservation = compute_v1.Reservation()
109+
reservation.name = reservation_name
110+
reservation.specific_reservation = specific_reservation
111+
112+
request.reservation_resource = reservation
113+
operation = reservations_client.insert(request)
114+
wait_for_extended_operation(operation, "Reservation creation")
115+
116+
return reservations_client.get(
117+
project=project_id, zone="us-central1-a", reservation=reservation_name
118+
)
119+
120+
121+
# [END compute_reservation_create_template]
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
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+
# 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+
import uuid
15+
16+
import google.auth
17+
from google.cloud import compute_v1
18+
import pytest
19+
20+
from ..instance_templates.create_reservation_from_template import (
21+
create_reservation_from_template,
22+
)
23+
24+
PROJECT = google.auth.default()[1]
25+
INSTANCE_ZONE = "us-central1-a"
26+
27+
28+
@pytest.fixture
29+
def instance_template():
30+
disk = compute_v1.AttachedDisk()
31+
initialize_params = compute_v1.AttachedDiskInitializeParams()
32+
initialize_params.source_image = (
33+
"projects/debian-cloud/global/images/family/debian-11"
34+
)
35+
initialize_params.disk_size_gb = 25
36+
initialize_params.disk_type = "pd-balanced"
37+
disk.initialize_params = initialize_params
38+
disk.auto_delete = True
39+
disk.boot = True
40+
41+
network_interface = compute_v1.NetworkInterface()
42+
network_interface.name = "global/networks/default"
43+
44+
template = compute_v1.InstanceTemplate()
45+
template.name = "test-template-" + uuid.uuid4().hex[:10]
46+
template.properties.disks = [disk]
47+
template.properties.machine_type = "n1-standard-4"
48+
template.properties.network_interfaces = [network_interface]
49+
50+
template_client = compute_v1.InstanceTemplatesClient()
51+
operation_client = compute_v1.GlobalOperationsClient()
52+
op = template_client.insert_unary(
53+
project=PROJECT, instance_template_resource=template
54+
)
55+
operation_client.wait(project=PROJECT, operation=op.name)
56+
57+
template = template_client.get(project=PROJECT, instance_template=template.name)
58+
59+
yield template
60+
61+
op = template_client.delete_unary(project=PROJECT, instance_template=template.name)
62+
operation_client.wait(project=PROJECT, operation=op.name)
63+
64+
65+
@pytest.fixture()
66+
def autodelete_reservation_name():
67+
instance_name = "test-reservation-" + uuid.uuid4().hex[:10]
68+
yield instance_name
69+
reservations_client = compute_v1.ReservationsClient()
70+
reservations_client.delete(
71+
project=PROJECT, zone=INSTANCE_ZONE, reservation=instance_name
72+
)
73+
74+
75+
def test_create_reservation_from_template(
76+
instance_template, autodelete_reservation_name
77+
):
78+
reservation = create_reservation_from_template(
79+
PROJECT, autodelete_reservation_name, instance_template.self_link
80+
)
81+
82+
assert reservation.name == autodelete_reservation_name
83+
assert reservation.zone.endswith(INSTANCE_ZONE)
84+
assert (
85+
reservation.specific_reservation.source_instance_template
86+
== instance_template.self_link
87+
)

0 commit comments

Comments
 (0)