Skip to content

Commit 5e1a891

Browse files
feat: New compute sample - attach regional disk to instance. (#12991)
* created compute sample : attach regional disk to instance.
1 parent 89b3202 commit 5e1a891

File tree

4 files changed

+203
-1
lines changed

4 files changed

+203
-1
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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 attach_regional_disk>
24+
def attach_regional_disk(
25+
project_id: str, zone: str, instance_name: str, disk_region: str, disk_name: str
26+
) -> None:
27+
"""
28+
Attaches a regional disk to a specified compute instance.
29+
Args:
30+
project_id (str): The ID of the Google Cloud project.
31+
zone (str): The zone where the instance is located.
32+
instance_name (str): The name of the instance to which the disk will be attached.
33+
disk_region (str): The region where the disk is located.
34+
disk_name (str): The name of the disk to be attached.
35+
Returns:
36+
None
37+
"""
38+
instances_client = compute_v1.InstancesClient()
39+
40+
disk_resource = compute_v1.AttachedDisk(
41+
source=f"/projects/{project_id}/regions/{disk_region}/disks/{disk_name}"
42+
)
43+
44+
operation = instances_client.attach_disk(
45+
project=project_id,
46+
zone=zone,
47+
instance=instance_name,
48+
attached_disk_resource=disk_resource,
49+
)
50+
wait_for_extended_operation(operation, "regional disk attachment")
51+
52+
53+
# </INGREDIENT>
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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+
# <REGION compute_instance_attach_regional_disk>
18+
# <IMPORTS/>
19+
20+
# <INGREDIENT wait_for_extended_operation />
21+
22+
# <INGREDIENT attach_regional_disk />
23+
24+
# </REGION compute_instance_attach_regional_disk>
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
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_instance_attach_regional_disk]
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 attach_regional_disk(
81+
project_id: str, zone: str, instance_name: str, disk_region: str, disk_name: str
82+
) -> None:
83+
"""
84+
Attaches a regional disk to a specified compute instance.
85+
Args:
86+
project_id (str): The ID of the Google Cloud project.
87+
zone (str): The zone where the instance is located.
88+
instance_name (str): The name of the instance to which the disk will be attached.
89+
disk_region (str): The region where the disk is located.
90+
disk_name (str): The name of the disk to be attached.
91+
Returns:
92+
None
93+
"""
94+
instances_client = compute_v1.InstancesClient()
95+
96+
disk_resource = compute_v1.AttachedDisk(
97+
source=f"/projects/{project_id}/regions/{disk_region}/disks/{disk_name}"
98+
)
99+
100+
operation = instances_client.attach_disk(
101+
project=project_id,
102+
zone=zone,
103+
instance=instance_name,
104+
attached_disk_resource=disk_resource,
105+
)
106+
wait_for_extended_operation(operation, "regional disk attachment")
107+
108+
109+
# [END compute_instance_attach_regional_disk]

compute/client_library/snippets/tests/test_disks.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import pytest
2222

2323
from ..disks.attach_disk import attach_disk
24+
from ..disks.attach_regional_disk_to_vm import attach_regional_disk
2425
from ..disks.clone_encrypted_disk_managed_key import create_disk_from_kms_encrypted_disk
2526
from ..disks.create_empty_disk import create_empty_disk
2627
from ..disks.create_from_image import create_disk_from_image
@@ -68,7 +69,7 @@
6869
REGION_SECONDARY = "europe-west3"
6970
KMS_KEYRING_NAME = "compute-test-keyring"
7071
KMS_KEY_NAME = "compute-test-key"
71-
DISK_SIZE = 11
72+
DISK_SIZE = 15
7273

7374

7475
@pytest.fixture()
@@ -527,6 +528,21 @@ def test_start_stop_zone_replication(test_empty_pd_balanced_disk, autodelete_dis
527528
time.sleep(20)
528529

529530

531+
def test_attach_regional_disk_to_vm(
532+
autodelete_regional_blank_disk, autodelete_compute_instance
533+
):
534+
attach_regional_disk(
535+
PROJECT,
536+
ZONE,
537+
autodelete_compute_instance.name,
538+
REGION,
539+
autodelete_regional_blank_disk.name,
540+
)
541+
542+
instance = get_instance(PROJECT, ZONE, autodelete_compute_instance.name)
543+
assert len(list(instance.disks)) == 2
544+
545+
530546
def test_clone_disks_in_consistency_group(
531547
autodelete_regional_disk_name,
532548
autodelete_regional_blank_disk,

0 commit comments

Comments
 (0)