Skip to content

Commit f2bbb5b

Browse files
docs(samples): Adding template samples (#136)
Co-authored-by: Kurtis Van Gent <[email protected]> Co-authored-by: Kurtis Van Gent <[email protected]>
1 parent e95ba15 commit f2bbb5b

File tree

3 files changed

+339
-1
lines changed

3 files changed

+339
-1
lines changed
Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
# Copyright 2021 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+
# [START compute_template_list ]
16+
from typing import Iterable
17+
# [END compute_template_list ]
18+
19+
# [START compute_template_create ]
20+
# [START compute_template_list ]
21+
# [START compute_template_get ]
22+
# [START compute_template_create_from_instance ]
23+
# [START compute_template_create_with_subnet ]
24+
# [START compute_template_delete ]
25+
from google.cloud import compute_v1
26+
# [END compute_template_delete ]
27+
# [END compute_template_create_with_subnet ]
28+
# [END compute_template_create_from_instance ]
29+
# [END compute_template_get ]
30+
# [END compute_template_list ]
31+
# [END compute_template_create ]
32+
33+
34+
# [START compute_template_get ]
35+
def get_instance_template(project_id: str, template_name: str) -> compute_v1.InstanceTemplate:
36+
"""
37+
Retrieve an instance template, which you can use to create virtual machine
38+
(VM) instances and managed instance groups (MIGs).
39+
40+
Args:
41+
project_id: project ID or project number of the Cloud project you use.
42+
template_name: name of the template to retrieve.
43+
44+
Returns:
45+
InstanceTemplate object that represents the retrieved template.
46+
"""
47+
template_client = compute_v1.InstanceTemplatesClient()
48+
return template_client.get(project=project_id, instance_template=template_name)
49+
# [END compute_template_get ]
50+
51+
52+
# [START compute_template_list ]
53+
def list_instance_templates(project_id: str) -> Iterable[compute_v1.InstanceTemplate]:
54+
"""
55+
Get a list of InstanceTemplate objects available in a project.
56+
57+
Args:
58+
project_id: project ID or project number of the Cloud project you use.
59+
60+
Returns:
61+
Iterable list of InstanceTemplate objects.
62+
"""
63+
template_client = compute_v1.InstanceTemplatesClient()
64+
return template_client.list(project=project_id)
65+
# [END compute_template_list ]
66+
67+
68+
# [START compute_template_create ]
69+
def create_template(project_id: str, template_name: str) -> compute_v1.InstanceTemplate:
70+
"""
71+
Create a new instance template with the provided name and a specific
72+
instance configuration.
73+
74+
Args:
75+
project_id: project ID or project number of the Cloud project you use.
76+
template_name: name of the new template to create.
77+
78+
Returns:
79+
InstanceTemplate object that represents the new instance template.
80+
"""
81+
# The template describes the size and source image of the boot disk
82+
# to attach to the instance.
83+
disk = compute_v1.AttachedDisk()
84+
initialize_params = compute_v1.AttachedDiskInitializeParams()
85+
initialize_params.source_image = (
86+
"projects/debian-cloud/global/images/family/debian-11"
87+
)
88+
initialize_params.disk_size_gb = 250
89+
disk.initialize_params = initialize_params
90+
disk.auto_delete = True
91+
disk.boot = True
92+
93+
# The template connects the instance to the `default` network,
94+
# without specifying a subnetwork.
95+
network_interface = compute_v1.NetworkInterface()
96+
network_interface.name = "global/networks/default"
97+
98+
# The template lets the instance use an external IP address.
99+
access_config = compute_v1.AccessConfig()
100+
access_config.name = "External NAT"
101+
access_config.type_ = compute_v1.AccessConfig.Type.ONE_TO_ONE_NAT
102+
access_config.network_tier = (
103+
compute_v1.AccessConfig.NetworkTier.PREMIUM
104+
)
105+
network_interface.access_configs = [access_config]
106+
107+
template = compute_v1.InstanceTemplate()
108+
template.name = template_name
109+
template.properties.disks = [disk]
110+
template.properties.machine_type = "e2-standard-4"
111+
template.properties.network_interfaces = [network_interface]
112+
113+
template_client = compute_v1.InstanceTemplatesClient()
114+
operation_client = compute_v1.GlobalOperationsClient()
115+
op = template_client.insert(project=project_id, instance_template_resource=template)
116+
operation_client.wait(project=project_id, operation=op.name)
117+
118+
return template_client.get(project=project_id, instance_template=template_name)
119+
# [END compute_template_create ]
120+
121+
122+
# [START compute_template_create_from_instance ]
123+
def create_template_from_instance(project_id: str, instance: str, template_name: str) -> compute_v1.InstanceTemplate:
124+
"""
125+
Create a new instance template based on an existing instance.
126+
This new template specifies a different boot disk.
127+
128+
Args:
129+
project_id: project ID or project number of the Cloud project you use.
130+
instance: the instance to base the new template on. This value uses
131+
the following format: "projects/{project}/zones/{zone}/instances/{instance_name}"
132+
template_name: name of the new template to create.
133+
134+
Returns:
135+
InstanceTemplate object that represents the new instance template.
136+
"""
137+
disk = compute_v1.DiskInstantiationConfig()
138+
# Device name must match the name of a disk attached to the instance you are
139+
# basing your template on.
140+
disk.device_name = "disk-1"
141+
# Replace the original boot disk image used in your instance with a Rocky Linux image.
142+
disk.instantiate_from = (
143+
compute_v1.DiskInstantiationConfig.InstantiateFrom.CUSTOM_IMAGE
144+
)
145+
disk.custom_image = "projects/rocky-linux-cloud/global/images/family/rocky-linux-8"
146+
# Override the auto_delete setting.
147+
disk.auto_delete = True
148+
149+
template = compute_v1.InstanceTemplate()
150+
template.name = template_name
151+
template.source_instance = instance
152+
template.source_instance_params = compute_v1.SourceInstanceParams()
153+
template.source_instance_params.disk_configs = [disk]
154+
155+
template_client = compute_v1.InstanceTemplatesClient()
156+
operation_client = compute_v1.GlobalOperationsClient()
157+
op = template_client.insert(project=project_id, instance_template_resource=template)
158+
operation_client.wait(project=project_id, operation=op.name)
159+
160+
return template_client.get(project=project_id, instance_template=template_name)
161+
# [END compute_template_create_from_instance ]
162+
163+
164+
# [START compute_template_create_with_subnet ]
165+
def create_template_with_subnet(
166+
project_id: str, network: str, subnetwork: str, template_name: str
167+
) -> compute_v1.InstanceTemplate:
168+
"""
169+
Create an instance template that uses a provided subnet.
170+
171+
Args:
172+
project_id: project ID or project number of the Cloud project you use.
173+
network: the network to be used in the new template. This value uses
174+
the following format: "projects/{project}/global/networks/{network}"
175+
subnetwork: the subnetwork to be used in the new template. This value
176+
uses the following format: "projects/{project}/regions/{region}/subnetworks/{subnetwork}"
177+
template_name: name of the new template to create.
178+
179+
Returns:
180+
InstanceTemplate object that represents the new instance template.
181+
"""
182+
# The template describes the size and source image of the book disk to
183+
# attach to the instance.
184+
disk = compute_v1.AttachedDisk()
185+
initialize_params = compute_v1.AttachedDiskInitializeParams()
186+
initialize_params.source_image = (
187+
"projects/debian-cloud/global/images/family/debian-11"
188+
)
189+
initialize_params.disk_size_gb = 250
190+
disk.initialize_params = initialize_params
191+
disk.auto_delete = True
192+
disk.boot = True
193+
194+
template = compute_v1.InstanceTemplate()
195+
template.name = template_name
196+
template.properties = compute_v1.InstanceProperties()
197+
template.properties.disks = [disk]
198+
template.properties.machine_type = "e2-standard-4"
199+
200+
# The template connects the instance to the specified network and subnetwork.
201+
network_interface = compute_v1.NetworkInterface()
202+
network_interface.network = network
203+
network_interface.subnetwork = subnetwork
204+
template.properties.network_interfaces = [network_interface]
205+
206+
template_client = compute_v1.InstanceTemplatesClient()
207+
operation_client = compute_v1.GlobalOperationsClient()
208+
op = template_client.insert(project=project_id, instance_template_resource=template)
209+
operation_client.wait(project=project_id, operation=op.name)
210+
211+
return template_client.get(project=project_id, instance_template=template_name)
212+
# [END compute_template_create_with_subnet ]
213+
214+
215+
# [START compute_template_delete ]
216+
def delete_instance_template(project_id: str, template_name: str):
217+
"""
218+
Delete an instance template.
219+
220+
Args:
221+
project_id: project ID or project number of the Cloud project you use.
222+
template_name: name of the template to delete.
223+
"""
224+
template_client = compute_v1.InstanceTemplatesClient()
225+
operation_client = compute_v1.GlobalOperationsClient()
226+
op = template_client.delete(project=project_id, instance_template=template_name)
227+
operation_client.wait(project=project_id, operation=op.name)
228+
return
229+
# [END compute_template_delete ]

compute/compute/snippets/test_sample_start_stop.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323
import pytest
2424

25-
from samples.snippets.sample_start_stop import start_instance, start_instance_with_encryption_key, stop_instance
25+
from sample_start_stop import start_instance, start_instance_with_encryption_key, stop_instance
2626

2727
PROJECT = google.auth.default()[1]
2828

@@ -43,6 +43,7 @@ def _make_disk(raw_key: bytes = None):
4343
disk.auto_delete = True
4444
disk.boot = True
4545
disk.type_ = compute_v1.AttachedDisk.Type.PERSISTENT
46+
disk.device_name = 'disk-1'
4647

4748
if raw_key:
4849
disk.disk_encryption_key = compute_v1.CustomerEncryptionKey()
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
# Copyright 2021 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+
import uuid
16+
17+
import google.auth
18+
import pytest
19+
20+
from sample_templates import (
21+
create_template,
22+
create_template_from_instance,
23+
create_template_with_subnet,
24+
delete_instance_template,
25+
list_instance_templates,
26+
)
27+
28+
# Turning off F401 check because flake8 doesn't recognize using
29+
# PyTest fixture as parameter as usage.
30+
from test_sample_start_stop import compute_instance # noqa: F401
31+
32+
PROJECT = google.auth.default()[1]
33+
34+
INSTANCE_ZONE = "europe-central2-b"
35+
36+
37+
@pytest.fixture
38+
def deletable_template_name():
39+
template_name = "i" + uuid.uuid4().hex[:10]
40+
yield template_name
41+
delete_instance_template(PROJECT, template_name)
42+
43+
44+
@pytest.fixture
45+
def template_to_be_deleted():
46+
template_name = "i" + uuid.uuid4().hex[:10]
47+
template = create_template(PROJECT, template_name)
48+
yield template
49+
50+
51+
def test_create_template_and_list(deletable_template_name):
52+
53+
template = create_template(PROJECT, deletable_template_name)
54+
55+
assert template.name == deletable_template_name
56+
assert any(
57+
template.name == deletable_template_name
58+
for template in list_instance_templates(PROJECT)
59+
)
60+
assert template.properties.disks[0].initialize_params.disk_size_gb == 250
61+
assert "debian-11" in template.properties.disks[0].initialize_params.source_image
62+
assert template.properties.network_interfaces[0].name == "global/networks/default"
63+
assert template.properties.machine_type == "e2-standard-4"
64+
65+
66+
def test_create_from_instance(compute_instance, deletable_template_name): # noqa: F811
67+
68+
template = create_template_from_instance(
69+
PROJECT, compute_instance.self_link, deletable_template_name
70+
)
71+
72+
assert template.name == deletable_template_name
73+
assert template.properties.machine_type in compute_instance.machine_type
74+
assert (
75+
template.properties.disks[0].disk_size_gb
76+
== compute_instance.disks[0].disk_size_gb
77+
)
78+
assert (
79+
template.properties.disks[0].initialize_params.source_image
80+
== "projects/rocky-linux-cloud/global/images/family/rocky-linux-8"
81+
)
82+
83+
84+
def test_create_template_with_subnet(deletable_template_name):
85+
template = create_template_with_subnet(
86+
PROJECT,
87+
"global/networks/default",
88+
"regions/asia-east1/subnetworks/default",
89+
deletable_template_name,
90+
)
91+
92+
assert template.name == deletable_template_name
93+
assert (
94+
"global/networks/default" in template.properties.network_interfaces[0].network
95+
)
96+
assert (
97+
"regions/asia-east1/subnetworks/default"
98+
in template.properties.network_interfaces[0].subnetwork
99+
)
100+
101+
102+
def test_delete_template(template_to_be_deleted):
103+
delete_instance_template(PROJECT, template_to_be_deleted.name)
104+
105+
assert all(
106+
template.name != template_to_be_deleted.name
107+
for template in list_instance_templates(PROJECT)
108+
)

0 commit comments

Comments
 (0)