Skip to content

Commit

Permalink
chore(samples): Making samples required for moving VM instance docs (#…
Browse files Browse the repository at this point in the history
…242)


Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
  • Loading branch information
m-strzelczyk and gcf-owl-bot[bot] authored Mar 23, 2022
1 parent 82f7b7e commit 5638466
Show file tree
Hide file tree
Showing 74 changed files with 2,227 additions and 240 deletions.
61 changes: 61 additions & 0 deletions compute/compute/ingredients/disks/autodelete_change.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Copyright 2022 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
import sys
from typing import NoReturn


from google.cloud import compute_v1


# <INGREDIENT set_disk_autodelete>
def set_disk_autodelete(project_id: str, zone: str, instance_name: str, disk_name: str, autodelete: bool) -> NoReturn:
"""
Set the autodelete flag of a disk to given value.
Args:
project_id: project ID or project number of the Cloud project you want to use.
zone: name of the zone in which is the disk you want to modify.
instance_name: name of the instance the disk is attached to.
disk_name: the name of the disk which flag you want to modify.
autodelete: the new value of the autodelete flag.
"""
instance_client = compute_v1.InstancesClient()
instance = instance_client.get(project=project_id, zone=zone, instance=instance_name)

for disk in instance.disks:
if disk.device_name == disk_name:
break
else:
raise RuntimeError(f"Instance {instance_name} doesn't have a disk named {disk_name} attached.")

disk.auto_delete = autodelete

operation = instance_client.update_unary(project=project_id, zone=zone, instance=instance_name, instance_resource=instance)
operation_client = compute_v1.ZoneOperationsClient()
operation = operation_client.wait(project=project_id, zone=zone, operation=operation.name)

if operation.error:
print("Error during instance update:", operation.error, file=sys.stderr)
raise RuntimeError(operation.error)
if operation.warnings:
print("Warnings during instance update:\n", file=sys.stderr)
for warning in operation.warnings:
print(f" - {warning.code}: {warning.message}", file=sys.stderr)
return
# </INGREDIENT>
67 changes: 67 additions & 0 deletions compute/compute/ingredients/disks/create_from_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Copyright 2022 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
import sys

from google.cloud import compute_v1


# <INGREDIENT create_disk_from_image>
def create_disk_from_image(
project_id: str, zone: str, disk_name: str, disk_type: str, disk_size_gb: int, source_image: str
) -> compute_v1.Disk:
"""
Creates a new disk in a project in given zone using an image as base.
Args:
project_id: project ID or project number of the Cloud project you want to use.
zone: name of the zone in which you want to create the disk.
disk_name: name of the disk you want to create.
disk_type: the type of disk you want to create. This value uses the following format:
"zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".
For example: "zones/us-west3-b/diskTypes/pd-ssd"
disk_size_gb: size of the new disk in gigabytes
source_image: source image to use when creating this disk. You must have read access to this disk. This
can be one of the publicly available images or an image from one of your projects.
This value uses the following format: "projects/{project_name}/global/images/{image_name}"
Returns:
An unattached Disk instance.
"""
disk = compute_v1.Disk()
disk.size_gb = disk_size_gb
disk.name = disk_name
disk.zone = zone
disk.type_ = disk_type
disk.source_image = source_image

disk_client = compute_v1.DisksClient()
operation = disk_client.insert_unary(project=project_id, zone=zone, disk_resource=disk)
operation_client = compute_v1.ZoneOperationsClient()
operation = operation_client.wait(project=project_id, zone=zone, operation=operation.name)

if operation.error:
print("Error during disk creation:", operation.error, file=sys.stderr)
raise RuntimeError(operation.error)
if operation.warnings:
print("Warnings during disk creation:\n", file=sys.stderr)
for warning in operation.warnings:
print(f" - {warning.code}: {warning.message}", file=sys.stderr)

return disk_client.get(project=project_id, zone=zone, disk=disk.name)
# </INGREDIENT>
65 changes: 65 additions & 0 deletions compute/compute/ingredients/disks/create_from_snapshot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Copyright 2022 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
import sys


from google.cloud import compute_v1


# <INGREDIENT create_disk_from_snapshot>
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:
"""
Creates a new disk in a project in given zone.
Args:
project_id: project ID or project number of the Cloud project you want to use.
zone: name of the zone in which you want to create the disk.
disk_name: name of the disk you want to create.
disk_type: the type of disk you want to create. This value uses the following format:
"zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".
For example: "zones/us-west3-b/diskTypes/pd-ssd"
disk_size_gb: size of the new disk in gigabytes
snapshot_link: a link to the snapshot you want to use as a source for the new disk.
This value uses the following format: "projects/{project_name}/global/snapshots/{snapshot_name}"
Returns:
An unattached Disk instance.
"""
disk_client = compute_v1.DisksClient()
disk = compute_v1.Disk()
disk.zone = zone
disk.size_gb = disk_size_gb
disk.source_snapshot = snapshot_link
disk.type_ = disk_type
disk.name = disk_name
operation = disk_client.insert_unary(project=project_id, zone=zone, disk_resource=disk)
operation_client = compute_v1.ZoneOperationsClient()
operation = operation_client.wait(project=project_id, zone=zone, operation=operation.name)

