Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2019 Yuwei Zhou, <[email protected]>
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = '''
13 ---
14 module: azure_rm_iothub_info
15
16 version_added: "0.1.2"
17
18 short_description: Get IoT Hub facts
19
20 description:
21 - Get facts for a specific IoT Hub or all IoT Hubs.
22
23 options:
24 name:
25 description:
26 - Limit results to a specific resource group.
27 type: str
28 resource_group:
29 description:
30 - The resource group to search for the desired IoT Hub.
31 type: str
32 tags:
33 description:
34 - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'.
35 type: list
36 elements: str
37 show_stats:
38 description:
39 - Show the statistics for IoT Hub.
40 - Note this will have network overhead for each IoT Hub.
41 type: bool
42 show_quota_metrics:
43 description:
44 - Get the quota metrics for an IoT hub.
45 - Note this will have network overhead for each IoT Hub.
46 type: bool
47 show_endpoint_health:
48 description:
49 - Get the health for routing endpoints.
50 - Note this will have network overhead for each IoT Hub.
51 type: bool
52 test_route_message:
53 description:
54 - Test routes message. It will be used to test all routes.
55 type: str
56 list_consumer_groups:
57 description:
58 - List the consumer group of the built-in event hub.
59 type: bool
60 list_keys:
61 description:
62 - List the keys of IoT Hub.
63 - Note this will have network overhead for each IoT Hub.
64 type: bool
65 extends_documentation_fragment:
66 - azure.azcollection.azure
67
68 author:
69 - Yuwei Zhou (@yuwzho)
70 '''
71
72 EXAMPLES = '''
73 - name: Get facts for one IoT Hub
74 azure_rm_iothub_info:
75 name: Testing
76 resource_group: myResourceGroup
77
78 - name: Get facts for all IoT Hubs
79 azure_rm_iothub_info:
80
81 - name: Get facts for all IoT Hubs in a specific resource group
82 azure_rm_iothub_info:
83 resource_group: myResourceGroup
84
85 - name: Get facts by tags
86 azure_rm_iothub_info:
87 tags:
88 - testing
89 '''
90
91 RETURN = '''
92 azure_iothubs:
93 description:
94 - List of IoT Hub dicts.
95 returned: always
96 type: complex
97 contains:
98 id:
99 description:
100 - Resource ID of the IoT hub.
101 type: str
102 returned: always
103 sample: "/subscriptions/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/resourceGroups/myResourceGroup/providers/Microsoft.Devices/IotHubs/Testing"
104 name:
105 description:
106 - Name of the IoT hub.
107 type: str
108 returned: always
109 sample: Testing
110 resource_group:
111 description:
112 - Resource group of the IoT hub.
113 type: str
114 returned: always
115 sample: myResourceGroup.
116 location:
117 description:
118 - Location of the IoT hub.
119 type: str
120 returned: always
121 sample: eastus
122 unit:
123 description:
124 - Units in the IoT Hub.
125 type: int
126 returned: always
127 sample: 1
128 sku:
129 description:
130 - Pricing tier for Azure IoT Hub.
131 type: str
132 returned: always
133 sample: f1
134 identity:
135 description:
136 - Identity for the Server.
137 type: complex
138 returned: when available
139 contains:
140 type:
141 description:
142 - Type of the managed identity
143 returned: always
144 sample: UserAssigned
145 type: str
146 user_assigned_identities:
147 description:
148 - User Assigned Managed Identities and its options
149 returned: always
150 type: complex
151 contains:
152 id:
153 description:
154 - Dict of the user assigned identities IDs associated to the Resource
155 returned: always
156 type: dict
157 elements: dict
158 cloud_to_device:
159 description:
160 - Cloud to device message properties.
161 type: complex
162 returned: always
163 contains:
164 max_delivery_count:
165 description:
166 - The number of times the IoT hub attempts to deliver a message on the feedback queue.
167 - "See U(https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages)."
168 type: int
169 returned: always
170 sample: 10
171 ttl_as_iso8601:
172 description:
173 - The period of time for which a message is available to consume before it is expired by the IoT hub.
174 - "See U(https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages)."
175 type: str
176 returned: always
177 sample: "1:00:00"
178 enable_file_upload_notifications:
179 description:
180 - Whether file upload notifications are enabled.
181 type: str
182 returned: always
183 sample: True
184 event_endpoints:
185 description:
186 - Built-in endpoint where to deliver device message.
187 type: complex
188 returned: always
189 contains:
190 endpoint:
191 description:
192 - The Event Hub-compatible endpoint.
193 type: str
194 returned: always
195 sample: "sb://iothub-ns-testing-1478811-9bbc4a15f0.servicebus.windows.net/"
196 partition_count:
197 description:
198 - The number of partitions for receiving device-to-cloud messages in the Event Hub-compatible endpoint.
199 - "See U(https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#device-to-cloud-messages)."
200 type: int
201 returned: always
202 sample: 2
203 retention_time_in_days:
204 description:
205 - The retention time for device-to-cloud messages in days.
206 - "See U(https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#device-to-cloud-messages)."
207 type: int
208 returned: always
209 sample: 1
210 partition_ids:
211 description:
212 - List of the partition id for the event endpoint.
213 type: list
214 returned: always
215 sample: ["0", "1"]
216 host_name:
217 description:
218 - Host of the IoT hub.
219 type: str
220 returned: always
221 sample: "testing.azure-devices.net"
222 ip_filters:
223 description:
224 - Configure rules for rejecting or accepting traffic from specific IPv4 addresses.
225 type: complex
226 returned: always
227 contains:
228 name:
229 description:
230 - Name of the filter.
231 type: str
232 returned: always
233 sample: filter
234 ip_mask:
235 description:
236 - A string that contains the IP address range in CIDR notation for the rule.
237 type: str
238 returned: always
239 sample: 40.54.7.3
240 action:
241 description:
242 - The desired action for requests captured by this rule.
243 type: str
244 returned: always
245 sample: Reject
246 routing_endpoints:
247 description:
248 - Custom endpoints.
249 type: complex
250 returned: always
251 contains:
252 event_hubs:
253 description:
254 - List of custom endpoints of event hubs.
255 type: complex
256 returned: always
257 contains:
258 name:
259 description:
260 - Name of the custom endpoint.
261 type: str
262 returned: always
263 sample: foo
264 resource_group:
265 description:
266 - Resource group of the endpoint.
267 type: str
268 returned: always
269 sample: bar
270 subscription:
271 description:
272 - Subscription ID of the endpoint.
273 type: str
274 returned: always
275 sample: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
276 connection_string:
277 description:
278 - Connection string of the custom endpoint.
279 type: str
280 returned: always
281 sample: "Endpoint=sb://quux.servicebus.windows.net:5671/;SharedAccessKeyName=qux;SharedAccessKey=****;EntityPath=foo"
282 service_bus_queues:
283 description:
284 - List of custom endpoints of service bus queue.
285 type: complex
286 returned: always
287 contains:
288 name:
289 description:
290 - Name of the custom endpoint.
291 type: str
292 returned: always
293 sample: foo
294 resource_group:
295 description:
296 - Resource group of the endpoint.
297 type: str
298 returned: always
299 sample: bar
300 subscription:
301 description:
302 - Subscription ID of the endpoint.
303 type: str
304 returned: always
305 sample: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
306 connection_string:
307 description:
308 - Connection string of the custom endpoint.
309 type: str
310 returned: always
311 sample: "Endpoint=sb://quux.servicebus.windows.net:5671/;SharedAccessKeyName=qux;SharedAccessKey=****;EntityPath=foo"
312 service_bus_topics:
313 description:
314 - List of custom endpoints of service bus topic.
315 type: complex
316 returned: always
317 contains:
318 name:
319 description:
320 - Name of the custom endpoint.
321 type: str
322 returned: always
323 sample: foo
324 resource_group:
325 description:
326 - Resource group of the endpoint.
327 type: str
328 returned: always
329 sample: bar
330 subscription:
331 description:
332 - Subscription ID of the endpoint.
333 type: str
334 returned: always
335 sample: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
336 connection_string:
337 description:
338 - Connection string of the custom endpoint.
339 type: str
340 returned: always
341 sample: "Endpoint=sb://quux.servicebus.windows.net:5671/;SharedAccessKeyName=qux;SharedAccessKey=****;EntityPath=foo"
342 storage_containers:
343 description:
344 - List of custom endpoints of storage.
345 type: complex
346 returned: always
347 contains:
348 name:
349 description:
350 - Name of the custom endpoint.
351 type: str
352 returned: always
353 sample: foo
354 resource_group:
355 description:
356 - Resource group of the endpoint.
357 type: str
358 returned: always
359 sample: bar
360 subscription:
361 description:
362 - Subscription ID of the endpoint.
363 type: str
364 returned: always
365 sample: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
366 connection_string:
367 description:
368 - Connection string of the custom endpoint.
369 type: str
370 returned: always
371 sample: "Endpoint=sb://quux.servicebus.windows.net:5671/;SharedAccessKeyName=qux;SharedAccessKey=****;EntityPath=foo"
372 routes:
373 description:
374 - Route device-to-cloud messages to service-facing endpoints.
375 type: complex
376 returned: always
377 contains:
378 name:
379 description:
380 - Name of the route.
381 type: str
382 returned: always
383 sample: route1
384 source:
385 description:
386 - The origin of the data stream to be acted upon.
387 type: str
388 returned: always
389 sample: device_messages
390 enabled:
391 description:
392 - Whether to enable the route.
393 type: bool
394 returned: always
395 sample: true
396 endpoint_name:
397 description:
398 - The name of the endpoint in I(routing_endpoints) where IoT Hub sends messages that match the query.
399 type: str
400 returned: always
401 sample: foo
402 condition:
403 description:
404 - "The query expression for the routing query that is run against the message application properties,
405 system properties, message body, device twin tags, and device twin properties to determine if it is a match for the endpoint."
406 - "For more information about constructing a query,
407 see U(https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-routing-query-syntax)"
408 type: bool
409 returned: always
410 sample: "true"
411 tags:
412 description:
413 - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'.
414 type: dict
415 returned: always
416 sample: { 'key1': 'value1' }
417 '''
418
419 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
420 from ansible.module_utils.common.dict_transformations import _camel_to_snake
421
422 try:
423 from azure.mgmt.core.tools import parse_resource_id
424 except Exception:
425 # handled in azure_rm_common
426 pass
427
428
429 class AzureRMIoTHubFacts(AzureRMModuleBase):
430 """Utility class to get IoT Hub facts"""
431
432 def __init__(self):
433
434 self.module_args = dict(
435 name=dict(type='str'),
436 resource_group=dict(type='str'),
437 tags=dict(type='list', elements='str'),
438 show_stats=dict(type='bool'),
439 show_quota_metrics=dict(type='bool'),
440 show_endpoint_health=dict(type='bool'),
441 list_keys=dict(type='bool'),
442 test_route_message=dict(type='str'),
443 list_consumer_groups=dict(type='bool')
444 )
445
446 self.results = dict(
447 changed=False,
448 azure_iothubs=[]
449 )
450
451 self.name = None
452 self.resource_group = None
453 self.tags = None
454 self.show_stats = None
455 self.show_quota_metrics = None
456 self.show_endpoint_health = None
457 self.list_keys = None
458 self.test_route_message = None
459 self.list_consumer_groups = None
460
461 super(AzureRMIoTHubFacts, self).__init__(
462 derived_arg_spec=self.module_args,
463 supports_check_mode=True,
464 supports_tags=False,
465 facts_module=True
466 )
467
468 def exec_module(self, **kwargs):
469
470 for key in self.module_args:
471 setattr(self, key, kwargs[key])
472
473 response = []
474 if self.name:
475 response = self.get_item()
476 elif self.resource_group:
477 response = self.list_by_resource_group()
478 else:
479 response = self.list_all()
480 self.results['iothubs'] = [self.to_dict(x) for x in response if self.has_tags(x.tags, self.tags)]
481 return self.results
482
483 def get_item(self):
484 """Get a single IoT Hub"""
485
486 self.log('Get properties for {0}'.format(self.name))
487
488 item = None
489
490 try:
491 item = self.IoThub_client.iot_hub_resource.get(self.resource_group, self.name)
492 return [item]
493 except Exception as exc:
494 self.fail('Error when getting IoT Hub {0}: {1}'.format(self.name, exc.message or str(exc)))
495
496 def list_all(self):
497 """Get all IoT Hubs"""
498
499 self.log('List all IoT Hubs')
500
501 try:
502 return self.IoThub_client.iot_hub_resource.list_by_subscription()
503 except Exception as exc:
504 self.fail('Failed to list all IoT Hubs - {0}'.format(str(exc)))
505
506 def list_by_resource_group(self):
507 try:
508 return self.IoThub_client.iot_hub_resource.list_by_resource_group(self.resource_group)
509 except Exception as exc:
510 self.fail('Failed to list IoT Hub in resource group {0} - {1}'.format(self.resource_group, exc.message or str(exc)))
511
512 def show_hub_stats(self, resource_group, name):
513 try:
514 return self.IoThub_client.iot_hub_resource.get_stats(resource_group, name).as_dict()
515 except Exception as exc:
516 self.fail('Failed to getting statistics for IoT Hub {0}/{1}: {2}'.format(resource_group, name, str(exc)))
517
518 def show_hub_quota_metrics(self, resource_group, name):
519 result = []
520 try:
521 resp = self.IoThub_client.iot_hub_resource.get_quota_metrics(resource_group, name)
522 while True:
523 result.append(resp.next().as_dict())
524 except StopIteration:
525 pass
526 except Exception as exc:
527 self.fail('Failed to getting quota metrics for IoT Hub {0}/{1}: {2}'.format(resource_group, name, str(exc)))
528 return result
529
530 def show_hub_endpoint_health(self, resource_group, name):
531 result = []
532 try:
533 resp = self.IoThub_client.iot_hub_resource.get_endpoint_health(resource_group, name)
534 while True:
535 result.append(resp.next().as_dict())
536 except StopIteration:
537 pass
538 except Exception as exc:
539 self.fail('Failed to getting health for IoT Hub {0}/{1} routing endpoint: {2}'.format(resource_group, name, str(exc)))
540 return result
541
542 def test_all_routes(self, resource_group, name):
543 try:
544 return self.IoThub_client.iot_hub_resource.test_all_routes(self.test_route_message, resource_group, name).routes.as_dict()
545 except Exception as exc:
546 self.fail('Failed to getting statistics for IoT Hub {0}/{1}: {2}'.format(resource_group, name, str(exc)))
547
548 def list_hub_keys(self, resource_group, name):
549 result = []
550 try:
551 resp = self.IoThub_client.iot_hub_resource.list_keys(resource_group, name)
552 while True:
553 result.append(resp.next().as_dict())
554 except StopIteration:
555 pass
556 except Exception as exc:
557 self.fail('Failed to getting health for IoT Hub {0}/{1} routing endpoint: {2}'.format(resource_group, name, str(exc)))
558 return result
559
560 def list_event_hub_consumer_groups(self, resource_group, name, event_hub_endpoint='events'):
561 result = []
562 try:
563 resp = self.IoThub_client.iot_hub_resource.list_event_hub_consumer_groups(resource_group, name, event_hub_endpoint)
564 while True:
565 cg = resp.next()
566 result.append(dict(
567 id=cg.id,
568 name=cg.name
569 ))
570 except StopIteration:
571 pass
572 except Exception as exc:
573 self.fail('Failed to listing consumer group for IoT Hub {0}/{1} routing endpoint: {2}'.format(resource_group, name, str(exc)))
574 return result
575
576 def route_to_dict(self, route):
577 return dict(
578 name=route.name,
579 source=_camel_to_snake(route.source),
580 endpoint_name=route.endpoint_names[0],
581 enabled=route.is_enabled,
582 condition=route.condition
583 )
584
585 def instance_dict_to_dict(self, instance_dict):
586 result = dict()
587 for key in instance_dict.keys():
588 result[key] = instance_dict[key].as_dict()
589 return result
590
591 def to_dict(self, hub):
592 result = dict()
593 properties = hub.properties
594 result['id'] = hub.id
595 result['name'] = hub.name
596 result['resource_group'] = parse_resource_id(hub.id).get('resource_group')
597 result['location'] = hub.location
598 result['tags'] = hub.tags
599 result['unit'] = hub.sku.capacity
600 result['sku'] = hub.sku.name.lower()
601 result['identity'] = hub.identity.as_dict() if hub.identity else None
602 result['cloud_to_device'] = dict(
603 max_delivery_count=properties.cloud_to_device.feedback.max_delivery_count,
604 ttl_as_iso8601=str(properties.cloud_to_device.feedback.ttl_as_iso8601)
605 )
606 result['enable_file_upload_notifications'] = properties.enable_file_upload_notifications
607 result['event_hub_endpoints'] = self.instance_dict_to_dict(properties.event_hub_endpoints)
608 result['host_name'] = properties.host_name
609 result['ip_filters'] = [x.as_dict() for x in properties.ip_filter_rules]
610 result['routing_endpoints'] = properties.routing.endpoints.as_dict()
611 result['routes'] = [self.route_to_dict(x) for x in properties.routing.routes]
612 result['fallback_route'] = self.route_to_dict(properties.routing.fallback_route)
613 result['status'] = properties.state
614 result['storage_endpoints'] = self.instance_dict_to_dict(properties.storage_endpoints)
615
616 # network overhead part
617 if self.show_stats:
618 result['statistics'] = self.show_hub_stats(result['resource_group'], hub.name)
619 if self.show_quota_metrics:
620 result['quota_metrics'] = self.show_hub_quota_metrics(result['resource_group'], hub.name)
621 if self.show_endpoint_health:
622 result['endpoint_health'] = self.show_hub_endpoint_health(result['resource_group'], hub.name)
623 if self.list_keys:
624 result['keys'] = self.list_hub_keys(result['resource_group'], hub.name)
625 if self.test_route_message:
626 result['test_route_result'] = self.test_all_routes(result['resource_group'], hub.name)
627 if self.list_consumer_groups:
628 result['consumer_groups'] = self.list_event_hub_consumer_groups(result['resource_group'], hub.name)
629 return result
630
631
632 def main():
633 """Main module execution code path"""
634
635 AzureRMIoTHubFacts()
636
637
638 if __name__ == '__main__':
639 main()