Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_devtestlabvirtualmachine.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2018 Zim Kalinowski, <[email protected]>
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10
11 DOCUMENTATION = '''
12 ---
13 module: azure_rm_devtestlabvirtualmachine
14 version_added: "0.1.2"
15 short_description: Manage Azure DevTest Lab Virtual Machine instance
16 description:
17 - Create, update and delete instance of Azure DevTest Lab Virtual Machine.
18
19 options:
20 resource_group:
21 description:
22 - The name of the resource group.
23 required: True
24 type: str
25 lab_name:
26 description:
27 - The name of the lab.
28 required: True
29 type: str
30 name:
31 description:
32 - The name of the virtual machine.
33 required: True
34 type: str
35 notes:
36 description:
37 - The notes of the virtual machine.
38 type: str
39 os_type:
40 description:
41 - Base type of operating system.
42 type: str
43 choices:
44 - windows
45 - linux
46 - Windows
47 - Linux
48 vm_size:
49 description:
50 - A valid Azure VM size value. For example, C(Standard_D4).
51 - The list of choices varies depending on the subscription and location. Check your subscription for available choices.
52 - Available values can be found on this website, link U(https://docs.microsoft.com/en-us/azure/virtual-machines/windows/sizes-general).
53 - Required when I(state=present).
54 type: str
55 user_name:
56 description:
57 - The user name of the virtual machine.
58 type: str
59 password:
60 description:
61 - The password of the virtual machine administrator.
62 type: str
63 ssh_key:
64 description:
65 - The SSH key of the virtual machine administrator.
66 type: str
67 lab_subnet:
68 description:
69 - An existing subnet within lab's virtual network.
70 - It can be the subnet's resource id.
71 - It can be a dict which contains C(virtual_network_name) and C(name).
72 type: raw
73 disallow_public_ip_address:
74 description:
75 - Indicates whether the virtual machine is to be created without a public IP address.
76 type: str
77 artifacts:
78 description:
79 - The artifacts to be installed on the virtual machine.
80 type: list
81 elements: dict
82 suboptions:
83 source_name:
84 description:
85 - The artifact's source name.
86 type: str
87 source_path:
88 description:
89 - The artifact's path in the source repository.
90 type: str
91 parameters:
92 description:
93 - The parameters of the artifact.
94 type: list
95 elements: dict
96 suboptions:
97 name:
98 description:
99 - The name of the artifact parameter.
100 type: str
101 value:
102 description:
103 - The value of the artifact parameter.
104 type: str
105 image:
106 description:
107 - The Microsoft Azure Marketplace image reference of the virtual machine.
108 type: dict
109 suboptions:
110 offer:
111 description:
112 - The offer of the gallery image.
113 type: str
114 publisher:
115 description:
116 - The publisher of the gallery image.
117 type: str
118 sku:
119 description:
120 - The SKU of the gallery image.
121 type: str
122 os_type:
123 description:
124 - The OS type of the gallery image.
125 type: str
126 version:
127 description:
128 - The version of the gallery image.
129 type: str
130 expiration_date:
131 description:
132 - The expiration date for VM.
133 type: str
134 allow_claim:
135 description:
136 - Indicates whether another user can take ownership of the virtual machine.
137 type: str
138 storage_type:
139 description:
140 - Storage type to use for virtual machine.
141 type: str
142 choices:
143 - standard
144 - premium
145 is_authentication_with_ssh_key:
146 description:
147 - Indicates whether this virtual machine uses an SSH key for authentication.
148 - I(is_authentication_with_ssh_key=True) when I(ssh_key) is set for ssh authentication.
149 type: bool
150 state:
151 description:
152 - Assert the state of the Virtual Machine.
153 - Use C(present) to create or update an Virtual Machine and C(absent) to delete it.
154 type: str
155 default: present
156 choices:
157 - absent
158 - present
159
160 extends_documentation_fragment:
161 - azure.azcollection.azure
162 - azure.azcollection.azure_tags
163
164 author:
165 - Zim Kalinowski (@zikalino)
166
167 '''
168
169 EXAMPLES = '''
170 - name: Create (or update) Virtual Machine
171 azure_rm_devtestlabvirtualmachine:
172 resource_group: myrg
173 lab_name: mylab
174 name: myvm
175 notes: Virtual machine notes....
176 os_type: linux
177 vm_size: Standard_A2_v2
178 user_name: vmadmin
179 password: "{{ password }}"
180 lab_subnet:
181 name: myvnSubnet
182 virtual_network_name: myvn
183 disallow_public_ip_address: false
184 image:
185 offer: 0001-com-ubuntu-server-focal
186 publisher: Canonical
187 sku: 20_04-lts
188 os_type: Linux
189 version: latest
190 artifacts:
191 - source_name: myartifact
192 source_path: "/Artifacts/linux-install-mongodb"
193 allow_claim: false
194 expiration_date: "2019-02-22T01:49:12.117974Z"
195 '''
196
197 RETURN = '''
198 id:
199 description:
200 - The identifier of the DTL Virtual Machine resource.
201 returned: always
202 type: str
203 sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myrg/providers/microsoft.devtestlab/labs/mylab/virtualmachines/myvm
204 compute_id:
205 description:
206 - The identifier of the underlying Compute Virtual Machine resource.
207 returned: always
208 type: str
209 sample: /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myrg/providers/microsoft.devtestlab/labs/mylab/virtualmachines/myvm
210 fqdn:
211 description:
212 - Fully qualified domain name or IP Address of the virtual machine.
213 returned: always
214 type: str
215 sample: myvm.eastus.cloudapp.azure.com
216 '''
217
218 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
219 from ansible.module_utils.common.dict_transformations import _snake_to_camel
220
221 try:
222 from azure.core.polling import LROPoller
223 from azure.core.exceptions import ResourceNotFoundError
224 from azure.mgmt.devtestlabs import DevTestLabsClient
225 except ImportError:
226 # This is handled in azure_rm_common
227 pass
228
229
230 class Actions:
231 NoAction, Create, Update, Delete = range(4)
232
233
234 class AzureRMVirtualMachine(AzureRMModuleBase):
235 """Configuration class for an Azure RM Virtual Machine resource"""
236
237 def __init__(self):
238 self.module_arg_spec = dict(
239 resource_group=dict(
240 type='str',
241 required=True
242 ),
243 lab_name=dict(
244 type='str',
245 required=True
246 ),
247 name=dict(
248 type='str',
249 required=True
250 ),
251 notes=dict(
252 type='str'
253 ),
254 os_type=dict(
255 type='str',
256 choices=['linux', 'windows', 'Linux', 'Windows']
257 ),
258 vm_size=dict(
259 type='str'
260 ),
261 user_name=dict(
262 type='str'
263 ),
264 password=dict(
265 type='str',
266 no_log=True
267 ),
268 ssh_key=dict(
269 type='str',
270 no_log=True
271 ),
272 lab_subnet=dict(
273 type='raw'
274 ),
275 disallow_public_ip_address=dict(
276 type='str'
277 ),
278 artifacts=dict(
279 type='list',
280 elements='dict',
281 options=dict(
282 source_name=dict(
283 type='str',
284 ),
285 source_path=dict(
286 type='str'
287 ),
288 parameters=dict(
289 type='list',
290 elements='dict',
291 options=dict(
292 name=dict(
293 type='str'
294 ),
295 value=dict(
296 type='str'
297 )
298 )
299 )
300 )
301 ),
302 image=dict(
303 type='dict',
304 options=dict(
305 offer=dict(
306 type='str'
307 ),
308 publisher=dict(
309 type='str'
310 ),
311 sku=dict(
312 type='str'
313 ),
314 os_type=dict(
315 type='str'
316 ),
317 version=dict(
318 type='str'
319 )
320 )
321 ),
322 expiration_date=dict(
323 type='str'
324 ),
325 allow_claim=dict(
326 type='str'
327 ),
328 storage_type=dict(
329 type='str',
330 choices=['standard', 'premium']
331 ),
332 is_authentication_with_ssh_key=dict(
333 type='bool'
334 ),
335 state=dict(
336 type='str',
337 default='present',
338 choices=['present', 'absent']
339 )
340 )
341
342 required_if = [
343 ('state', 'present', ['image', 'lab_subnet', 'vm_size', 'os_type']),
344 ('is_authentication_with_ssh_key', True, ['ssh_key'])
345 ]
346
347 self.resource_group = None
348 self.lab_name = None
349 self.name = None
350 self.lab_virtual_machine = dict()
351
352 self.results = dict(changed=False)
353 self.mgmt_client = None
354 self.state = None
355 self.to_do = Actions.NoAction
356
357 super(AzureRMVirtualMachine, self).__init__(derived_arg_spec=self.module_arg_spec,
358 supports_check_mode=True,
359 supports_tags=True,
360 required_if=required_if)
361
362 def exec_module(self, **kwargs):
363 """Main module execution method"""
364
365 for key in list(self.module_arg_spec.keys()) + ['tags']:
366 if hasattr(self, key):
367 setattr(self, key, kwargs[key])
368 elif kwargs[key] is not None:
369 self.lab_virtual_machine[key] = kwargs[key]
370
371 self.lab_virtual_machine['gallery_image_reference'] = self.lab_virtual_machine.pop('image', None)
372
373 if self.lab_virtual_machine.get('artifacts') is not None:
374 for artifact in self.lab_virtual_machine.get('artifacts'):
375 source_name = artifact.pop('source_name')
376 source_path = artifact.pop('source_path')
377 template = "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.DevTestLab/labs/{2}/artifactsources/{3}{4}"
378 artifact['artifact_id'] = template.format(self.subscription_id, self.resource_group, self.lab_name, source_name, source_path)
379
380 self.lab_virtual_machine['size'] = self.lab_virtual_machine.pop('vm_size') if self.lab_virtual_machine.get('vm_size') else None
381 self.lab_virtual_machine['os_type'] = _snake_to_camel(self.lab_virtual_machine['os_type']) if self.lab_virtual_machine.get('os_type') else None
382
383 if self.lab_virtual_machine.get('storage_type'):
384 self.lab_virtual_machine['storage_type'] = _snake_to_camel(self.lab_virtual_machine['storage_type'], True)
385
386 lab_subnet = self.lab_virtual_machine.pop('lab_subnet') if self.lab_virtual_machine.get('lab_subnet') else dict()
387
388 if isinstance(lab_subnet, str):
389 vn_and_subnet = lab_subnet.split('/subnets/')
390 if (len(vn_and_subnet) == 2):
391 self.lab_virtual_machine['lab_virtual_network_id'] = vn_and_subnet[0]
392 self.lab_virtual_machine['lab_subnet_name'] = vn_and_subnet[1]
393 else:
394 self.fail("Invalid 'lab_subnet' resource id format")
395 else:
396 template = "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.DevTestLab/labs/{2}/virtualnetworks/{3}"
397 self.lab_virtual_machine['lab_virtual_network_id'] = template.format(self.subscription_id,
398 self.resource_group,
399 self.lab_name,
400 lab_subnet.get('virtual_network_name'))
401 self.lab_virtual_machine['lab_subnet_name'] = lab_subnet.get('name')
402
403 response = None
404
405 self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient,
406 base_url=self._cloud_environment.endpoints.resource_manager)
407
408 old_response = self.get_virtualmachine()
409
410 if not old_response:
411 self.log("Virtual Machine instance doesn't exist")
412 if self.state == 'absent':
413 self.log("Old instance didn't exist")
414 else:
415 self.to_do = Actions.Create
416 # get location from the lab as it has to be the same and has to be specified (why??)
417 lab = self.get_devtestlab()
418 self.lab_virtual_machine['location'] = lab['location']
419 else:
420 self.log("Virtual Machine instance already exists")
421 if self.state == 'absent':
422 self.to_do = Actions.Delete
423 elif self.state == 'present':
424 self.lab_virtual_machine['location'] = old_response['location']
425
426 if old_response['size'].lower() != self.lab_virtual_machine.get('size').lower():
427 self.lab_virtual_machine['size'] = old_response['size']
428 self.module.warn("Property 'size' cannot be changed")
429
430 if self.lab_virtual_machine.get('storage_type') is not None and \
431 old_response['storage_type'].lower() != self.lab_virtual_machine.get('storage_type').lower():
432 self.lab_virtual_machine['storage_type'] = old_response['storage_type']
433 self.module.warn("Property 'storage_type' cannot be changed")
434
435 if old_response.get('gallery_image_reference', {}) != self.lab_virtual_machine.get('gallery_image_reference', {}):
436 self.lab_virtual_machine['gallery_image_reference'] = old_response['gallery_image_reference']
437 self.module.warn("Property 'image' cannot be changed")
438
439 # currently artifacts can be only specified when vm is created
440 # and in addition we don't have detailed information, just a number of "total artifacts"
441 if len(self.lab_virtual_machine.get('artifacts', [])) != old_response['artifact_deployment_status']['total_artifacts']:
442 self.module.warn("Property 'artifacts' cannot be changed")
443
444 if self.lab_virtual_machine.get('is_authentication_with_ssh_key') is not None:
445 if bool(old_response['is_authentication_with_ssh_key']) != bool(self.lab_virtual_machine['is_authentication_with_ssh_key']):
446 self.module.warn("Property 'is_authentication_with_ssh_key' cannot be changed")
447 else:
448 self.lab_virtual_machine['is_authentication_with_ssh_key'] = old_response['is_authentication_with_ssh_key']
449
450 if self.lab_virtual_machine.get('disallow_public_ip_address') is not None:
451 if old_response['disallow_public_ip_address'] != self.lab_virtual_machine.get('disallow_public_ip_address'):
452 self.module.warn("Property 'disallow_public_ip_address' cannot be changed")
453 self.lab_virtual_machine['disallow_public_ip_address'] = old_response['disallow_public_ip_address']
454
455 if self.lab_virtual_machine.get('allow_claim') is not None:
456 if old_response['allow_claim'] != self.lab_virtual_machine.get('allow_claim'):
457 self.module.warn("Property 'allow_claim' cannot be changed")
458 self.lab_virtual_machine['allow_claim'] = old_response['allow_claim']
459
460 if self.lab_virtual_machine.get('notes') is not None:
461 if old_response['notes'] != self.lab_virtual_machine.get('notes'):
462 self.to_do = Actions.Update
463 else:
464 self.lab_virtual_machine['notes'] = old_response['notes']
465
466 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
467 self.log("Need to Create / Update the Virtual Machine instance")
468
469 self.results['changed'] = True
470 if self.check_mode:
471 return self.results
472
473 response = self.create_update_virtualmachine()
474
475 self.log("Creation / Update done")
476 elif self.to_do == Actions.Delete:
477 self.log("Virtual Machine instance deleted")
478 self.results['changed'] = True
479
480 if self.check_mode:
481 return self.results
482
483 self.delete_virtualmachine()
484 else:
485 self.log("Virtual Machine instance unchanged")
486 self.results['changed'] = False
487 response = old_response
488
489 if self.state == 'present':
490 self.results.update({
491 'id': response.get('id', None),
492 'compute_id': response.get('compute_id', None),
493 'fqdn': response.get('fqdn', None)
494 })
495 return self.results
496
497 def create_update_virtualmachine(self):
498 '''
499 Creates or updates Virtual Machine with the specified configuration.
500
501 :return: deserialized Virtual Machine instance state dictionary
502 '''
503 self.log("Creating / Updating the Virtual Machine instance {0}".format(self.name))
504
505 try:
506 response = self.mgmt_client.virtual_machines.begin_create_or_update(resource_group_name=self.resource_group,
507 lab_name=self.lab_name,
508 name=self.name,
509 lab_virtual_machine=self.lab_virtual_machine)
510 if isinstance(response, LROPoller):
511 response = self.get_poller_result(response)
512
513 except Exception as exc:
514 self.log('Error attempting to create the Virtual Machine instance.')
515 self.fail("Error creating the Virtual Machine instance: {0}".format(str(exc)))
516 return response.as_dict()
517
518 def delete_virtualmachine(self):
519 '''
520 Deletes specified Virtual Machine instance in the specified subscription and resource group.
521
522 :return: True
523 '''
524 self.log("Deleting the Virtual Machine instance {0}".format(self.name))
525 try:
526 response = self.mgmt_client.virtual_machines.begin_delete(resource_group_name=self.resource_group,
527 lab_name=self.lab_name,
528 name=self.name)
529 except Exception as e:
530 self.log('Error attempting to delete the Virtual Machine instance.')
531 self.fail("Error deleting the Virtual Machine instance: {0}".format(str(e)))
532
533 if isinstance(response, LROPoller):
534 response = self.get_poller_result(response)
535
536 return True
537
538 def get_virtualmachine(self):
539 '''
540 Gets the properties of the specified Virtual Machine.
541
542 :return: deserialized Virtual Machine instance state dictionary
543 '''
544 self.log("Checking if the Virtual Machine instance {0} is present".format(self.name))
545 found = False
546 try:
547 response = self.mgmt_client.virtual_machines.get(resource_group_name=self.resource_group,
548 lab_name=self.lab_name,
549 name=self.name)
550 found = True
551 self.log("Response : {0}".format(response))
552 self.log("Virtual Machine instance : {0} found".format(response.name))
553 except ResourceNotFoundError as e:
554 self.log('Did not find the Virtual Machine instance.')
555 if found is True:
556 return response.as_dict()
557
558 return False
559
560 def get_devtestlab(self):
561 '''
562 Gets the properties of the specified DevTest Lab.
563
564 :return: deserialized DevTest Lab instance state dictionary
565 '''
566 self.log("Checking if the DevTest Lab instance {0} is present".format(self.lab_name))
567 try:
568 response = self.mgmt_client.labs.get(resource_group_name=self.resource_group,
569 name=self.lab_name)
570 self.log("Response : {0}".format(response))
571 self.log("DevTest Lab instance : {0} found".format(response.name))
572 return response.as_dict()
573 except ResourceNotFoundError as e:
574 self.fail('Did not find the DevTest Lab instance.')
575 return False
576
577
578 def main():
579 """Main execution"""
580 AzureRMVirtualMachine()
581
582
583 if __name__ == '__main__':
584 main()