Debian Codegraph @

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