Skip to content

Commit 362c9e7

Browse files
feat: Compute regional template Samples - Create, Get, Delete (#12732)
* New 3 Regional Instance Template Samples - Create, Get, Delete. Added tests.
1 parent 5add740 commit 362c9e7

File tree

11 files changed

+607
-0
lines changed

11 files changed

+607
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
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+
from google.cloud import compute_v1
20+
21+
22+
# <INGREDIENT create_regional_instance_template>
23+
def create_regional_instance_template(
24+
project_id: str, region: str, template_name: str
25+
) -> compute_v1.InstanceTemplate:
26+
"""Creates a regional instance template with the provided name and a specific instance configuration.
27+
Args:
28+
project_id (str): The ID of the Google Cloud project
29+
region (str, optional): The region where the instance template will be created.
30+
template_name (str): The name of the regional instance template.
31+
Returns:
32+
InstanceTemplate: The created instance template.
33+
"""
34+
disk = compute_v1.AttachedDisk()
35+
initialize_params = compute_v1.AttachedDiskInitializeParams()
36+
initialize_params.source_image = (
37+
"projects/debian-cloud/global/images/family/debian-11"
38+
)
39+
initialize_params.disk_size_gb = 250
40+
disk.initialize_params = initialize_params
41+
disk.auto_delete = True
42+
disk.boot = True
43+
44+
# The template connects the instance to the `default` network,
45+
# without specifying a subnetwork.
46+
network_interface = compute_v1.NetworkInterface()
47+
network_interface.network = f"projects/{project_id}/global/networks/default"
48+
49+
# The template lets the instance use an external IP address.
50+
access_config = compute_v1.AccessConfig()
51+
access_config.name = "External NAT" # Name of the access configuration.
52+
access_config.type_ = "ONE_TO_ONE_NAT" # Type of the access configuration.
53+
access_config.network_tier = "PREMIUM" # Network tier for the access configuration.
54+
55+
network_interface.access_configs = [access_config]
56+
57+
template = compute_v1.InstanceTemplate()
58+
template.name = template_name
59+
template.properties.disks = [disk]
60+
template.properties.machine_type = "e2-standard-4"
61+
template.properties.network_interfaces = [network_interface]
62+
63+
# Create the instance template request in the specified region.
64+
request = compute_v1.InsertRegionInstanceTemplateRequest(
65+
instance_template_resource=template, project=project_id, region=region
66+
)
67+
68+
client = compute_v1.RegionInstanceTemplatesClient()
69+
operation = client.insert(
70+
request=request,
71+
)
72+
wait_for_extended_operation(operation, "Instance template creation")
73+
74+
template = client.get(
75+
project=project_id, region=region, instance_template=template_name
76+
)
77+
print(template.name)
78+
print(template.region)
79+
print(template.properties.disks[0].initialize_params.source_image)
80+
# Example response:
81+
# test-regional-template
82+
# https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/regions/[REGION]
83+
# projects/debian-cloud/global/images/family/debian-11
84+
85+
return template
86+
87+
88+
# </INGREDIENT>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
from google.cloud import compute_v1
20+
21+
22+
# <INGREDIENT delete_regional_instance_template>
23+
def delete_regional_instance_template(
24+
project_id: str, region: str, template_name: str
25+
) -> None:
26+
"""Deletes a regional instance template in Google Cloud.
27+
Args:
28+
project_id (str): The ID of the Google Cloud project.
29+
region (str): The region where the instance template is located.
30+
template_name (str): The name of the instance template to delete.
31+
Returns:
32+
None
33+
"""
34+
client = compute_v1.RegionInstanceTemplatesClient()
35+
36+
operation = client.delete(
37+
project=project_id, region=region, instance_template=template_name
38+
)
39+
wait_for_extended_operation(operation, "Instance template deletion")
40+
41+
42+
# </INGREDIENT>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
from google.cloud import compute_v1
20+
21+
22+
# <INGREDIENT get_regional_instance_template>
23+
def get_regional_instance_template(
24+
project_id: str, region: str, template_name: str
25+
) -> compute_v1.InstanceTemplate:
26+
"""Retrieves a regional instance template from Google Cloud.
27+
Args:
28+
project_id (str): The ID of the Google Cloud project.
29+
region (str): The region where the instance template is located.
30+
template_name (str): The name of the instance template.
31+
Returns:
32+
InstanceTemplate: The retrieved instance template.
33+
"""
34+
client = compute_v1.RegionInstanceTemplatesClient()
35+
36+
template = client.get(
37+
project=project_id, region=region, instance_template=template_name
38+
)
39+
print(template.name)
40+
print(template.region)
41+
print(template.properties.disks[0].initialize_params.source_image)
42+
# Example response:
43+
# test-regional-template
44+
# https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/regions/[REGION]
45+
# projects/debian-cloud/global/images/family/debian-11
46+
return template
47+
48+
49+
# </INGREDIENT>
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_regional_template_create>
17+
# <IMPORTS/>
18+
19+
# <INGREDIENT wait_for_extended_operation />
20+
21+
# <INGREDIENT create_regional_instance_template />
22+
# </REGION compute_regional_template_create>
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_regional_template_delete>
17+
# <IMPORTS/>
18+
19+
# <INGREDIENT wait_for_extended_operation />
20+
21+
# <INGREDIENT delete_regional_instance_template />
22+
# </REGION compute_regional_template_delete>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
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_regional_template_get>
17+
# <IMPORTS/>
18+
19+
# <INGREDIENT get_regional_instance_template />
20+
# </REGION compute_regional_template_get>

compute/client_library/snippets/instance_templates/compute_regional_template/__init__.py

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
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_regional_template_create]
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_regional_instance_template(
81+
project_id: str, region: str, template_name: str
82+
) -> compute_v1.InstanceTemplate:
83+
"""Creates a regional instance template with the provided name and a specific instance configuration.
84+
Args:
85+
project_id (str): The ID of the Google Cloud project
86+
region (str, optional): The region where the instance template will be created.
87+
template_name (str): The name of the regional instance template.
88+
Returns:
89+
InstanceTemplate: The created instance template.
90+
"""
91+
disk = compute_v1.AttachedDisk()
92+
initialize_params = compute_v1.AttachedDiskInitializeParams()
93+
initialize_params.source_image = (
94+
"projects/debian-cloud/global/images/family/debian-11"
95+
)
96+
initialize_params.disk_size_gb = 250
97+
disk.initialize_params = initialize_params
98+
disk.auto_delete = True
99+
disk.boot = True
100+
101+
# The template connects the instance to the `default` network,
102+
# without specifying a subnetwork.
103+
network_interface = compute_v1.NetworkInterface()
104+
network_interface.network = f"projects/{project_id}/global/networks/default"
105+
106+
# The template lets the instance use an external IP address.
107+
access_config = compute_v1.AccessConfig()
108+
access_config.name = "External NAT" # Name of the access configuration.
109+
access_config.type_ = "ONE_TO_ONE_NAT" # Type of the access configuration.
110+
access_config.network_tier = "PREMIUM" # Network tier for the access configuration.
111+
112+
network_interface.access_configs = [access_config]
113+
114+
template = compute_v1.InstanceTemplate()
115+
template.name = template_name
116+
template.properties.disks = [disk]
117+
template.properties.machine_type = "e2-standard-4"
118+
template.properties.network_interfaces = [network_interface]
119+
120+
# Create the instance template request in the specified region.
121+
request = compute_v1.InsertRegionInstanceTemplateRequest(
122+
instance_template_resource=template, project=project_id, region=region
123+
)
124+
125+
client = compute_v1.RegionInstanceTemplatesClient()
126+
operation = client.insert(
127+
request=request,
128+
)
129+
wait_for_extended_operation(operation, "Instance template creation")
130+
131+
template = client.get(
132+
project=project_id, region=region, instance_template=template_name
133+
)
134+
print(template.name)
135+
print(template.region)
136+
print(template.properties.disks[0].initialize_params.source_image)
137+
# Example response:
138+
# test-regional-template
139+
# https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/regions/[REGION]
140+
# projects/debian-cloud/global/images/family/debian-11
141+
142+
return template
143+
144+
145+
# [END compute_regional_template_create]

0 commit comments

Comments
 (0)