This repository has been archived by the owner on Jun 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 84
/
example.py
326 lines (280 loc) · 9.7 KB
/
example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
"""Create and manage virtual machines.
This script expects that the following environment vars are set:
AZURE_TENANT_ID: your Azure Active Directory tenant id or domain
AZURE_CLIENT_ID: your Azure Active Directory Application Client ID
AZURE_CLIENT_SECRET: your Azure Active Directory Application Secret
AZURE_SUBSCRIPTION_ID: your Azure Subscription Id
"""
import os
import traceback
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.compute.models import DiskCreateOption
from msrestazure.azure_exceptions import CloudError
from haikunator import Haikunator
haikunator = Haikunator()
# Azure Datacenter
LOCATION = 'westus'
# Resource Group
GROUP_NAME = 'azure-sample-group-virtual-machines'
# Network
VNET_NAME = 'azure-sample-vnet'
SUBNET_NAME = 'azure-sample-subnet'
# VM
OS_DISK_NAME = 'azure-sample-osdisk'
STORAGE_ACCOUNT_NAME = haikunator.haikunate(delimiter='')
IP_CONFIG_NAME = 'azure-sample-ip-config'
NIC_NAME = 'azure-sample-nic'
USERNAME = 'userlogin'
PASSWORD = 'Pa$$w0rd91'
VM_NAME = 'VmName'
VM_REFERENCE = {
'linux': {
'publisher': 'Canonical',
'offer': 'UbuntuServer',
'sku': '16.04.0-LTS',
'version': 'latest'
},
'windows': {
'publisher': 'MicrosoftWindowsServer',
'offer': 'WindowsServer',
'sku': '2016-Datacenter',
'version': 'latest'
}
}
def get_credentials():
subscription_id = os.environ['AZURE_SUBSCRIPTION_ID']
credentials = ServicePrincipalCredentials(
client_id=os.environ['AZURE_CLIENT_ID'],
secret=os.environ['AZURE_CLIENT_SECRET'],
tenant=os.environ['AZURE_TENANT_ID']
)
return credentials, subscription_id
def run_example():
"""Virtual Machine management example."""
#
# Create all clients with an Application (service principal) token provider
#
credentials, subscription_id = get_credentials()
resource_client = ResourceManagementClient(credentials, subscription_id)
compute_client = ComputeManagementClient(credentials, subscription_id)
network_client = NetworkManagementClient(credentials, subscription_id)
###########
# Prepare #
###########
# Create Resource group
print('\nCreate Resource Group')
resource_client.resource_groups.create_or_update(
GROUP_NAME, {'location': LOCATION})
try:
# Create a NIC
nic = create_nic(network_client)
#############
# VM Sample #
#############
# Create Linux VM
print('\nCreating Linux Virtual Machine')
vm_parameters = create_vm_parameters(nic.id, VM_REFERENCE['linux'])
async_vm_creation = compute_client.virtual_machines.create_or_update(
GROUP_NAME, VM_NAME, vm_parameters)
async_vm_creation.wait()
# Tag the VM
print('\nTag Virtual Machine')
async_vm_update = compute_client.virtual_machines.create_or_update(
GROUP_NAME,
VM_NAME,
{
'location': LOCATION,
'tags': {
'who-rocks': 'python',
'where': 'on azure'
}
}
)
async_vm_update.wait()
# Create managed data disk
print('\nCreate (empty) managed Data Disk')
async_disk_creation = compute_client.disks.create_or_update(
GROUP_NAME,
'mydatadisk1',
{
'location': LOCATION,
'disk_size_gb': 1,
'creation_data': {
'create_option': DiskCreateOption.empty
}
}
)
data_disk = async_disk_creation.result()
# Get the virtual machine by name
print('\nGet Virtual Machine by Name')
virtual_machine = compute_client.virtual_machines.get(
GROUP_NAME,
VM_NAME
)
# Attach data disk
print('\nAttach Data Disk')
virtual_machine.storage_profile.data_disks.append({
'lun': 12,
'name': 'mydatadisk1',
'create_option': DiskCreateOption.attach,
'managed_disk': {
'id': data_disk.id
}
})
async_disk_attach = compute_client.virtual_machines.create_or_update(
GROUP_NAME,
virtual_machine.name,
virtual_machine
)
async_disk_attach.wait()
# Detach data disk
print('\nDetach Data Disk')
data_disks = virtual_machine.storage_profile.data_disks
data_disks[:] = [
disk for disk in data_disks if disk.name != 'mydatadisk1']
async_vm_update = compute_client.virtual_machines.create_or_update(
GROUP_NAME,
VM_NAME,
virtual_machine
)
virtual_machine = async_vm_update.result()
# Deallocating the VM (in preparation for a disk resize)
print('\nDeallocating the VM (to prepare for a disk resize)')
async_vm_deallocate = compute_client.virtual_machines.deallocate(
GROUP_NAME, VM_NAME)
async_vm_deallocate.wait()
# Increase OS disk size by 10 GB
print('\nUpdate OS disk size')
os_disk_name = virtual_machine.storage_profile.os_disk.name
os_disk = compute_client.disks.get(GROUP_NAME, os_disk_name)
if not os_disk.disk_size_gb:
print(
"\tServer is not returning the OS disk size, possible bug in the server?")
print("\tAssuming that the OS disk size is 30 GB")
os_disk.disk_size_gb = 30
os_disk.disk_size_gb += 10
async_disk_update = compute_client.disks.create_or_update(
GROUP_NAME,
os_disk.name,
os_disk
)
async_disk_update.wait()
# Start the VM
print('\nStart VM')
async_vm_start = compute_client.virtual_machines.start(
GROUP_NAME, VM_NAME)
async_vm_start.wait()
# Restart the VM
print('\nRestart VM')
async_vm_restart = compute_client.virtual_machines.restart(
GROUP_NAME, VM_NAME)
async_vm_restart.wait()
# Stop the VM
print('\nStop VM')
async_vm_stop = compute_client.virtual_machines.power_off(
GROUP_NAME, VM_NAME)
async_vm_stop.wait()
# List VMs in subscription
print('\nList VMs in subscription')
for vm in compute_client.virtual_machines.list_all():
print("\tVM: {}".format(vm.name))
# List VM in resource group
print('\nList VMs in resource group')
for vm in compute_client.virtual_machines.list(GROUP_NAME):
print("\tVM: {}".format(vm.name))
# Delete VM
print('\nDelete VM')
async_vm_delete = compute_client.virtual_machines.delete(
GROUP_NAME, VM_NAME)
async_vm_delete.wait()
# Create Windows VM
print('\nCreating Windows Virtual Machine')
# Recycling NIC of previous VM
vm_parameters = create_vm_parameters(nic.id, VM_REFERENCE['windows'])
async_vm_creation = compute_client.virtual_machines.create_or_update(
GROUP_NAME, VM_NAME, vm_parameters)
async_vm_creation.wait()
except CloudError:
print('A VM operation failed:\n{}'.format(traceback.format_exc()))
else:
print('All example operations completed successfully!')
finally:
# Delete Resource group and everything in it
print('\nDelete Resource Group')
delete_async_operation = resource_client.resource_groups.delete(
GROUP_NAME)
delete_async_operation.wait()
print("\nDeleted: {}".format(GROUP_NAME))
def create_nic(network_client):
"""Create a Network Interface for a VM.
"""
# Create VNet
print('\nCreate Vnet')
async_vnet_creation = network_client.virtual_networks.create_or_update(
GROUP_NAME,
VNET_NAME,
{
'location': LOCATION,
'address_space': {
'address_prefixes': ['10.0.0.0/16']
}
}
)
async_vnet_creation.wait()
# Create Subnet
print('\nCreate Subnet')
async_subnet_creation = network_client.subnets.create_or_update(
GROUP_NAME,
VNET_NAME,
SUBNET_NAME,
{'address_prefix': '10.0.0.0/24'}
)
subnet_info = async_subnet_creation.result()
# Create NIC
print('\nCreate NIC')
async_nic_creation = network_client.network_interfaces.create_or_update(
GROUP_NAME,
NIC_NAME,
{
'location': LOCATION,
'ip_configurations': [{
'name': IP_CONFIG_NAME,
'subnet': {
'id': subnet_info.id
}
}]
}
)
return async_nic_creation.result()
def create_vm_parameters(nic_id, vm_reference):
"""Create the VM parameters structure.
"""
return {
'location': LOCATION,
'os_profile': {
'computer_name': VM_NAME,
'admin_username': USERNAME,
'admin_password': PASSWORD
},
'hardware_profile': {
'vm_size': 'Standard_DS1_v2'
},
'storage_profile': {
'image_reference': {
'publisher': vm_reference['publisher'],
'offer': vm_reference['offer'],
'sku': vm_reference['sku'],
'version': vm_reference['version']
},
},
'network_profile': {
'network_interfaces': [{
'id': nic_id,
}]
},
}
if __name__ == "__main__":
run_example()