if operation.error:
print("Error during disk creation:", operation.error, file=sys.stderr)
raise RuntimeError(operation.error)

if operation.warnings:
print("Warnings during disk creation:\n", file=sys.stderr)
for warning in operation.warnings:
print(f" - {warning.code}: {warning.message}", file=sys.stderr)

return disk_client.get(project=project_id, zone=zone, disk=disk_name)
# </INGREDIENT>
48 changes: 48 additions & 0 deletions compute/compute/ingredients/disks/delete.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Copyright 2022 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
import sys
from typing import NoReturn

from google.cloud import compute_v1


# <INGREDIENT delete_disk>
def delete_disk(project_id: str, zone: str, disk_name: str) -> NoReturn:
"""
Deletes a disk from a project.
Args:
project_id: project ID or project number of the Cloud project you want to use.
zone: name of the zone in which is the disk you want to delete.
disk_name: name of the disk you want to delete.
"""
disk_client = compute_v1.DisksClient()
operation = disk_client.delete_unary(project=project_id, zone=zone, disk=disk_name)
operation_client = compute_v1.ZoneOperationsClient()
operation = operation_client.wait(project=project_id, zone=zone, operation=operation.name)

if operation.error:
print("Error during disk delete operation:", operation.error, file=sys.stderr)
raise RuntimeError(operation.error)
if operation.warnings:
print("Warnings during disk delete operation:\n", file=sys.stderr)
for warning in operation.warnings:
print(f" - {warning.code}: {warning.message}", file=sys.stderr)
return
# </INGREDIENT>
43 changes: 43 additions & 0 deletions compute/compute/ingredients/disks/list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Copyright 2022 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
import sys
from typing import NoReturn, Iterable

from google.cloud import compute_v1


# <INGREDIENT list_disks>
def list_disks(project_id: str, zone: str, filter_: str = "") -> Iterable[compute_v1.Disk]:
"""
Deletes a disk from a project.
Args:
project_id: project ID or project number of the Cloud project you want to use.
zone: name of the zone in which is the disk you want to delete.
filter_: filter to be applied when listing disks. Learn more about filters here:
https://cloud.google.com/python/docs/reference/compute/latest/google.cloud.compute_v1.types.ListDisksRequest
"""
disk_client = compute_v1.DisksClient()
request = compute_v1.ListDisksRequest()
request.project = project_id
request.zone = zone
request.filter = filter_
return disk_client.list(request)
# </INGREDIENT>

29 changes: 29 additions & 0 deletions compute/compute/ingredients/instances/create_instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ def create_instance(
machine_type: str = "n1-standard-1",
network_link: str = "global/networks/default",
subnetwork_link: str = None,
internal_ip: str = None,
external_access: bool = False,
external_ipv4: str = None,
accelerators: List[compute_v1.AcceleratorConfig] = None,
preemptible: bool = False,
custom_hostname: str = None,
delete_protection: bool = False,
Expand All @@ -55,6 +59,16 @@ def create_instance(
subnetwork_link: name of the subnetwork you want the new instance to use.
This value uses the following format:
"regions/{region}/subnetworks/{subnetwork_name}"
internal_ip: internal IP address you want to assign to the new instance.
By default, a free address from the pool of available internal IP addresses of
used subnet will be used.
external_access: boolean flag indicating if the instance should have an external IPv4
address assigned.
external_ipv4: external IPv4 address to be assigned to this instance. If you specify
an external IP address, it must live in the same region as the zone of the instance.
This setting requires `external_access` to be set to True to work.
accelerators: a list of AcceleratorConfig objects describing the accelerators that will
be attached to the new instance.
preemptible: boolean value indicating if the new instance should be preemptible
or not.
custom_hostname: Custom hostname of the new VM instance.
Expand All @@ -73,6 +87,18 @@ def create_instance(
if subnetwork_link:
network_interface.subnetwork = subnetwork_link

if internal_ip:
network_interface.network_i_p = internal_ip

if external_access:
access = compute_v1.AccessConfig()
access.type_ = compute_v1.AccessConfig.Type.ONE_TO_ONE_NAT.name
access.name = "External NAT"
access.network_tier = access.NetworkTier.PREMIUM.name
if external_ipv4:
access.nat_i_p = external_ipv4
network_interface.access_configs = [access]

# Collect information into the Instance object.
instance = compute_v1.Instance()
instance.name = instance_name
Expand All @@ -82,6 +108,9 @@ def create_instance(
else:
instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"

if accelerators:
instance.guest_accelerators = accelerators

instance.network_interfaces = [network_interface]

if preemptible:
Expand Down
Loading

0 comments on commit 5638466

Please sign in to comment.