Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2019 Zim Kalinowski, (@zikalino)
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_devtestlabcustomimage
14 version_added: "0.1.2"
15 short_description: Manage Azure DevTest Lab Custom Image instance
16 description:
17 - Create, update and delete instance of Azure DevTest Lab Custom Image.
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 custom image.
33 required: True
34 type: str
35 source_vm:
36 description:
37 - Source DevTest Lab virtual machine name.
38 type: str
39 windows_os_state:
40 description:
41 - The state of the Windows OS.
42 type: str
43 choices:
44 - 'non_sysprepped'
45 - 'sysprep_requested'
46 - 'sysprep_applied'
47 linux_os_state:
48 description:
49 - The state of the Linux OS.
50 type: str
51 choices:
52 - 'non_deprovisioned'
53 - 'deprovision_requested'
54 - 'deprovision_applied'
55 description:
56 description:
57 - The description of the custom image.
58 type: str
59 author:
60 description:
61 - The author of the custom image.
62 type: str
63 state:
64 description:
65 - Assert the state of the Custom Image.
66 - Use C(present) to create or update an Custom Image and C(absent) to delete it.
67 default: present
68 type: str
69 choices:
70 - absent
71 - present
72
73 extends_documentation_fragment:
74 - azure.azcollection.azure
75 - azure.azcollection.azure_tags
76
77 author:
78 - Zim Kalinowski (@zikalino)
79
80 '''
81
82 EXAMPLES = '''
83 - name: Create instance of DevTest Lab Image
84 azure_rm_devtestlabcustomimage:
85 resource_group: myResourceGroup
86 lab_name: myLab
87 name: myImage
88 source_vm: myDevTestLabVm
89 linux_os_state: non_deprovisioned
90 '''
91
92 RETURN = '''
93 id:
94 description:
95 - The identifier of the resource.
96 returned: always
97 type: str
98 sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/microsoft.devtestlab/labs/myLab/images/myImage"
99 '''
100
101 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
102 from ansible.module_utils.common.dict_transformations import _snake_to_camel
103
104 try:
105 from azure.core.polling import LROPoller
106 from azure.core.exceptions import ResourceNotFoundError
107 from azure.mgmt.devtestlabs import DevTestLabsClient
108 except ImportError:
109 # This is handled in azure_rm_common
110 pass
111
112
113 class Actions:
114 NoAction, Create, Update, Delete = range(4)
115
116
117 class AzureRMDtlCustomImage(AzureRMModuleBase):
118 """Configuration class for an Azure RM Custom Image resource"""
119
120 def __init__(self):
121 self.module_arg_spec = dict(
122 resource_group=dict(
123 type='str',
124 required=True
125 ),
126 lab_name=dict(
127 type='str',
128 required=True
129 ),
130 name=dict(
131 type='str',
132 required=True
133 ),
134 source_vm=dict(
135 type='str'
136 ),
137 windows_os_state=dict(
138 type='str',
139 choices=['non_sysprepped',
140 'sysprep_requested',
141 'sysprep_applied']
142 ),
143 linux_os_state=dict(
144 type='str',
145 choices=['non_deprovisioned',
146 'deprovision_requested',
147 'deprovision_applied']
148 ),
149 description=dict(
150 type='str'
151 ),
152 author=dict(
153 type='str'
154 ),
155 state=dict(
156 type='str',
157 default='present',
158 choices=['present', 'absent']
159 )
160 )
161
162 self.resource_group = None
163 self.lab_name = None
164 self.name = None
165 self.custom_image = dict()
166
167 self.results = dict(changed=False)
168 self.mgmt_client = None
169 self.state = None
170 self.to_do = Actions.NoAction
171
172 required_if = [
173 ('state', 'present', [
174 'source_vm'])
175 ]
176
177 super(AzureRMDtlCustomImage, self).__init__(derived_arg_spec=self.module_arg_spec,
178 supports_check_mode=True,
179 supports_tags=True,
180 required_if=required_if)
181
182 def exec_module(self, **kwargs):
183 """Main module execution method"""
184
185 for key in list(self.module_arg_spec.keys()) + ['tags']:
186 if hasattr(self, key):
187 setattr(self, key, kwargs[key])
188 elif kwargs[key] is not None:
189 self.custom_image[key] = kwargs[key]
190
191 if self.state == 'present':
192 windows_os_state = self.custom_image.pop('windows_os_state', False)
193 linux_os_state = self.custom_image.pop('linux_os_state', False)
194 source_vm_name = self.custom_image.pop('source_vm')
195 temp = "/subscriptions/{0}/resourcegroups/{1}/providers/microsoft.devtestlab/labs/{2}/virtualmachines/{3}"
196 self.custom_image['vm'] = {}
197 self.custom_image['vm']['source_vm_id'] = temp.format(self.subscription_id, self.resource_group, self.lab_name, source_vm_name)
198 if windows_os_state:
199 self.custom_image['vm']['windows_os_info'] = {'windows_os_state': _snake_to_camel(windows_os_state, True)}
200 elif linux_os_state:
201 self.custom_image['vm']['linux_os_info'] = {'linux_os_state': _snake_to_camel(linux_os_state, True)}
202 else:
203 self.fail("Either 'linux_os_state' or 'linux_os_state' must be specified")
204
205 response = None
206
207 self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient,
208 base_url=self._cloud_environment.endpoints.resource_manager)
209
210 old_response = self.get_customimage()
211
212 if not old_response:
213 self.log("Custom Image instance doesn't exist")
214 if self.state == 'absent':
215 self.log("Old instance didn't exist")
216 else:
217 self.to_do = Actions.Create
218 else:
219 self.log("Custom Image instance already exists")
220 if self.state == 'absent':
221 self.to_do = Actions.Delete
222 elif self.state == 'present':
223 if (not default_compare(self.custom_image, old_response, '', self.results)):
224 self.to_do = Actions.Update
225
226 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
227 self.log("Need to Create / Update the Custom Image instance")
228
229 if self.check_mode:
230 self.results['changed'] = True
231 return self.results
232
233 response = self.create_update_customimage()
234
235 self.results['changed'] = True
236 self.log("Creation / Update done")
237 elif self.to_do == Actions.Delete:
238 self.log("Custom Image instance deleted")
239 self.results['changed'] = True
240
241 if self.check_mode:
242 return self.results
243
244 self.delete_customimage()
245 # This currently doesnt' work as there is a bug in SDK / Service
246 if isinstance(response, LROPoller):
247 response = self.get_poller_result(response)
248 else:
249 self.log("Custom Image instance unchanged")
250 self.results['changed'] = False
251 response = old_response
252
253 if self.state == 'present':
254 self.results.update({
255 'id': response.get('id', None)
256 })
257 return self.results
258
259 def create_update_customimage(self):
260 '''
261 Creates or updates Custom Image with the specified configuration.
262
263 :return: deserialized Custom Image instance state dictionary
264 '''
265 self.log("Creating / Updating the Custom Image instance {0}".format(self.name))
266
267 try:
268 response = self.mgmt_client.custom_images.begin_create_or_update(resource_group_name=self.resource_group,
269 lab_name=self.lab_name,
270 name=self.name,
271 custom_image=self.custom_image)
272 if isinstance(response, LROPoller):
273 response = self.get_poller_result(response)
274
275 except Exception as exc:
276 self.log('Error attempting to create the Custom Image instance.')
277 self.fail("Error creating the Custom Image instance: {0}".format(str(exc)))
278 return response.as_dict()
279
280 def delete_customimage(self):
281 '''
282 Deletes specified Custom Image instance in the specified subscription and resource group.
283
284 :return: True
285 '''
286 self.log("Deleting the Custom Image instance {0}".format(self.name))
287 try:
288 response = self.mgmt_client.custom_images.begin_delete(resource_group_name=self.resource_group,
289 lab_name=self.lab_name,
290 name=self.name)
291 except Exception as e:
292 self.log('Error attempting to delete the Custom Image instance.')
293 self.fail("Error deleting the Custom Image instance: {0}".format(str(e)))
294
295 return True
296
297 def get_customimage(self):
298 '''
299 Gets the properties of the specified Custom Image.
300
301 :return: deserialized Custom Image instance state dictionary
302 '''
303 self.log("Checking if the Custom Image instance {0} is present".format(self.name))
304 found = False
305 try:
306 response = self.mgmt_client.custom_images.get(resource_group_name=self.resource_group,
307 lab_name=self.lab_name,
308 name=self.name)
309 found = True
310 self.log("Response : {0}".format(response))
311 self.log("Custom Image instance : {0} found".format(response.name))
312 except ResourceNotFoundError as e:
313 self.log('Did not find the Custom Image instance.')
314 if found is True:
315 return response.as_dict()
316
317 return False
318
319
320 def default_compare(new, old, path, result):
321 if new is None:
322 return True
323 elif isinstance(new, dict):
324 if not isinstance(old, dict):
325 result['compare'] = 'changed [' + path + '] old dict is null'
326 return False
327 for k in new.keys():
328 if not default_compare(new.get(k), old.get(k, None), path + '/' + k, result):
329 return False
330 return True
331 elif isinstance(new, list):
332 if not isinstance(old, list) or len(new) != len(old):
333 result['compare'] = 'changed [' + path + '] length is different or null'
334 return False
335 if isinstance(old[0], dict):
336 key = None
337 if 'id' in old[0] and 'id' in new[0]:
338 key = 'id'
339 elif 'name' in old[0] and 'name' in new[0]:
340 key = 'name'
341 else:
342 key = list(old[0])[0]
343 new = sorted(new, key=lambda x: x.get(key, None))
344 old = sorted(old, key=lambda x: x.get(key, None))
345 else:
346 new = sorted(new)
347 old = sorted(old)
348 for i in range(len(new)):
349 if not default_compare(new[i], old[i], path + '/*', result):
350 return False
351 return True
352 else:
353 if path == '/location':
354 new = new.replace(' ', '').lower()
355 old = new.replace(' ', '').lower()
356 if new == old:
357 return True
358 else:
359 result['compare'] = 'changed [' + path + '] ' + str(new) + ' != ' + str(old)
360 return False
361
362
363 def dict_camelize(d, path, camelize_first):
364 if isinstance(d, list):
365 for i in range(len(d)):
366 dict_camelize(d[i], path, camelize_first)
367 elif isinstance(d, dict):
368 if len(path) == 1:
369 old_value = d.get(path[0], None)
370 if old_value is not None:
371 d[path[0]] = _snake_to_camel(old_value, camelize_first)
372 else:
373 sd = d.get(path[0], None)
374 if sd is not None:
375 dict_camelize(sd, path[1:], camelize_first)
376
377
378 def main():
379 """Main execution"""
380 AzureRMDtlCustomImage()
381
382
383 if __name__ == '__main__':
384 main()