Skip to content

Commit 3983c07

Browse files
authored
feat: MIG create and delete samples (#13014)
1 parent 9531bf4 commit 3983c07

File tree

7 files changed

+460
-0
lines changed

7 files changed

+460
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
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_managed_instance_group>
24+
def create_managed_instance_group(
25+
project_id: str,
26+
zone: str,
27+
group_name: str,
28+
size: int,
29+
template: str,
30+
) -> compute_v1.InstanceGroupManager:
31+
"""
32+
Send a managed group instance creation request to the Compute Engine API and wait for it to complete.
33+
34+
Args:
35+
project_id: project ID or project number of the Cloud project you want to use.
36+
zone: name of the zone to create the instance in. For example: "us-west3-b"
37+
group_name: the name for this instance group.
38+
size: the size of the instance group.
39+
template: the name of the instance template to use for this group. Example:
40+
projects/example-project/regions/us-west3-b/instanceTemplates/example-regional-instance-template
41+
Returns:
42+
Instance group manager object.
43+
"""
44+
instance_client = compute_v1.InstanceGroupManagersClient()
45+
46+
instance_group_manager = compute_v1.InstanceGroupManager()
47+
instance_group_manager.name = group_name
48+
instance_group_manager.target_size = size
49+
instance_group_manager.instance_template = template
50+
51+
# Prepare the request to insert an instance.
52+
request = compute_v1.InsertInstanceGroupManagerRequest()
53+
request.zone = zone
54+
request.project = project_id
55+
request.instance_group_manager_resource = instance_group_manager
56+
57+
# Wait for the create operation to complete.
58+
print(f"Creating the {group_name} group in {zone}...")
59+
60+
operation = instance_client.insert(request=request)
61+
62+
wait_for_extended_operation(operation, "instance creation")
63+
64+
print(f"Group {group_name} created.")
65+
return instance_client.get(project=project_id, zone=zone, instance_group_manager=group_name)
66+
67+
68+
# </INGREDIENT>
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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 delete_managed_instance_group>
24+
def delete_managed_instance_group(
25+
project_id: str,
26+
zone: str,
27+
group_name: str,
28+
) -> None:
29+
"""
30+
Send a managed group instance deletion request to the Compute Engine API and wait for it to complete.
31+
32+
Args:
33+
project_id: project ID or project number of the Cloud project you want to use.
34+
zone: name of the zone to create the instance in. For example: "us-west3-b"
35+
group_name: the name for this instance group.
36+
Returns:
37+
Instance group manager object.
38+
"""
39+
instance_client = compute_v1.InstanceGroupManagersClient()
40+
41+
# Prepare the request to delete an instance.
42+
request = compute_v1.DeleteInstanceGroupManagerRequest()
43+
request.zone = zone
44+
request.project = project_id
45+
request.instance_group_manager = group_name
46+
47+
# Wait for the create operation to complete.
48+
print(f"Deleting the {group_name} group in {zone}...")
49+
50+
operation = instance_client.delete(request=request)
51+
52+
wait_for_extended_operation(operation, "instance deletion")
53+
54+
print(f"Group {group_name} deleted.")
55+
return None
56+
57+
58+
# </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_instance_group_create>
17+
# <IMPORTS/>
18+
19+
# <INGREDIENT wait_for_extended_operation />
20+
21+
# <INGREDIENT create_managed_instance_group />
22+
# </REGION compute_instance_group_create>
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_instance_group_delete>
17+
# <IMPORTS/>
18+
19+
# <INGREDIENT wait_for_extended_operation />
20+
21+
# <INGREDIENT delete_managed_instance_group />
22+
# </REGION compute_instance_group_delete>
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
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_group_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_managed_instance_group(
81+
project_id: str,
82+
zone: str,
83+
group_name: str,
84+
size: int,
85+
template: str,
86+
) -> compute_v1.InstanceGroupManager:
87+
"""
88+
Send a managed group instance creation request to the Compute Engine API and wait for it to complete.
89+
90+
Args:
91+
project_id: project ID or project number of the Cloud project you want to use.
92+
zone: name of the zone to create the instance in. For example: "us-west3-b"
93+
group_name: the name for this instance group.
94+
size: the size of the instance group.
95+
template: the name of the instance template to use for this group. Example:
96+
projects/example-project/regions/us-west3-b/instanceTemplates/example-regional-instance-template
97+
Returns:
98+
Instance group manager object.
99+
"""
100+
instance_client = compute_v1.InstanceGroupManagersClient()
101+
102+
instance_group_manager = compute_v1.InstanceGroupManager()
103+
instance_group_manager.name = group_name
104+
instance_group_manager.target_size = size
105+
instance_group_manager.instance_template = template
106+
107+
# Prepare the request to insert an instance.
108+
request = compute_v1.InsertInstanceGroupManagerRequest()
109+
request.zone = zone
110+
request.project = project_id
111+
request.instance_group_manager_resource = instance_group_manager
112+
113+
# Wait for the create operation to complete.
114+
print(f"Creating the {group_name} group in {zone}...")
115+
116+
operation = instance_client.insert(request=request)
117+
118+
wait_for_extended_operation(operation, "instance creation")
119+
120+
print(f"Group {group_name} created.")
121+
return instance_client.get(
122+
project=project_id, zone=zone, instance_group_manager=group_name
123+
)
124+
125+
126+
# [END compute_instance_group_create]

0 commit comments

Comments
 (0)