Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2018 Hai Cao, <[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_trafficmanager
13 version_added: "0.1.2"
14 short_description: Manage a 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 'global'.
40 type: str
41 profile_status:
42 description:
43 - The status of the Traffic Manager profile.
44 default: Enabled
45 type: str
46 choices:
47 - Enabled
48 - Disabled
49 traffic_routing_method:
50 description:
51 - The traffic routing method of the Traffic Manager profile.
52 default: Performance
53 type: str
54 choices:
55 - Performance
56 - Priority
57 - Weighted
58 - Geographic
59 dns_config:
60 description:
61 - The DNS settings of the Traffic Manager profile.
62 type: dict
63 suboptions:
64 relative_name:
65 description:
66 - The relative DNS name provided by this Traffic Manager profile.
67 - If no provided, name of the Traffic Manager will be used
68 type: str
69 ttl:
70 description:
71 - The DNS Time-To-Live (TTL), in seconds.
72 type: int
73 monitor_config:
74 description:
75 - The endpoint monitoring settings of the Traffic Manager profile.
76 type: dict
77 suboptions:
78 profile_monitor_status:
79 description:
80 - The profile-level monitoring status of the Traffic Manager.
81 type: str
82 protocol:
83 description:
84 - The protocol (HTTP, HTTPS or TCP) used to probe for endpoint health.
85 type: str
86 choices:
87 - HTTP
88 - HTTPS
89 - TCP
90 port:
91 description:
92 - The TCP port used to probe for endpoint health.
93 type: int
94 path:
95 description:
96 - The path relative to the endpoint domain name used to probe for endpoint health.
97 type: str
98 interval_in_seconds:
99 description:
100 - The monitor interval for endpoints in this profile.
101 type: int
102 timeout_in_seconds:
103 description:
104 - The monitor timeout for endpoints in this profile.
105 type: int
106 tolerated_number_of_failures:
107 description:
108 - The number of consecutive failed health check before declaring an endpoint in this profile Degraded after the next failed health check.
109 type: int
110 default:
111 protocol: HTTP
112 port: 80
113 path: /
114 endpoints:
115 description:
116 - The list of endpoints in the Traffic Manager profile.
117 type: list
118 elements: dict
119 default: []
120 suboptions:
121 endpoint_monitor_status:
122 description:
123 - The monitoring status of the endpoint.
124 type: str
125 id:
126 description:
127 - Fully qualified resource Id for the resource.
128 type: str
129 name:
130 description:
131 - The name of the endpoint.
132 type: str
133 type:
134 description:
135 - The type of the endpoint. Ex- Microsoft.network/TrafficManagerProfiles/ExternalEndpoints.
136 type: str
137 target_resource_id:
138 description:
139 - The Azure Resource URI of the of the endpoint.
140 - Not applicable to endpoints of type 'ExternalEndpoints'.
141 type: str
142 target:
143 description:
144 - The fully-qualified DNS name of the endpoint.
145 type: str
146 endpoint_status:
147 description:
148 - The status of the endpoint.
149 type: str
150 choices:
151 - Enabled
152 - Disabled
153 weight:
154 description:
155 - The weight of this endpoint when using the 'Weighted' traffic routing method.
156 - Possible values are from 1 to 1000.
157 type: int
158 priority:
159 description:
160 - The priority of this endpoint when using the 'Priority' traffic routing method.
161 - Possible values are from 1 to 1000, lower values represent higher priority.
162 - This is an optional parameter. If specified, it must be specified on all endpoints.
163 - No two endpoints can share the same priority value.
164 type: int
165 endpoint_location:
166 description:
167 - Specifies the location of the external or nested endpoints when using the 'Performance' traffic routing method.
168 type: str
169 min_child_endpoints:
170 description:
171 - The minimum number of endpoints that must be available in the child profile in order for the parent profile to be considered available.
172 - Only applicable to endpoint of type 'NestedEndpoints'.
173 type: int
174 geo_mapping:
175 description:
176 - The list of countries/regions mapped to this endpoint when using the 'Geographic' traffic routing method.
177 type: list
178 elements: str
179
180 extends_documentation_fragment:
181 - azure.azcollection.azure
182 - azure.azcollection.azure_tags
183
184 author:
185 - Hai Cao (@caohai)
186
187 '''
188
189 EXAMPLES = '''
190 - name: Create a Traffic Manager Profile
191 azure_rm_trafficmanager:
192 name: tmtest
193 resource_group: tmt
194 location: global
195 profile_status: Enabled
196 traffic_routing_method: Priority
197 dns_config:
198 relative_name: tmtest
199 ttl: 60
200 monitor_config:
201 protocol: HTTPS
202 port: 80
203 path: '/'
204 endpoints:
205 - name: e1
206 type: Microsoft.network/TrafficManagerProfiles/ExternalEndpoints
207 endpoint_location: West US 2
208 endpoint_status: Enabled
209 priority: 2
210 target: 1.2.3.4
211 weight: 1
212 tags:
213 Environment: Test
214
215 - name: Delete a Traffic Manager Profile
216 azure_rm_trafficmanager:
217 state: absent
218 name: tmtest
219 resource_group: tmt
220 '''
221 RETURN = '''
222 state:
223 description: Current state of the Traffic Manager Profile
224 returned: always
225 type: dict
226 example:
227 "dns_config": {
228 "fqdn": "tmtest.trafficmanager.net",
229 "relative_name": "tmtest",
230 "ttl": 60
231 }
232 "endpoints": [
233 {
234 "endpoint_location": "West US 2",
235 "endpoint_monitor_status": "Degraded",
236 "endpoint_status": "Enabled",
237 "geo_mapping": null,
238 "id": "/subscriptions/XXXXXX...XXXXXXXXX/resourceGroups/tmt/providers/Microsoft.Network/trafficManagerProfiles/tmtest/externalEndpoints/e1",
239 "min_child_endpoints": null,
240 "name": "e1",
241 "priority": 2,
242 "target": "1.2.3.4",
243 "target_resource_id": null,
244 "type": "Microsoft.Network/trafficManagerProfiles/externalEndpoints",
245 "weight": 1
246 }
247 ]
248 "id": "/subscriptions/XXXXXX...XXXXXXXXX/resourceGroups/tmt/providers/Microsoft.Network/trafficManagerProfiles/tmtest"
249 "location": "global"
250 "monitor_config": {
251 "interval_in_seconds": 30,
252 "path": "/",
253 "port": 80,
254 "profile_monitor_status": "Degraded",
255 "protocol": "HTTPS",
256 "timeout_in_seconds": 10,
257 "tolerated_number_of_failures": 3
258 }
259 "name": "tmtest"
260 "profile_status": "Enabled"
261 "tags": {
262 "Environment": "Test"
263 }
264 "traffic_routing_method": "Priority"
265 "type": "Microsoft.Network/trafficManagerProfiles"
266 '''
267 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
268
269 try:
270 from azure.core.exceptions import ResourceNotFoundError
271 from azure.mgmt.trafficmanager.models import (
272 Profile, Endpoint, DnsConfig, MonitorConfig
273 )
274 except ImportError:
275 # This is handled in azure_rm_common
276 pass
277
278
279 def traffic_manager_profile_to_dict(tmp):
280 result = dict(
281 id=tmp.id,
282 name=tmp.name,
283 type=tmp.type,
284 tags=tmp.tags,
285 location=tmp.location,
286 profile_status=tmp.profile_status,
287 traffic_routing_method=tmp.traffic_routing_method,
288 dns_config=dict(),
289 monitor_config=dict(),
290 endpoints=[]
291 )
292 if tmp.dns_config:
293 result['dns_config']['relative_name'] = tmp.dns_config.relative_name
294 result['dns_config']['fqdn'] = tmp.dns_config.fqdn
295 result['dns_config']['ttl'] = tmp.dns_config.ttl
296 if tmp.monitor_config:
297 result['monitor_config']['profile_monitor_status'] = tmp.monitor_config.profile_monitor_status
298 result['monitor_config']['protocol'] = tmp.monitor_config.protocol
299 result['monitor_config']['port'] = tmp.monitor_config.port
300 result['monitor_config']['path'] = tmp.monitor_config.path
301 result['monitor_config']['interval_in_seconds'] = tmp.monitor_config.interval_in_seconds
302 result['monitor_config']['timeout_in_seconds'] = tmp.monitor_config.timeout_in_seconds
303 result['monitor_config']['tolerated_number_of_failures'] = tmp.monitor_config.tolerated_number_of_failures
304 if tmp.endpoints:
305 for endpoint in tmp.endpoints:
306 result['endpoints'].append(dict(
307 id=endpoint.id,
308 name=endpoint.name,
309 type=endpoint.type,
310 target_resource_id=endpoint.target_resource_id,
311 target=endpoint.target,
312 endpoint_status=endpoint.endpoint_status,
313 weight=endpoint.weight,
314 priority=endpoint.priority,
315 endpoint_location=endpoint.endpoint_location,
316 endpoint_monitor_status=endpoint.endpoint_monitor_status,
317 min_child_endpoints=endpoint.min_child_endpoints,
318 geo_mapping=endpoint.geo_mapping
319 ))
320 return result
321
322
323 def create_dns_config_instance(dns_config):
324 return DnsConfig(
325 relative_name=dns_config['relative_name'],
326 ttl=dns_config['ttl']
327 )
328
329
330 def create_monitor_config_instance(monitor_config):
331 return MonitorConfig(
332 profile_monitor_status=monitor_config['profile_monitor_status'],
333 protocol=monitor_config['protocol'],
334 port=monitor_config['port'],
335 path=monitor_config['path'],
336 interval_in_seconds=monitor_config['interval_in_seconds'],
337 timeout_in_seconds=monitor_config['timeout_in_seconds'],
338 tolerated_number_of_failures=monitor_config['tolerated_number_of_failures']
339 )
340
341
342 def create_endpoint_instance(endpoint):
343 return Endpoint(
344 id=endpoint['id'],
345 name=endpoint['name'],
346 type=endpoint['type'],
347 target_resource_id=endpoint['target_resource_id'],
348 target=endpoint['target'],
349 endpoint_status=endpoint['endpoint_status'],
350 weight=endpoint['weight'],
351 priority=endpoint['priority'],
352 endpoint_location=endpoint['endpoint_location'],
353 min_child_endpoints=endpoint['min_child_endpoints'],
354 geo_mapping=endpoint['geo_mapping']
355 )
356
357
358 def create_endpoints(endpoints):
359 return [create_endpoint_instance(endpoint) for endpoint in endpoints]
360
361
362 dns_config_spec = dict(
363 relative_name=dict(type='str'),
364 ttl=dict(type='int')
365 )
366
367 monitor_config_spec = dict(
368 profile_monitor_status=dict(type='str'),
369 protocol=dict(type='str', choices=['HTTP', 'HTTPS', 'TCP']),
370 port=dict(type='int'),
371 path=dict(type='str'),
372 interval_in_seconds=dict(type='int'),
373 timeout_in_seconds=dict(type='int'),
374 tolerated_number_of_failures=dict(type='int')
375 )
376
377 endpoint_spec = dict(
378 id=dict(type='str'),
379 name=dict(type='str'),
380 type=dict(type='str'),
381 target_resource_id=dict(type='str'),
382 target=dict(type='str'),
383 endpoint_status=dict(type='str', choices=['Enabled', 'Disabled']),
384 weight=dict(type='int'),
385 priority=dict(type='int'),
386 endpoint_location=dict(type='str'),
387 endpoint_monitor_status=dict(type='str'),
388 min_child_endpoints=dict(type='int'),
389 geo_mapping=dict(type='list', elements='str')
390 )
391
392
393 class AzureRMTrafficManager(AzureRMModuleBase):
394
395 def __init__(self):
396 self.module_arg_spec = dict(
397 resource_group=dict(
398 type='str',
399 required=True
400 ),
401 name=dict(
402 type='str',
403 required=True
404 ),
405 state=dict(
406 type='str',
407 default='present',
408 choices=['present', 'absent']
409 ),
410 location=dict(
411 type='str'
412 ),
413 profile_status=dict(
414 type='str',
415 default='Enabled',
416 choices=['Enabled', 'Disabled']
417 ),
418 traffic_routing_method=dict(
419 type='str',
420 default='Performance',
421 choices=['Performance', 'Priority', 'Weighted', 'Geographic']
422 ),
423 dns_config=dict(
424 type='dict',
425 options=dns_config_spec
426 ),
427 monitor_config=dict(
428 type='dict',
429 default=dict(
430 protocol='HTTP',
431 port=80,
432 path='/'
433 ),
434 options=monitor_config_spec
435 ),
436 endpoints=dict(
437 type='list',
438 elements='dict',
439 options=endpoint_spec,
440 default=[]
441 )
442 )
443
444 self.resource_group = None
445 self.name = None
446 self.state = None
447 self.tags = None
448 self.location = None
449 self.profile_status = None
450 self.traffic_routing_method = None
451 self.dns_config = None
452 self.monitor_config = None
453 self.endpoints = None
454
455 self.results = dict(
456 changed=False
457 )
458
459 super(AzureRMTrafficManager, self).__init__(derived_arg_spec=self.module_arg_spec, supports_check_mode=True)
460
461 def exec_module(self, **kwargs):
462
463 for key in list(self.module_arg_spec.keys()) + ['tags']:
464 setattr(self, key, kwargs[key])
465
466 to_be_updated = False
467
468 if not self.dns_config:
469 self.dns_config = dict(
470 relative_name=self.name,
471 ttl=60
472 )
473
474 if not self.location:
475 self.location = 'global'
476
477 response = self.get_traffic_manager_profile()
478
479 if self.state == 'present':
480 if not response:
481 to_be_updated = True
482 else:
483 self.results = response
484 self.log('Results : {0}'.format(response))
485 update_tags, response['tags'] = self.update_tags(response['tags'])
486
487 if update_tags:
488 to_be_updated = True
489
490 to_be_updated = to_be_updated or self.check_update(response)
491
492 if to_be_updated:
493 self.log("Need to Create / Update the Traffic Manager profile")
494
495 if not self.check_mode:
496 self.results = self.ceate_update_traffic_manager_profile()
497 self.log("Creation / Update done.")
498
499 self.results['changed'] = True
500 return self.results
501
502 elif self.state == 'absent' and response:
503 self.log("Need to delete the Traffic Manager profile")
504 self.results['changed'] = True
505
506 if self.check_mode:
507 return self.results
508
509 self.delete_traffic_manager_profile()
510
511 self.log("Traffic Manager profile deleted")
512
513 return self.results
514
515 def get_traffic_manager_profile(self):
516 '''
517 Gets the properties of the specified Traffic Manager profile
518
519 :return: deserialized Traffic Manager profile dict
520 '''
521 self.log("Checking if Traffic Manager profile {0} is present".format(self.name))
522 try:
523 response = self.traffic_manager_management_client.profiles.get(self.resource_group, self.name)
524 self.log("Response : {0}".format(response))
525 self.log("Traffic Manager profile : {0} found".format(response.name))
526 return traffic_manager_profile_to_dict(response)
527 except ResourceNotFoundError:
528 self.log('Did not find the Traffic Manager profile.')
529 return False
530
531 def delete_traffic_manager_profile(self):
532 '''
533 Deletes the specified Traffic Manager profile in the specified subscription and resource group.
534 :return: True
535 '''
536
537 self.log("Deleting the Traffic Manager profile {0}".format(self.name))
538 try:
539 operation_result = self.traffic_manager_management_client.profiles.delete(self.resource_group, self.name)
540 return True
541 except Exception as e:
542 self.log('Error attempting to delete the Traffic Manager profile.')
543 self.fail("Error deleting the Traffic Manager profile: {0}".format(e.message))
544 return False
545
546 def ceate_update_traffic_manager_profile(self):
547 '''
548 Creates or updates a Traffic Manager profile.
549
550 :return: deserialized Traffic Manager profile state dictionary
551 '''
552 self.log("Creating / Updating the Traffic Manager profile {0}".format(self.name))
553
554 parameters = Profile(
555 tags=self.tags,
556 location=self.location,
557 profile_status=self.profile_status,
558 traffic_routing_method=self.traffic_routing_method,
559 dns_config=create_dns_config_instance(self.dns_config) if self.dns_config else None,
560 monitor_config=create_monitor_config_instance(self.monitor_config) if self.monitor_config else None,
561 endpoints=create_endpoints(self.endpoints)
562 )
563 try:
564 response = self.traffic_manager_management_client.profiles.create_or_update(self.resource_group, self.name, parameters)
565 return traffic_manager_profile_to_dict(response)
566 except Exception as exc:
567 self.log('Error attempting to create the Traffic Manager.')
568 self.fail("Error creating the Traffic Manager: {0}".format(exc.message))
569
570 def check_update(self, response):
571 if response['location'] != self.location:
572 self.log("Location Diff - Origin {0} / Update {1}".format(response['location'], self.location))
573 return True
574
575 if response['profile_status'] != self.profile_status:
576 self.log("Profile Status Diff - Origin {0} / Update {1}".format(response['profile_status'], self.profile_status))
577 return True
578
579 if response['traffic_routing_method'] != self.traffic_routing_method:
580 self.log("Traffic Routing Method Diff - Origin {0} / Update {1}".format(response['traffic_routing_method'], self.traffic_routing_method))
581 return True
582
583 if (response['dns_config']['relative_name'] != self.dns_config['relative_name'] or response['dns_config']['ttl'] != self.dns_config['ttl']):
584 self.log("DNS Config Diff - Origin {0} / Update {1}".format(response['dns_config'], self.dns_config))
585 return True
586
587 for k, v in self.monitor_config.items():
588 if v:
589 if str(v).lower() != str(response['monitor_config'][k]).lower():
590 self.log("Monitor Config Diff - Origin {0} / Update {1}".format(response['monitor_config'], self.monitor_config))
591 return True
592
593 if len(response['endpoints']) != len(self.endpoints):
594 self.log("Endpoints Diff - Origin {0} / Update {1}".format(response['endpoints'], self.endpoints))
595 return True
596 else:
597 for e1, e2 in zip(sorted(self.endpoints, key=lambda k: k['name']), sorted(response['endpoints'], key=lambda k: k['name'])):
598 for k, v in e1.items():
599 if v:
600 if str(v).lower() != str(e2[k]).lower():
601 self.log("Endpoints Diff - Origin {0} / Update {1}".format(response['endpoints'], self.endpoints))
602 return True
603 return False
604
605
606 def main():
607 """Main execution"""
608 AzureRMTrafficManager()
609
610
611 if __name__ == '__main__':
612 main()