Debian Codegraph @

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