Skip to content
This repository was archived by the owner on Dec 31, 2023. It is now read-only.

Commit 55f7361

Browse files
chore(samples): Making samples required for moving VM instance docs (#242)
Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
1 parent 2298e8d commit 55f7361

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

74 files changed

+2227
-240
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Copyright 2022 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+
import sys
20+
from typing import NoReturn
21+
22+
23+
from google.cloud import compute_v1
24+
25+
26+
# <INGREDIENT set_disk_autodelete>
27+
def set_disk_autodelete(project_id: str, zone: str, instance_name: str, disk_name: str, autodelete: bool) -> NoReturn:
28+
"""
29+
Set the autodelete flag of a disk to given value.
30+
31+
Args:
32+
project_id: project ID or project number of the Cloud project you want to use.
33+
zone: name of the zone in which is the disk you want to modify.
34+
instance_name: name of the instance the disk is attached to.
35+
disk_name: the name of the disk which flag you want to modify.
36+
autodelete: the new value of the autodelete flag.
37+
"""
38+
instance_client = compute_v1.InstancesClient()
39+
instance = instance_client.get(project=project_id, zone=zone, instance=instance_name)
40+
41+
for disk in instance.disks:
42+
if disk.device_name == disk_name:
43+
break
44+
else:
45+
raise RuntimeError(f"Instance {instance_name} doesn't have a disk named {disk_name} attached.")
46+
47+
disk.auto_delete = autodelete
48+
49+
operation = instance_client.update_unary(project=project_id, zone=zone, instance=instance_name, instance_resource=instance)
50+
operation_client = compute_v1.ZoneOperationsClient()
51+
operation = operation_client.wait(project=project_id, zone=zone, operation=operation.name)
52+
53+
if operation.error:
54+
print("Error during instance update:", operation.error, file=sys.stderr)
55+
raise RuntimeError(operation.error)
56+
if operation.warnings:
57+
print("Warnings during instance update:\n", file=sys.stderr)
58+
for warning in operation.warnings:
59+
print(f" - {warning.code}: {warning.message}", file=sys.stderr)
60+
return
61+
# </INGREDIENT>
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Copyright 2022 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+
import sys
20+
21+
from google.cloud import compute_v1
22+
23+
24+
# <INGREDIENT create_disk_from_image>
25+
def create_disk_from_image(
26+
project_id: str, zone: str, disk_name: str, disk_type: str, disk_size_gb: int, source_image: str
27+
) -> compute_v1.Disk:
28+
"""
29+
Creates a new disk in a project in given zone using an image as base.
30+
31+
Args:
32+
project_id: project ID or project number of the Cloud project you want to use.
33+
zone: name of the zone in which you want to create the disk.
34+
disk_name: name of the disk you want to create.
35+
disk_type: the type of disk you want to create. This value uses the following format:
36+
"zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".
37+
For example: "zones/us-west3-b/diskTypes/pd-ssd"
38+
disk_size_gb: size of the new disk in gigabytes
39+
source_image: source image to use when creating this disk. You must have read access to this disk. This
40+
can be one of the publicly available images or an image from one of your projects.
41+
This value uses the following format: "projects/{project_name}/global/images/{image_name}"
42+
43+
Returns:
44+
An unattached Disk instance.
45+
"""
46+
disk = compute_v1.Disk()
47+
disk.size_gb = disk_size_gb
48+
disk.name = disk_name
49+
disk.zone = zone
50+
disk.type_ = disk_type
51+
disk.source_image = source_image
52+
53+
disk_client = compute_v1.DisksClient()
54+
operation = disk_client.insert_unary(project=project_id, zone=zone, disk_resource=disk)
55+
operation_client = compute_v1.ZoneOperationsClient()
56+
operation = operation_client.wait(project=project_id, zone=zone, operation=operation.name)
57+
58+
if operation.error:
59+
print("Error during disk creation:", operation.error, file=sys.stderr)
60+
raise RuntimeError(operation.error)
61+
if operation.warnings:
62+
print("Warnings during disk creation:\n", file=sys.stderr)
63+
for warning in operation.warnings:
64+
print(f" - {warning.code}: {warning.message}", file=sys.stderr)
65+
66+
return disk_client.get(project=project_id, zone=zone, disk=disk.name)
67+
# </INGREDIENT>
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# Copyright 2022 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+
import sys
20+
21+
22+
from google.cloud import compute_v1
23+
24+
25+
# <INGREDIENT create_disk_from_snapshot>
26+
def create_disk_from_snapshot(project_id: str, zone: str, disk_name: str, disk_type: str, disk_size_gb: int, snapshot_link: str) -> compute_v1.Disk:
27+
"""
28+
Creates a new disk in a project in given zone.
29+
30+
Args:
31+
project_id: project ID or project number of the Cloud project you want to use.
32+
zone: name of the zone in which you want to create the disk.
33+
disk_name: name of the disk you want to create.
34+
disk_type: the type of disk you want to create. This value uses the following format:
35+
"zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".
36+
For example: "zones/us-west3-b/diskTypes/pd-ssd"
37+
disk_size_gb: size of the new disk in gigabytes
38+
snapshot_link: a link to the snapshot you want to use as a source for the new disk.
39+
This value uses the following format: "projects/{project_name}/global/snapshots/{snapshot_name}"
40+
41+
Returns:
42+
An unattached Disk instance.
43+
"""
44+
disk_client = compute_v1.DisksClient()
45+
disk = compute_v1.Disk()
46+
disk.zone = zone
47+
disk.size_gb = disk_size_gb
48+
disk.source_snapshot = snapshot_link
49+
disk.type_ = disk_type
50+
disk.name = disk_name
51+
operation = disk_client.insert_unary(project=project_id, zone=zone, disk_resource=disk)
52+
operation_client = compute_v1.ZoneOperationsClient()
53+
operation = operation_client.wait(project=project_id, zone=zone, operation=operation.name)
54+
55+
if operation.error:
56+
print("Error during disk creation:", operation.error, file=sys.stderr)
57+
raise RuntimeError(operation.error)
58+
59+
if operation.warnings:
60+
print("Warnings during disk creation:\n", file=sys.stderr)
61+
for warning in operation.warnings:
62+
print(f" - {warning.code}: {warning.message}", file=sys.stderr)
63+
64+
return disk_client.get(project=project_id, zone=zone, disk=disk_name)
65+
# </INGREDIENT>

samples/ingredients/disks/delete.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Copyright 2022 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+
import sys
20+
from typing import NoReturn
21+
22+
from google.cloud import compute_v1
23+
24+
25+
# <INGREDIENT delete_disk>
26+
def delete_disk(project_id: str, zone: str, disk_name: str) -> NoReturn:
27+
"""
28+
Deletes a disk from a project.
29+
30+
Args:
31+
project_id: project ID or project number of the Cloud project you want to use.
32+
zone: name of the zone in which is the disk you want to delete.
33+
disk_name: name of the disk you want to delete.
34+
"""
35+
disk_client = compute_v1.DisksClient()
36+
operation = disk_client.delete_unary(project=project_id, zone=zone, disk=disk_name)
37+
operation_client = compute_v1.ZoneOperationsClient()
38+
operation = operation_client.wait(project=project_id, zone=zone, operation=operation.name)
39+
40+
if operation.error:
41+
print("Error during disk delete operation:", operation.error, file=sys.stderr)
42+
raise RuntimeError(operation.error)
43+
if operation.warnings:
44+
print("Warnings during disk delete operation:\n", file=sys.stderr)
45+
for warning in operation.warnings:
46+
print(f" - {warning.code}: {warning.message}", file=sys.stderr)
47+
return
48+
# </INGREDIENT>

samples/ingredients/disks/list.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Copyright 2022 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+
import sys
20+
from typing import NoReturn, Iterable
21+
22+
from google.cloud import compute_v1
23+
24+
25+
# <INGREDIENT list_disks>
26+
def list_disks(project_id: str, zone: str, filter_: str = "") -> Iterable[compute_v1.Disk]:
27+
"""
28+
Deletes a disk from a project.
29+
30+
Args:
31+
project_id: project ID or project number of the Cloud project you want to use.
32+
zone: name of the zone in which is the disk you want to delete.
33+
filter_: filter to be applied when listing disks. Learn more about filters here:
34+
https://cloud.google.com/python/docs/reference/compute/latest/google.cloud.compute_v1.types.ListDisksRequest
35+
"""
36+
disk_client = compute_v1.DisksClient()
37+
request = compute_v1.ListDisksRequest()
38+
request.project = project_id
39+
request.zone = zone
40+
request.filter = filter_
41+
return disk_client.list(request)
42+
# </INGREDIENT>
43+

samples/ingredients/instances/create_instance.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,10 @@ def create_instance(
3333
machine_type: str = "n1-standard-1",
3434
network_link: str = "global/networks/default",
3535
subnetwork_link: str = None,
36+
internal_ip: str = None,
37+
external_access: bool = False,
38+
external_ipv4: str = None,
39+
accelerators: List[compute_v1.AcceleratorConfig] = None,
3640
preemptible: bool = False,
3741
custom_hostname: str = None,
3842
delete_protection: bool = False,
@@ -55,6 +59,16 @@ def create_instance(
5559
subnetwork_link: name of the subnetwork you want the new instance to use.
5660
This value uses the following format:
5761
"regions/{region}/subnetworks/{subnetwork_name}"
62+
internal_ip: internal IP address you want to assign to the new instance.
63+
By default, a free address from the pool of available internal IP addresses of
64+
used subnet will be used.
65+
external_access: boolean flag indicating if the instance should have an external IPv4
66+
address assigned.
67+
external_ipv4: external IPv4 address to be assigned to this instance. If you specify
68+
an external IP address, it must live in the same region as the zone of the instance.
69+
This setting requires `external_access` to be set to True to work.
70+
accelerators: a list of AcceleratorConfig objects describing the accelerators that will
71+
be attached to the new instance.
5872
preemptible: boolean value indicating if the new instance should be preemptible
5973
or not.
6074
custom_hostname: Custom hostname of the new VM instance.
@@ -73,6 +87,18 @@ def create_instance(
7387
if subnetwork_link:
7488
network_interface.subnetwork = subnetwork_link
7589

90+
if internal_ip:
91+
network_interface.network_i_p = internal_ip
92+
93+
if external_access:
94+
access = compute_v1.AccessConfig()
95+
access.type_ = compute_v1.AccessConfig.Type.ONE_TO_ONE_NAT.name
96+
access.name = "External NAT"
97+
access.network_tier = access.NetworkTier.PREMIUM.name
98+
if external_ipv4:
99+
access.nat_i_p = external_ipv4
100+
network_interface.access_configs = [access]
101+
76102
# Collect information into the Instance object.
77103
instance = compute_v1.Instance()
78104
instance.name = instance_name
@@ -82,6 +108,9 @@ def create_instance(
82108
else:
83109
instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
84110

111+
if accelerators:
112+
instance.guest_accelerators = accelerators
113+
85114
instance.network_interfaces = [network_interface]
86115

87116
if preemptible:

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy