Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2018 Hai Cao, <[email protected]> Yunge Zhu <[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 DOCUMENTATION = '''
11 ---
12 module: azure_rm_trafficmanagerprofile
13 version_added: "0.1.2"
14 short_description: Manage Azure Traffic Manager profile
15 description:
16 - Create, update and delete a Traffic Manager profile.
17
18 options:
19 resource_group:
20 description:
21 - Name of a resource group where the Traffic Manager profile exists or will be created.
22 required: true
23 type: str
24 name:
25 description:
26 - Name of the Traffic Manager profile.
27 required: true
28 type: str
29 state:
30 description:
31 - Assert the state of the Traffic Manager profile. Use C(present) to create or update a Traffic Manager profile and C(absent) to delete it.
32 default: present
33 type: str
34 choices:
35 - absent
36 - present
37 location:
38 description:
39 - Valid Azure location. Defaults to C(global) because in default public Azure cloud, Traffic Manager profile can only be deployed globally.
40 - Reference U(https://docs.microsoft.com/en-us/azure/traffic-manager/quickstart-create-traffic-manager-profile#create-a-traffic-manager-profile).
41 type: str
42 default: global
43 profile_status:
44 description:
45 - The status of the Traffic Manager profile.
46 default: enabled
47 type: str
48 choices:
49 - enabled
50 - disabled
51 routing_method:
52 description:
53 - The traffic routing method of the Traffic Manager profile.
54 default: performance
55 type: str
56 choices:
57 - performance
58 - priority
59 - weighted
60 - geographic
61 dns_config:
62 description:
63 - The DNS settings of the Traffic Manager profile.
64 type: dict
65 suboptions:
66 relative_name:
67 description:
68 - The relative DNS name provided by this Traffic Manager profile.
69 - If not provided, name of the Traffic Manager will be used.
70 type: str
71 ttl:
72 description:
73 - The DNS Time-To-Live (TTL), in seconds.
74 type: int
75 monitor_config:
76 description:
77 - The endpoint monitoring settings of the Traffic Manager profile.
78 type: dict
79 suboptions:
80 profile_monitor_status:
81 description:
82 - The profile-level monitoring status of the Traffic Manager.
83 type: str
84 choices:
85 - CheckingEndpoint
86 - Online
87 - Degraded
88 - Inactive
89 - Stopped
90 - Disabled
91 protocol:
92 description:
93 - The protocol C(HTTP), C(HTTPS) or C(TCP) used to probe for endpoint health.
94 type: str
95 choices:
96 - HTTPS
97 - HTTP
98 - TCP
99 port:
100 description:
101 - The TCP port used to probe for endpoint health.
102 type: int
103 path:
104 description:
105 - The path relative to the endpoint domain name used to probe for endpoint health.
106 type: str
107 interval:
108 description:
109 - The monitor interval for endpoints in this profile in seconds.
110 type: int
111 timeout:
112 description:
113 - The monitor timeout for endpoints in this profile in seconds.
114 type: int
115 tolerated_failures:
116 description:
117 - The number of consecutive failed health check before declaring an endpoint in this profile Degraded after the next failed health check.
118 type: int
119 custom_headers:
120 description:
121 - List of custom headers.
122 type: list
123 elements: dict
124 suboptions:
125 name:
126 description:
127 - Header name.
128 type: str
129 required: true
130 value:
131 description:
132 - Header value.
133 type: str
134 required: true
135 expected_status_code_ranges:
136 description:
137 - List of expected status code ranges.
138 type: list
139 elements: dict
140 suboptions:
141 max:
142 description:
143 - Max status code.
144 type: int
145 required: true
146 min:
147 description:
148 - Min status code.
149 type: int
150 required: true
151 default:
152 protocol: HTTP
153 port: 80
154 path: /
155 max_return:
156 description:
157 - Maximum number of endpoints to be returned for MultiValue routing type.
158 type: int
159 allowed_endpoint_record_types:
160 description:
161 - The list of allowed endpoint record types.
162 type: list
163 elements: str
164 choices:
165 - DomainName
166 - IPv4Address
167 - IPv6Address
168 - Any
169
170 extends_documentation_fragment:
171 - azure.azcollection.azure
172 - azure.azcollection.azure_tags
173
174 author:
175 - Hai Cao (@caohai)
176 - Yunge Zhu (@yungezz)
177
178 '''
179
180 EXAMPLES = '''
181 - name: Create a Traffic Manager Profile
182 azure_rm_trafficmanagerprofile:
183 name: tmtest
184 resource_group: myResourceGroup
185 location: global
186 profile_status: enabled
187 routing_method: priority
188 dns_config:
189 relative_name: tmtest
190 ttl: 60
191 monitor_config:
192 protocol: HTTPS
193 port: 80
194 path: '/'
195 tags:
196 Environment: Test
197
198 - name: Delete a Traffic Manager Profile
199 azure_rm_trafficmanagerprofile:
200 state: absent
201 name: tmtest
202 resource_group: myResourceGroup
203 '''
204 RETURN = '''
205 id:
206 description:
207 - The ID of the traffic manager profile.
208 returned: when traffic manager profile exists
209 type: str
210 sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/tmt/providers/Microsoft.Network/trafficManagerProfiles/tmtest"
211 endpoints:
212 description:
213 - List of endpoint IDs attached to the profile.
214 returned: when traffic manager endpoints exists
215 type: list
216 sample: [
217 "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/tmt/providers/Microsoft.Network/trafficManagerProfiles/tm049b1ae293/exter
218 nalEndpoints/e2",
219 "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/tmt/providers/Microsoft.Network/trafficManagerProfiles/tm049b1ae293/exter
220 nalEndpoints/e1"
221 ]
222 '''
223 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import normalize_location_name
224 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
225
226 try:
227 from azure.core.exceptions import ResourceNotFoundError
228 from azure.mgmt.trafficmanager.models import (
229 Profile, DnsConfig, MonitorConfig, MonitorConfigExpectedStatusCodeRangesItem, MonitorConfigCustomHeadersItem
230 )
231 except ImportError:
232 # This is handled in azure_rm_common
233 pass
234
235
236 def shorten_traffic_manager_dict(tmd):
237 return dict(
238 id=tmd['id'],
239 endpoints=[endpoint['id'] for endpoint in tmd['endpoints']] if tmd['endpoints'] else []
240 )
241
242
243 def traffic_manager_profile_to_dict(tmp):
244 result = dict(
245 id=tmp.id,
246 name=tmp.name,
247 type=tmp.type,
248 tags=tmp.tags,
249 location=tmp.location,
250 profile_status=tmp.profile_status,
251 routing_method=tmp.traffic_routing_method,
252 dns_config=dict(),
253 monitor_config=dict(),
254 endpoints=[],
255 max_return=tmp.max_return,
256 allowed_endpoint_record_types=tmp.allowed_endpoint_record_types
257 )
258 if tmp.dns_config:
259 result['dns_config']['relative_name'] = tmp.dns_config.relative_name
260 result['dns_config']['fqdn'] = tmp.dns_config.fqdn
261 result['dns_config']['ttl'] = tmp.dns_config.ttl
262 if tmp.monitor_config:
263 result['monitor_config']['profile_monitor_status'] = tmp.monitor_config.profile_monitor_status
264 result['monitor_config']['protocol'] = tmp.monitor_config.protocol
265 result['monitor_config']['port'] = tmp.monitor_config.port
266 result['monitor_config']['path'] = tmp.monitor_config.path
267 result['monitor_config']['interval'] = tmp.monitor_config.interval_in_seconds
268 result['monitor_config']['timeout'] = tmp.monitor_config.timeout_in_seconds
269 result['monitor_config']['tolerated_failures'] = tmp.monitor_config.tolerated_number_of_failures
270 if tmp.monitor_config.expected_status_code_ranges is not None:
271 result['monitor_config']['expected_status_code_ranges'] = [dict(min=x.min, max=x.max) for x in tmp.monitor_config.expected_status_code_ranges]
272 else:
273 result['monitor_config']['expected_status_code_ranges'] = None
274 if tmp.monitor_config.custom_headers is not None:
275 result['monitor_config']['custom_headers'] = [dict(name=x.name, value=x.value) for x in tmp.monitor_config.custom_headers]
276 else:
277 result['monitor_config']['custom_headers'] = None
278 if tmp.endpoints:
279 for endpoint in tmp.endpoints:
280 result['endpoints'].append(dict(
281 id=endpoint.id,
282 name=endpoint.name,
283 type=endpoint.type,
284 target_resource_id=endpoint.target_resource_id,
285 target=endpoint.target,
286 endpoint_status=endpoint.endpoint_status,
287 weight=endpoint.weight,
288 priority=endpoint.priority,
289 endpoint_location=endpoint.endpoint_location,
290 endpoint_monitor_status=endpoint.endpoint_monitor_status,
291 min_child_endpoints=endpoint.min_child_endpoints,
292 geo_mapping=endpoint.geo_mapping
293 ))
294 return result
295
296
297 def create_dns_config_instance(dns_config):
298 return DnsConfig(
299 relative_name=dns_config['relative_name'],
300 ttl=dns_config['ttl']
301 )
302
303
304 def create_monitor_config_instance(monitor_config):
305
306 custom_headers = []
307 expected_status_code_ranges = []
308 if monitor_config.get('custom_headers') is not None:
309 for item in monitor_config['custom_headers']:
310 custom_headers.append(MonitorConfigCustomHeadersItem(name=item['name'], value=item['value']))
311 else:
312 custom_headers = None
313 if monitor_config.get('expected_status_code_ranges') is not None:
314 for item in monitor_config['expected_status_code_ranges']:
315 expected_status_code_ranges.append(MonitorConfigExpectedStatusCodeRangesItem(min=item['min'], max=item['max']))
316 else:
317 expected_status_code_ranges = None
318
319 return MonitorConfig(
320 profile_monitor_status=monitor_config.get('profile_monitor_status'),
321 protocol=monitor_config.get('protocol'),
322 port=monitor_config.get('port'),
323 path=monitor_config.get('path'),
324 interval_in_seconds=monitor_config.get('interval'),
325 timeout_in_seconds=monitor_config.get('timeout'),
326 tolerated_number_of_failures=monitor_config.get('tolerated_failures'),
327 custom_headers=custom_headers,
328 expected_status_code_ranges=expected_status_code_ranges
329 )
330
331
332 dns_config_spec = dict(
333 relative_name=dict(type='str'),
334 ttl=dict(type='int')
335 )
336
337 monitor_config_spec = dict(
338 profile_monitor_status=dict(type='str', choices=['CheckingEndpoint', 'Online', 'Degraded', 'Disabled', 'Inactive', 'Stopped']),
339 protocol=dict(type='str', choices=['HTTP', 'HTTPS', 'TCP']),
340 port=dict(type='int'),
341 path=dict(type='str'),
342 interval=dict(type='int'),
343 timeout=dict(type='int'),
344 tolerated_failures=dict(type='int'),
345 custom_headers=dict(
346 type='list',
347 elements='dict',
348 options=dict(
349 name=dict(type='str', required=True),
350 value=dict(type='str', required=True)
351 )
352 ),
353 expected_status_code_ranges=dict(
354 type='list',
355 elements='dict',
356 options=dict(
357 min=dict(type='int', required=True),
358 max=dict(type='int', required=True)
359 )
360 )
361 )
362
363
364 class AzureRMTrafficManagerProfile(AzureRMModuleBaseExt):
365
366 def __init__(self):
367 self.module_arg_spec = dict(
368 resource_group=dict(
369 type='str',
370 required=True
371 ),
372 name=dict(
373 type='str',
374 required=True
375 ),
376 state=dict(
377 type='str',
378 default='present',
379 choices=['present', 'absent']
380 ),
381 location=dict(
382 type='str',
383 default='global'
384 ),
385 profile_status=dict(
386 type='str',
387 default='enabled',
388 choices=['enabled', 'disabled']
389 ),
390 routing_method=dict(
391 type='str',
392 default='performance',
393 choices=['performance', 'priority', 'weighted', 'geographic']
394 ),
395 dns_config=dict(
396 type='dict',
397 options=dns_config_spec
398 ),
399 monitor_config=dict(
400 type='dict',
401 default=dict(
402 protocol='HTTP',
403 port=80,
404 path='/'
405 ),
406 options=monitor_config_spec
407 ),
408 max_return=dict(
409 type='int'
410 ),
411 allowed_endpoint_record_types=dict(
412 type='list',
413 elements='str',
414 choices=['DomainName', 'IPv4Address', 'IPv6Address', 'Any']
415 ),
416 )
417
418 self.resource_group = None
419 self.name = None
420 self.state = None
421 self.tags = None
422 self.location = None
423 self.profile_status = None
424 self.routing_method = None
425 self.dns_config = None
426 self.monitor_config = None
427 self.endpoints_copy = None
428 self.max_return = None
429 self.allowed_endpoint_record_types = None
430
431 self.results = dict(
432 changed=False
433 )
434
435 super(AzureRMTrafficManagerProfile, self).__init__(derived_arg_spec=self.module_arg_spec,
436 supports_check_mode=True,
437 supports_tags=True)
438
439 def exec_module(self, **kwargs):
440
441 for key in list(self.module_arg_spec.keys()) + ['tags']:
442 setattr(self, key, kwargs[key])
443
444 to_be_updated = False
445
446 if not self.dns_config:
447 self.dns_config = dict(
448 relative_name=self.name,
449 ttl=60
450 )
451
452 if not self.location:
453 self.location = 'global'
454
455 response = self.get_traffic_manager_profile()
456
457 if self.state == 'present':
458 if not response:
459 to_be_updated = True
460 else:
461 self.results = shorten_traffic_manager_dict(response)
462 self.log('Results : {0}'.format(response))
463 update_tags, response['tags'] = self.update_tags(response['tags'])
464
465 if update_tags:
466 to_be_updated = True
467
468 to_be_updated = to_be_updated or self.check_update(response)
469
470 if to_be_updated:
471 self.log("Need to Create / Update the Traffic Manager profile")
472
473 if not self.check_mode:
474 self.results = shorten_traffic_manager_dict(self.create_update_traffic_manager_profile())
475 self.log("Creation / Update done.")
476
477 self.results['changed'] = True
478 return self.results
479
480 elif self.state == 'absent' and response:
481 self.log("Need to delete the Traffic Manager profile")
482 self.results = shorten_traffic_manager_dict(response)
483 self.results['changed'] = True
484
485 if self.check_mode:
486 return self.results
487
488 self.delete_traffic_manager_profile()
489
490 self.log("Traffic Manager profile deleted")
491
492 return self.results
493
494 def get_traffic_manager_profile(self):
495 '''
496 Gets the properties of the specified Traffic Manager profile
497
498 :return: deserialized Traffic Manager profile dict
499 '''
500 self.log("Checking if Traffic Manager profile {0} is present".format(self.name))
501 try:
502 response = self.traffic_manager_management_client.profiles.get(self.resource_group, self.name)
503 self.log("Response : {0}".format(response))
504 self.log("Traffic Manager profile : {0} found".format(response.name))
505 self.endpoints_copy = response.endpoints if response and response.endpoints else None
506 return traffic_manager_profile_to_dict(response)
507 except ResourceNotFoundError:
508 self.log('Did not find the Traffic Manager profile.')
509 return False
510
511 def delete_traffic_manager_profile(self):
512 '''
513 Deletes the specified Traffic Manager profile in the specified subscription and resource group.
514 :return: True
515 '''
516
517 self.log("Deleting the Traffic Manager profile {0}".format(self.name))
518 try:
519 self.traffic_manager_management_client.profiles.delete(self.resource_group, self.name)
520 return True
521 except Exception as e:
522 self.log('Error attempting to delete the Traffic Manager profile.')
523 self.fail("Error deleting the Traffic Manager profile: {0}".format(e.message))
524 return False
525
526 def create_update_traffic_manager_profile(self):
527 '''
528 Creates or updates a Traffic Manager profile.
529
530 :return: deserialized Traffic Manager profile state dictionary
531 '''
532 self.log("Creating / Updating the Traffic Manager profile {0}".format(self.name))
533
534 parameters = Profile(
535 tags=self.tags,
536 location=self.location,
537 profile_status=self.profile_status,
538 traffic_routing_method=self.routing_method,
539 dns_config=create_dns_config_instance(self.dns_config) if self.dns_config else None,
540 monitor_config=create_monitor_config_instance(self.monitor_config) if self.monitor_config else None,
541 endpoints=self.endpoints_copy,
542 max_return=self.max_return,
543 allowed_endpoint_record_types=self.allowed_endpoint_record_types
544 )
545 try:
546 response = self.traffic_manager_management_client.profiles.create_or_update(self.resource_group, self.name, parameters)
547 return traffic_manager_profile_to_dict(response)
548 except Exception as exc:
549 self.log('Error attempting to create the Traffic Manager.')
550 self.fail("Error creating the Traffic Manager: {0}".format(exc.message))
551
552 def check_update(self, response):
553 if self.location and normalize_location_name(response['location']) != normalize_location_name(self.location):
554 self.log("Location Diff - Origin {0} / Update {1}".format(response['location'], self.location))
555 return True
556
557 if self.profile_status and response['profile_status'].lower() != self.profile_status:
558 self.log("Profile Status Diff - Origin {0} / Update {1}".format(response['profile_status'], self.profile_status))
559 return True
560
561 if self.routing_method and response['routing_method'].lower() != self.routing_method:
562 self.log("Traffic Routing Method Diff - Origin {0} / Update {1}".format(response['routing_method'], self.routing_method))
563 return True
564
565 if self.dns_config and \
566 (response['dns_config']['relative_name'] != self.dns_config['relative_name'] or response['dns_config']['ttl'] != self.dns_config['ttl']):
567 self.log("DNS Config Diff - Origin {0} / Update {1}".format(response['dns_config'], self.dns_config))
568 return True
569
570 if self.max_return and response['max_return'] != self.max_return:
571 self.log("Profile max_return Diff - Origin {0} / Update {1}".format(response['max_return'], self.max_return))
572 return True
573 else:
574 self.max_return = response['max_return']
575
576 if not self.default_compare({}, self.allowed_endpoint_record_types, response['allowed_endpoint_record_types'], '', dict(compare=[])):
577 self.log("Profile allowed_endpoint_record_types Diff - Origin {0} / Update {1}".format(response['allowed_endpoint_record_types'],
578 self.allowed_endpoint_record_types))
579 return True
580
581 if not self.default_compare({}, self.monitor_config, response['monitor_config'], '', dict(compare=[])):
582 self.log("Monitor Config Diff - Origin {0} / Update {1}".format(response['monitor_config'], self.monitor_config))
583 return True
584
585 return False
586
587
588 def main():
589 """Main execution"""
590 AzureRMTrafficManagerProfile()
591
592
593 if __name__ == '__main__':
594 main()