diff --git a/compute/client_library/ingredients/instance-templates/compute_regional_template/create_compute_regional_template.py b/compute/client_library/ingredients/instance-templates/compute_regional_template/create_compute_regional_template.py new file mode 100644 index 00000000000..57113ad45b0 --- /dev/null +++ b/compute/client_library/ingredients/instance-templates/compute_regional_template/create_compute_regional_template.py @@ -0,0 +1,88 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This is an ingredient file. It is not meant to be run directly. Check the samples/snippets +# folder for complete code samples that are ready to be used. +# Disabling flake8 for the ingredients file, as it would fail F821 - undefined name check. +# flake8: noqa +from google.cloud import compute_v1 + + +# +def create_regional_instance_template( + project_id: str, region: str, template_name: str +) -> compute_v1.InstanceTemplate: + """Creates a regional instance template with the provided name and a specific instance configuration. + Args: + project_id (str): The ID of the Google Cloud project + region (str, optional): The region where the instance template will be created. + template_name (str): The name of the regional instance template. + Returns: + InstanceTemplate: The created instance template. + """ + disk = compute_v1.AttachedDisk() + initialize_params = compute_v1.AttachedDiskInitializeParams() + initialize_params.source_image = ( + "projects/debian-cloud/global/images/family/debian-11" + ) + initialize_params.disk_size_gb = 250 + disk.initialize_params = initialize_params + disk.auto_delete = True + disk.boot = True + + # The template connects the instance to the `default` network, + # without specifying a subnetwork. + network_interface = compute_v1.NetworkInterface() + network_interface.network = f"projects/{project_id}/global/networks/default" + + # The template lets the instance use an external IP address. + access_config = compute_v1.AccessConfig() + access_config.name = "External NAT" # Name of the access configuration. + access_config.type_ = "ONE_TO_ONE_NAT" # Type of the access configuration. + access_config.network_tier = "PREMIUM" # Network tier for the access configuration. + + network_interface.access_configs = [access_config] + + template = compute_v1.InstanceTemplate() + template.name = template_name + template.properties.disks = [disk] + template.properties.machine_type = "e2-standard-4" + template.properties.network_interfaces = [network_interface] + + # Create the instance template request in the specified region. + request = compute_v1.InsertRegionInstanceTemplateRequest( + instance_template_resource=template, project=project_id, region=region + ) + + client = compute_v1.RegionInstanceTemplatesClient() + operation = client.insert( + request=request, + ) + wait_for_extended_operation(operation, "Instance template creation") + + template = client.get( + project=project_id, region=region, instance_template=template_name + ) + print(template.name) + print(template.region) + print(template.properties.disks[0].initialize_params.source_image) + # Example response: + # test-regional-template + # https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/regions/[REGION] + # projects/debian-cloud/global/images/family/debian-11 + + return template + + +# diff --git a/compute/client_library/ingredients/instance-templates/compute_regional_template/delete_compute_regional_template.py b/compute/client_library/ingredients/instance-templates/compute_regional_template/delete_compute_regional_template.py new file mode 100644 index 00000000000..decb0c875d1 --- /dev/null +++ b/compute/client_library/ingredients/instance-templates/compute_regional_template/delete_compute_regional_template.py @@ -0,0 +1,42 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This is an ingredient file. It is not meant to be run directly. Check the samples/snippets +# folder for complete code samples that are ready to be used. +# Disabling flake8 for the ingredients file, as it would fail F821 - undefined name check. +# flake8: noqa +from google.cloud import compute_v1 + + +# +def delete_regional_instance_template( + project_id: str, region: str, template_name: str +) -> None: + """Deletes a regional instance template in Google Cloud. + Args: + project_id (str): The ID of the Google Cloud project. + region (str): The region where the instance template is located. + template_name (str): The name of the instance template to delete. + Returns: + None + """ + client = compute_v1.RegionInstanceTemplatesClient() + + operation = client.delete( + project=project_id, region=region, instance_template=template_name + ) + wait_for_extended_operation(operation, "Instance template deletion") + + +# diff --git a/compute/client_library/ingredients/instance-templates/compute_regional_template/get_compute_regional_template.py b/compute/client_library/ingredients/instance-templates/compute_regional_template/get_compute_regional_template.py new file mode 100644 index 00000000000..05c44aa8b09 --- /dev/null +++ b/compute/client_library/ingredients/instance-templates/compute_regional_template/get_compute_regional_template.py @@ -0,0 +1,49 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This is an ingredient file. It is not meant to be run directly. Check the samples/snippets +# folder for complete code samples that are ready to be used. +# Disabling flake8 for the ingredients file, as it would fail F821 - undefined name check. +# flake8: noqa +from google.cloud import compute_v1 + + +# +def get_regional_instance_template( + project_id: str, region: str, template_name: str +) -> compute_v1.InstanceTemplate: + """Retrieves a regional instance template from Google Cloud. + Args: + project_id (str): The ID of the Google Cloud project. + region (str): The region where the instance template is located. + template_name (str): The name of the instance template. + Returns: + InstanceTemplate: The retrieved instance template. + """ + client = compute_v1.RegionInstanceTemplatesClient() + + template = client.get( + project=project_id, region=region, instance_template=template_name + ) + print(template.name) + print(template.region) + print(template.properties.disks[0].initialize_params.source_image) + # Example response: + # test-regional-template + # https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/regions/[REGION] + # projects/debian-cloud/global/images/family/debian-11 + return template + + +# diff --git a/compute/client_library/recipes/instance_templates/compute_regional_template/create_compute_regional_template.py b/compute/client_library/recipes/instance_templates/compute_regional_template/create_compute_regional_template.py new file mode 100644 index 00000000000..38a10421f77 --- /dev/null +++ b/compute/client_library/recipes/instance_templates/compute_regional_template/create_compute_regional_template.py @@ -0,0 +1,22 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# flake8: noqa + +# +# + +# + +# +# diff --git a/compute/client_library/recipes/instance_templates/compute_regional_template/delete_compute_regional_template.py b/compute/client_library/recipes/instance_templates/compute_regional_template/delete_compute_regional_template.py new file mode 100644 index 00000000000..d0ce7fea8ec --- /dev/null +++ b/compute/client_library/recipes/instance_templates/compute_regional_template/delete_compute_regional_template.py @@ -0,0 +1,22 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# flake8: noqa + +# +# + +# + +# +# diff --git a/compute/client_library/recipes/instance_templates/compute_regional_template/get_compute_regional_template.py b/compute/client_library/recipes/instance_templates/compute_regional_template/get_compute_regional_template.py new file mode 100644 index 00000000000..91c4a1bdd07 --- /dev/null +++ b/compute/client_library/recipes/instance_templates/compute_regional_template/get_compute_regional_template.py @@ -0,0 +1,20 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# flake8: noqa + +# +# + +# +# diff --git a/compute/client_library/snippets/instance_templates/compute_regional_template/__init__.py b/compute/client_library/snippets/instance_templates/compute_regional_template/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/compute/client_library/snippets/instance_templates/compute_regional_template/create_compute_regional_template.py b/compute/client_library/snippets/instance_templates/compute_regional_template/create_compute_regional_template.py new file mode 100644 index 00000000000..2bd43319374 --- /dev/null +++ b/compute/client_library/snippets/instance_templates/compute_regional_template/create_compute_regional_template.py @@ -0,0 +1,145 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# flake8: noqa + + +# This file is automatically generated. Please do not modify it directly. +# Find the relevant recipe file in the samples/recipes or samples/ingredients +# directory and apply your changes there. + + +# [START compute_regional_template_create] +from __future__ import annotations + +import sys +from typing import Any + +from google.api_core.extended_operation import ExtendedOperation +from google.cloud import compute_v1 + + +def wait_for_extended_operation( + operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300 +) -> Any: + """ + Waits for the extended (long-running) operation to complete. + + If the operation is successful, it will return its result. + If the operation ends with an error, an exception will be raised. + If there were any warnings during the execution of the operation + they will be printed to sys.stderr. + + Args: + operation: a long-running operation you want to wait on. + verbose_name: (optional) a more verbose name of the operation, + used only during error and warning reporting. + timeout: how long (in seconds) to wait for operation to finish. + If None, wait indefinitely. + + Returns: + Whatever the operation.result() returns. + + Raises: + This method will raise the exception received from `operation.exception()` + or RuntimeError if there is no exception set, but there is an `error_code` + set for the `operation`. + + In case of an operation taking longer than `timeout` seconds to complete, + a `concurrent.futures.TimeoutError` will be raised. + """ + result = operation.result(timeout=timeout) + + if operation.error_code: + print( + f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}", + file=sys.stderr, + flush=True, + ) + print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True) + raise operation.exception() or RuntimeError(operation.error_message) + + if operation.warnings: + print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True) + for warning in operation.warnings: + print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True) + + return result + + +def create_regional_instance_template( + project_id: str, region: str, template_name: str +) -> compute_v1.InstanceTemplate: + """Creates a regional instance template with the provided name and a specific instance configuration. + Args: + project_id (str): The ID of the Google Cloud project + region (str, optional): The region where the instance template will be created. + template_name (str): The name of the regional instance template. + Returns: + InstanceTemplate: The created instance template. + """ + disk = compute_v1.AttachedDisk() + initialize_params = compute_v1.AttachedDiskInitializeParams() + initialize_params.source_image = ( + "projects/debian-cloud/global/images/family/debian-11" + ) + initialize_params.disk_size_gb = 250 + disk.initialize_params = initialize_params + disk.auto_delete = True + disk.boot = True + + # The template connects the instance to the `default` network, + # without specifying a subnetwork. + network_interface = compute_v1.NetworkInterface() + network_interface.network = f"projects/{project_id}/global/networks/default" + + # The template lets the instance use an external IP address. + access_config = compute_v1.AccessConfig() + access_config.name = "External NAT" # Name of the access configuration. + access_config.type_ = "ONE_TO_ONE_NAT" # Type of the access configuration. + access_config.network_tier = "PREMIUM" # Network tier for the access configuration. + + network_interface.access_configs = [access_config] + + template = compute_v1.InstanceTemplate() + template.name = template_name + template.properties.disks = [disk] + template.properties.machine_type = "e2-standard-4" + template.properties.network_interfaces = [network_interface] + + # Create the instance template request in the specified region. + request = compute_v1.InsertRegionInstanceTemplateRequest( + instance_template_resource=template, project=project_id, region=region + ) + + client = compute_v1.RegionInstanceTemplatesClient() + operation = client.insert( + request=request, + ) + wait_for_extended_operation(operation, "Instance template creation") + + template = client.get( + project=project_id, region=region, instance_template=template_name + ) + print(template.name) + print(template.region) + print(template.properties.disks[0].initialize_params.source_image) + # Example response: + # test-regional-template + # https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/regions/[REGION] + # projects/debian-cloud/global/images/family/debian-11 + + return template + + +# [END compute_regional_template_create] diff --git a/compute/client_library/snippets/instance_templates/compute_regional_template/delete_compute_regional_template.py b/compute/client_library/snippets/instance_templates/compute_regional_template/delete_compute_regional_template.py new file mode 100644 index 00000000000..dc937e1723a --- /dev/null +++ b/compute/client_library/snippets/instance_templates/compute_regional_template/delete_compute_regional_template.py @@ -0,0 +1,99 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# flake8: noqa + + +# This file is automatically generated. Please do not modify it directly. +# Find the relevant recipe file in the samples/recipes or samples/ingredients +# directory and apply your changes there. + + +# [START compute_regional_template_delete] +from __future__ import annotations + +import sys +from typing import Any + +from google.api_core.extended_operation import ExtendedOperation +from google.cloud import compute_v1 + + +def wait_for_extended_operation( + operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300 +) -> Any: + """ + Waits for the extended (long-running) operation to complete. + + If the operation is successful, it will return its result. + If the operation ends with an error, an exception will be raised. + If there were any warnings during the execution of the operation + they will be printed to sys.stderr. + + Args: + operation: a long-running operation you want to wait on. + verbose_name: (optional) a more verbose name of the operation, + used only during error and warning reporting. + timeout: how long (in seconds) to wait for operation to finish. + If None, wait indefinitely. + + Returns: + Whatever the operation.result() returns. + + Raises: + This method will raise the exception received from `operation.exception()` + or RuntimeError if there is no exception set, but there is an `error_code` + set for the `operation`. + + In case of an operation taking longer than `timeout` seconds to complete, + a `concurrent.futures.TimeoutError` will be raised. + """ + result = operation.result(timeout=timeout) + + if operation.error_code: + print( + f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}", + file=sys.stderr, + flush=True, + ) + print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True) + raise operation.exception() or RuntimeError(operation.error_message) + + if operation.warnings: + print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True) + for warning in operation.warnings: + print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True) + + return result + + +def delete_regional_instance_template( + project_id: str, region: str, template_name: str +) -> None: + """Deletes a regional instance template in Google Cloud. + Args: + project_id (str): The ID of the Google Cloud project. + region (str): The region where the instance template is located. + template_name (str): The name of the instance template to delete. + Returns: + None + """ + client = compute_v1.RegionInstanceTemplatesClient() + + operation = client.delete( + project=project_id, region=region, instance_template=template_name + ) + wait_for_extended_operation(operation, "Instance template deletion") + + +# [END compute_regional_template_delete] diff --git a/compute/client_library/snippets/instance_templates/compute_regional_template/get_compute_regional_template.py b/compute/client_library/snippets/instance_templates/compute_regional_template/get_compute_regional_template.py new file mode 100644 index 00000000000..0a68e396b34 --- /dev/null +++ b/compute/client_library/snippets/instance_templates/compute_regional_template/get_compute_regional_template.py @@ -0,0 +1,52 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# flake8: noqa + + +# This file is automatically generated. Please do not modify it directly. +# Find the relevant recipe file in the samples/recipes or samples/ingredients +# directory and apply your changes there. + + +# [START compute_regional_template_get] +from google.cloud import compute_v1 + + +def get_regional_instance_template( + project_id: str, region: str, template_name: str +) -> compute_v1.InstanceTemplate: + """Retrieves a regional instance template from Google Cloud. + Args: + project_id (str): The ID of the Google Cloud project. + region (str): The region where the instance template is located. + template_name (str): The name of the instance template. + Returns: + InstanceTemplate: The retrieved instance template. + """ + client = compute_v1.RegionInstanceTemplatesClient() + + template = client.get( + project=project_id, region=region, instance_template=template_name + ) + print(template.name) + print(template.region) + print(template.properties.disks[0].initialize_params.source_image) + # Example response: + # test-regional-template + # https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/regions/[REGION] + # projects/debian-cloud/global/images/family/debian-11 + return template + + +# [END compute_regional_template_get] diff --git a/compute/client_library/snippets/tests/test_templates_regional.py b/compute/client_library/snippets/tests/test_templates_regional.py new file mode 100644 index 00000000000..808bdfcdf41 --- /dev/null +++ b/compute/client_library/snippets/tests/test_templates_regional.py @@ -0,0 +1,68 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import uuid + +from google.api_core.exceptions import NotFound + +import pytest + +from ..instance_templates.compute_regional_template import ( + create_compute_regional_template, + delete_compute_regional_template, + get_compute_regional_template, +) + + +PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT") +REGION = "us-central1" + + +@pytest.fixture(scope="function") +def regional_template(): + test_template_name = "test-template-" + uuid.uuid4().hex[:6] + template = create_compute_regional_template.create_regional_instance_template( + PROJECT_ID, REGION, test_template_name + ) + yield template + delete_compute_regional_template.delete_regional_instance_template( + PROJECT_ID, REGION, test_template_name + ) + + +def test_create_regional_template(regional_template): + assert regional_template.name.startswith("test-template-") + + +def test_get_regional_template(regional_template): + template = get_compute_regional_template.get_regional_instance_template( + PROJECT_ID, REGION, regional_template.name + ) + assert template.name == regional_template.name + + +def test_delete_regional_template(): + test_template_name = "test-template-" + uuid.uuid4().hex[:6] + create_compute_regional_template.create_regional_instance_template( + PROJECT_ID, REGION, test_template_name + ) + with pytest.raises(NotFound) as exc_info: + delete_compute_regional_template.delete_regional_instance_template( + PROJECT_ID, REGION, test_template_name + ) + get_compute_regional_template.get_regional_instance_template( + PROJECT_ID, REGION, test_template_name + ) + assert "was not found" in str(exc_info.value)