Skip to content

Commit

Permalink
docs(samples): Add samples for moving VM to different regions/zones (#…
Browse files Browse the repository at this point in the history
…244)

Co-authored-by: Anthonios Partheniou <partheniou@google.com>
  • Loading branch information
m-strzelczyk and parthea authored Mar 26, 2022
1 parent 4adcb04 commit ff549bd
Show file tree
Hide file tree
Showing 31 changed files with 745 additions and 142 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# 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_empty_disk>
def create_empty_disk(
project_id: str, zone: str, disk_name: str, disk_type: str, disk_size_gb: int
) -> compute_v1.Disk:
"""
Creates a new empty 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
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_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>
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

# <INGREDIENT disk_from_snapshot>
def disk_from_snapshot(
disk_type: str, disk_size_gb: int, boot: bool, source_snapshot: str, auto_delete: bool = False
disk_type: str, disk_size_gb: int, boot: bool, source_snapshot: str, auto_delete: bool = True
) -> compute_v1.AttachedDisk():
"""
Create an AttachedDisk object to be used in VM instance creation. Uses a disk snapshot as the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@


# <INGREDIENT empty_disk>
def empty_disk(disk_type: str, disk_size_gb: int, boot: bool = False, auto_delete: bool = False) -> compute_v1.AttachedDisk():
def empty_disk(disk_type: str, disk_size_gb: int, boot: bool = False, auto_delete: bool = True) -> compute_v1.AttachedDisk():
"""
Create an AttachedDisk object to be used in VM instance creation. The created disk contains
no data and requires formatting before it can be used.
Expand All @@ -43,7 +43,7 @@ def empty_disk(disk_type: str, disk_size_gb: int, boot: bool = False, auto_delet
disk.initialize_params = initialize_params
# Remember to set auto_delete to True if you want the disk to be deleted when you delete
# your VM instance.
disk.auto_delete = True
disk.boot = False
disk.auto_delete = auto_delete
disk.boot = boot
return disk
# </INGREDIENT>
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

# <INGREDIENT disk_from_image>
def disk_from_image(
disk_type: str, disk_size_gb: int, boot: bool, source_image: str, auto_delete: bool = False
disk_type: str, disk_size_gb: int, boot: bool, source_image: str, auto_delete: bool = True
) -> compute_v1.AttachedDisk:
"""
Create an AttachedDisk object to be used in VM instance creation. Uses an image as the
Expand Down
37 changes: 37 additions & 0 deletions packages/google-cloud-compute/samples/ingredients/disks/get.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# 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 get_disk>
def get_disk(project_id: str, zone: str, disk_name: str) -> compute_v1.Disk:
"""
Gets 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 where the disk exists.
disk_name: name of the disk you want to retrieve.
"""
disk_client = compute_v1.DisksClient()
return disk_client.get(project=project_id, zone=zone, disk=disk_name)
# </INGREDIENT>
Original file line number Diff line number Diff line change
Expand Up @@ -149,5 +149,5 @@ def create_instance(
if operation.warnings:
print("Warning during creation:", operation.warnings, file=sys.stderr)
print(f"Instance {instance_name} created.")
return instance
return instance_client.get(project=project_id, zone=zone, instance=instance_name)
# </INGREDIENT>
Original file line number Diff line number Diff line change
@@ -1,22 +1,3 @@
# 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
#
# 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
Expand Down Expand Up @@ -55,7 +36,7 @@ def create_from_custom_image(
Instance object.
"""
disk_type = f"zones/{zone}/diskTypes/pd-standard"
disks = [disk_from_image(disk_type, 10, True, custom_image_link)]
disks = [disk_from_image(disk_type, 10, True, custom_image_link, True)]
instance = create_instance(project_id, zone, instance_name, disks)
return instance
# </INGREDIENT>
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def create_from_public_image(project_id: str, zone: str, instance_name: str) ->
project="debian-cloud", family="debian-10"
)
disk_type = f"zones/{zone}/diskTypes/pd-standard"
disks = [disk_from_image(disk_type, 10, True, newest_debian.self_link)]
disks = [disk_from_image(disk_type, 10, True, newest_debian.self_link, True)]
instance = create_instance(project_id, zone, instance_name, disks)
return instance
# </INGREDIENT>
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# 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
from typing import List

from google.cloud import compute_v1


# <INGREDIENT create_with_existing_disks>
def create_with_existing_disks(project_id: str, zone: str, instance_name: str, disk_names: List[str]) -> compute_v1.Instance:
"""
Create a new VM instance using selected disks. The first disk in disk_names will
be used as boot disk.
Args:
project_id: project ID or project number of the Cloud project you want to use.
zone: name of the zone to create the instance in. For example: "us-west3-b"
instance_name: name of the new virtual machine (VM) instance.
disk_names: list of disk names to be attached to the new virtual machine.
First disk in this list will be used as the boot device.
Returns:
Instance object.
"""
assert(len(disk_names) >= 1)
disks = [get_disk(project_id, zone, disk_name) for disk_name in disk_names]
attached_disks = []
for disk in disks:
adisk = compute_v1.AttachedDisk()
adisk.source = disk.self_link
attached_disks.append(adisk)
attached_disks[0].boot = True
instance = create_instance(project_id, zone, instance_name, attached_disks)
return instance
# </INGREDIENT>
39 changes: 39 additions & 0 deletions packages/google-cloud-compute/samples/ingredients/instances/get.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# 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
from google.cloud import compute_v1


# <INGREDIENT get_instance>
def get_instance(project_id: str, zone: str, instance_name: str) -> compute_v1.Instance:
"""
Get information about a VM instance in the given zone in the specified project.
Args:
project_id: project ID or project number of the Cloud project you want to use.
zone: name of the zone you want to use. For example: “us-west3-b”
instance_name: name of the VM instance you want to query.
Returns:
An Instance object.
"""
instance_client = compute_v1.InstancesClient()
instance = instance_client.get(project=project_id, zone=zone, instance=instance_name)

return instance
# </INGREDIENT>

Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# 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.
# flake8: noqa

# <REGION compute_disk_create_empty_disk>
# <IMPORTS/>

# <INGREDIENT create_empty_disk />

# </REGION compute_disk_create_empty_disk>
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# 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.
# flake8: noqa


# <REGION compute_instances_create_with_existing_disks>
# <IMPORTS/>

# <INGREDIENT get_disk />


# <INGREDIENT create_instance />


# <INGREDIENT create_with_existing_disks />
# </REGION compute_instances_create_with_existing_disks>
20 changes: 20 additions & 0 deletions packages/google-cloud-compute/samples/recipes/instances/get.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# 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.
# flake8: noqa

# <REGION compute_instances_get>
# <IMPORTS/>

# <INGREDIENT get_instance />
# </REGION compute_instances_get>
Loading

0 comments on commit ff549bd

Please sign in to comment.