| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
|
| 11 |
DOCUMENTATION = ''' |
| 12 |
--- |
| 13 |
module: azure_rm_devtestlabschedule |
| 14 |
version_added: "0.1.2" |
| 15 |
short_description: Manage Azure DevTest Lab Schedule instance |
| 16 |
description: |
| 17 |
- Create, update and delete instance of Azure DecTest Lab Schedule. |
| 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 schedule. |
| 33 |
required: True |
| 34 |
type: str |
| 35 |
choices: |
| 36 |
- lab_vms_startup |
| 37 |
- lab_vms_shutdown |
| 38 |
time: |
| 39 |
description: |
| 40 |
- The time of day the schedule will occur. |
| 41 |
type: str |
| 42 |
time_zone_id: |
| 43 |
description: |
| 44 |
- The time zone ID. |
| 45 |
type: str |
| 46 |
state: |
| 47 |
description: |
| 48 |
- Assert the state of the Schedule. |
| 49 |
- Use C(present) to create or update an Schedule and C(absent) to delete it. |
| 50 |
default: present |
| 51 |
type: str |
| 52 |
choices: |
| 53 |
- absent |
| 54 |
- present |
| 55 |
|
| 56 |
extends_documentation_fragment: |
| 57 |
- azure.azcollection.azure |
| 58 |
- azure.azcollection.azure_tags |
| 59 |
|
| 60 |
author: |
| 61 |
- Zim Kalinowski (@zikalino) |
| 62 |
|
| 63 |
''' |
| 64 |
|
| 65 |
EXAMPLES = ''' |
| 66 |
- name: Create (or update) DevTest Lab Schedule |
| 67 |
azure_rm_devtestlabschedule: |
| 68 |
resource_group: myResourceGroup |
| 69 |
lab_name: myLab |
| 70 |
name: lab_vms_shutdown |
| 71 |
time: "1030" |
| 72 |
time_zone_id: "UTC+12" |
| 73 |
''' |
| 74 |
|
| 75 |
RETURN = ''' |
| 76 |
id: |
| 77 |
description: |
| 78 |
- The identifier of the resource. |
| 79 |
returned: always |
| 80 |
type: str |
| 81 |
sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/microsoft.devtestlab/labs/myLab/schedules/l |
| 82 |
abVmsShutdown" |
| 83 |
''' |
| 84 |
|
| 85 |
from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase |
| 86 |
|
| 87 |
try: |
| 88 |
from azure.core.polling import LROPoller |
| 89 |
from azure.core.exceptions import ResourceNotFoundError |
| 90 |
from azure.mgmt.devtestlabs import DevTestLabsClient |
| 91 |
except ImportError: |
| 92 |
|
| 93 |
pass |
| 94 |
|
| 95 |
|
| 96 |
class Actions: |
| 97 |
NoAction, Create, Update, Delete = range(4) |
| 98 |
|
| 99 |
|
| 100 |
class AzureRMSchedule(AzureRMModuleBase): |
| 101 |
"""Configuration class for an Azure RM Schedule resource""" |
| 102 |
|
| 103 |
def __init__(self): |
| 104 |
self.module_arg_spec = dict( |
| 105 |
resource_group=dict( |
| 106 |
type='str', |
| 107 |
required=True |
| 108 |
), |
| 109 |
lab_name=dict( |
| 110 |
type='str', |
| 111 |
required=True |
| 112 |
), |
| 113 |
name=dict( |
| 114 |
type='str', |
| 115 |
required=True, |
| 116 |
choices=['lab_vms_startup', 'lab_vms_shutdown'] |
| 117 |
), |
| 118 |
time=dict( |
| 119 |
type='str' |
| 120 |
), |
| 121 |
time_zone_id=dict( |
| 122 |
type='str' |
| 123 |
), |
| 124 |
state=dict( |
| 125 |
type='str', |
| 126 |
default='present', |
| 127 |
choices=['present', 'absent'] |
| 128 |
) |
| 129 |
) |
| 130 |
|
| 131 |
self.resource_group = None |
| 132 |
self.lab_name = None |
| 133 |
self.name = None |
| 134 |
self.schedule = dict() |
| 135 |
|
| 136 |
self.results = dict(changed=False) |
| 137 |
self.mgmt_client = None |
| 138 |
self.state = None |
| 139 |
self.to_do = Actions.NoAction |
| 140 |
|
| 141 |
required_if = [ |
| 142 |
('state', 'present', ['time', 'time_zone_id']) |
| 143 |
] |
| 144 |
|
| 145 |
super(AzureRMSchedule, self).__init__(derived_arg_spec=self.module_arg_spec, |
| 146 |
supports_check_mode=True, |
| 147 |
supports_tags=True, |
| 148 |
required_if=required_if) |
| 149 |
|
| 150 |
def exec_module(self, **kwargs): |
| 151 |
"""Main module execution method""" |
| 152 |
|
| 153 |
for key in list(self.module_arg_spec.keys()) + ['tags']: |
| 154 |
if hasattr(self, key): |
| 155 |
setattr(self, key, kwargs[key]) |
| 156 |
elif kwargs[key] is not None: |
| 157 |
self.schedule[key] = kwargs[key] |
| 158 |
|
| 159 |
self.schedule['status'] = "Enabled" |
| 160 |
|
| 161 |
if self.name == 'lab_vms_startup': |
| 162 |
self.name = 'LabVmsStartup' |
| 163 |
self.schedule['task_type'] = 'LabVmsStartupTask' |
| 164 |
elif self.name == 'lab_vms_shutdown': |
| 165 |
self.name = 'LabVmsShutdown' |
| 166 |
self.schedule['task_type'] = 'LabVmsShutdownTask' |
| 167 |
|
| 168 |
if self.state == 'present': |
| 169 |
self.schedule['daily_recurrence'] = {'time': self.schedule.pop('time')} |
| 170 |
self.schedule['time_zone_id'] = self.schedule['time_zone_id'].upper() |
| 171 |
|
| 172 |
response = None |
| 173 |
|
| 174 |
self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient, |
| 175 |
base_url=self._cloud_environment.endpoints.resource_manager) |
| 176 |
|
| 177 |
resource_group = self.get_resource_group(self.resource_group) |
| 178 |
|
| 179 |
old_response = self.get_schedule() |
| 180 |
|
| 181 |
if not old_response: |
| 182 |
self.log("Schedule instance doesn't exist") |
| 183 |
if self.state == 'absent': |
| 184 |
self.log("Old instance didn't exist") |
| 185 |
else: |
| 186 |
self.to_do = Actions.Create |
| 187 |
else: |
| 188 |
self.log("Schedule instance already exists") |
| 189 |
if self.state == 'absent': |
| 190 |
self.to_do = Actions.Delete |
| 191 |
elif self.state == 'present': |
| 192 |
if (not default_compare(self.schedule, old_response, '', self.results)): |
| 193 |
self.to_do = Actions.Update |
| 194 |
|
| 195 |
if (self.to_do == Actions.Create) or (self.to_do == Actions.Update): |
| 196 |
self.log("Need to Create / Update the Schedule instance") |
| 197 |
|
| 198 |
if self.check_mode: |
| 199 |
self.results['changed'] = True |
| 200 |
return self.results |
| 201 |
|
| 202 |
response = self.create_update_schedule() |
| 203 |
|
| 204 |
self.results['changed'] = True |
| 205 |
self.log("Creation / Update done") |
| 206 |
elif self.to_do == Actions.Delete: |
| 207 |
self.log("Schedule instance deleted") |
| 208 |
self.results['changed'] = True |
| 209 |
|
| 210 |
if self.check_mode: |
| 211 |
return self.results |
| 212 |
|
| 213 |
self.delete_schedule() |
| 214 |
|
| 215 |
if isinstance(response, LROPoller): |
| 216 |
response = self.get_poller_result(response) |
| 217 |
else: |
| 218 |
self.log("Schedule instance unchanged") |
| 219 |
self.results['changed'] = False |
| 220 |
response = old_response |
| 221 |
|
| 222 |
if self.state == 'present': |
| 223 |
self.results.update({ |
| 224 |
'id': response.get('id', None) |
| 225 |
}) |
| 226 |
return self.results |
| 227 |
|
| 228 |
def create_update_schedule(self): |
| 229 |
''' |
| 230 |
Creates or updates Schedule with the specified configuration. |
| 231 |
|
| 232 |
:return: deserialized Schedule instance state dictionary |
| 233 |
''' |
| 234 |
self.log("Creating / Updating the Schedule instance {0}".format(self.name)) |
| 235 |
|
| 236 |
try: |
| 237 |
response = self.mgmt_client.schedules.create_or_update(resource_group_name=self.resource_group, |
| 238 |
lab_name=self.lab_name, |
| 239 |
name=self.name, |
| 240 |
schedule=self.schedule) |
| 241 |
if isinstance(response, LROPoller): |
| 242 |
response = self.get_poller_result(response) |
| 243 |
|
| 244 |
except Exception as exc: |
| 245 |
self.log('Error attempting to create the Schedule instance.') |
| 246 |
self.fail("Error creating the Schedule instance: {0}".format(str(exc))) |
| 247 |
return response.as_dict() |
| 248 |
|
| 249 |
def delete_schedule(self): |
| 250 |
''' |
| 251 |
Deletes specified Schedule instance in the specified subscription and resource group. |
| 252 |
|
| 253 |
:return: True |
| 254 |
''' |
| 255 |
self.log("Deleting the Schedule instance {0}".format(self.name)) |
| 256 |
try: |
| 257 |
response = self.mgmt_client.schedules.delete(resource_group_name=self.resource_group, |
| 258 |
lab_name=self.lab_name, |
| 259 |
name=self.name) |
| 260 |
except Exception as e: |
| 261 |
self.log('Error attempting to delete the Schedule instance.') |
| 262 |
self.fail("Error deleting the Schedule instance: {0}".format(str(e))) |
| 263 |
|
| 264 |
return True |
| 265 |
|
| 266 |
def get_schedule(self): |
| 267 |
''' |
| 268 |
Gets the properties of the specified Schedule. |
| 269 |
|
| 270 |
:return: deserialized Schedule instance state dictionary |
| 271 |
''' |
| 272 |
self.log("Checking if the Schedule instance {0} is present".format(self.name)) |
| 273 |
found = False |
| 274 |
try: |
| 275 |
response = self.mgmt_client.schedules.get(resource_group_name=self.resource_group, |
| 276 |
lab_name=self.lab_name, |
| 277 |
name=self.name) |
| 278 |
found = True |
| 279 |
self.log("Response : {0}".format(response)) |
| 280 |
self.log("Schedule instance : {0} found".format(response.name)) |
| 281 |
except ResourceNotFoundError as e: |
| 282 |
self.log('Did not find the Schedule instance.') |
| 283 |
if found is True: |
| 284 |
return response.as_dict() |
| 285 |
|
| 286 |
return False |
| 287 |
|
| 288 |
|
| 289 |
def default_compare(new, old, path, result): |
| 290 |
if new is None: |
| 291 |
return True |
| 292 |
elif isinstance(new, dict): |
| 293 |
if not isinstance(old, dict): |
| 294 |
result['compare'] = 'changed [' + path + '] old dict is null' |
| 295 |
return False |
| 296 |
for k in new.keys(): |
| 297 |
if not default_compare(new.get(k), old.get(k, None), path + '/' + k, result): |
| 298 |
return False |
| 299 |
return True |
| 300 |
elif isinstance(new, list): |
| 301 |
if not isinstance(old, list) or len(new) != len(old): |
| 302 |
result['compare'] = 'changed [' + path + '] length is different or null' |
| 303 |
return False |
| 304 |
if isinstance(old[0], dict): |
| 305 |
key = None |
| 306 |
if 'id' in old[0] and 'id' in new[0]: |
| 307 |
key = 'id' |
| 308 |
elif 'name' in old[0] and 'name' in new[0]: |
| 309 |
key = 'name' |
| 310 |
else: |
| 311 |
key = list(old[0])[0] |
| 312 |
new = sorted(new, key=lambda x: x.get(key, None)) |
| 313 |
old = sorted(old, key=lambda x: x.get(key, None)) |
| 314 |
else: |
| 315 |
new = sorted(new) |
| 316 |
old = sorted(old) |
| 317 |
for i in range(len(new)): |
| 318 |
if not default_compare(new[i], old[i], path + '/*', result): |
| 319 |
return False |
| 320 |
return True |
| 321 |
else: |
| 322 |
if path == '/location': |
| 323 |
new = new.replace(' ', '').lower() |
| 324 |
old = new.replace(' ', '').lower() |
| 325 |
if new == old: |
| 326 |
return True |
| 327 |
else: |
| 328 |
result['compare'] = 'changed [' + path + '] ' + str(new) + ' != ' + str(old) |
| 329 |
return False |
| 330 |
|
| 331 |
|
| 332 |
def main(): |
| 333 |
"""Main execution""" |
| 334 |
AzureRMSchedule() |
| 335 |
|
| 336 |
|
| 337 |
if __name__ == '__main__': |
| 338 |
main() |