Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_iotdevice_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 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10
11 DOCUMENTATION = '''
12 ---
13 module: azure_rm_iotdevice_info
14 version_added: "0.1.2"
15 short_description: Facts of Azure IoT hub device
16 description:
17 - Query, get Azure IoT hub device.
18 options:
19 hub:
20 description:
21 - Name of IoT Hub.
22 type: str
23 required: true
24 hub_policy_name:
25 description:
26 - Policy name of the IoT Hub which will be used to query from IoT hub.
27 - This policy should have at least 'Registry Read' access.
28 type: str
29 required: true
30 hub_policy_key:
31 description:
32 - Key of the I(hub_policy_name).
33 type: str
34 required: true
35 name:
36 description:
37 - Name of the IoT hub device identity.
38 type: str
39 aliases:
40 - device_id
41 module_id:
42 description:
43 - Name of the IoT hub device module.
44 - Must use with I(device_id) defined.
45 type: str
46 query:
47 description:
48 - Query an IoT hub to retrieve information regarding device twins using a SQL-like language.
49 - "See U(https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-query-language)."
50 type: str
51 top:
52 description:
53 - Used when I(name) not defined.
54 - List the top n devices in the query.
55 type: int
56 extends_documentation_fragment:
57 - azure.azcollection.azure
58 - azure.azcollection.azure_tags
59
60 author:
61 - Yuwei Zhou (@yuwzho)
62 '''
63
64 EXAMPLES = '''
65 - name: Get the details of a device
66 azure_rm_iotdevice_info:
67 name: Testing
68 hub: MyIoTHub
69 hub_policy_name: registryRead
70 hub_policy_key: XXXXXXXXXXXXXXXXXXXX
71
72 - name: Query devices
73 azure_rm_iotdevice_info:
74 hub: "hub{{ rpfx }}"
75 query: "SELECT * FROM devices"
76 hub_policy_name: "{{ registry_write_name }}"
77 hub_policy_key: "{{ registry_write_key }}"
78
79 - name: Query all device modules in an IoT Hub
80 azure_rm_iotdevice_info:
81 hub: MyIoTHub
82 hub_policy_name: registryRead
83 hub_policy_key: XXXXXXXXXXXXXXXXXXXX
84
85 - name: List all devices in an IoT Hub
86 azure_rm_iotdevice_info:
87 hub: MyIoTHub
88 hub_policy_name: registryRead
89 hub_policy_key: XXXXXXXXXXXXXXXXXXXX
90 '''
91
92 RETURN = '''
93 iot_devices:
94 description:
95 - IoT Hub device.
96 returned: always
97 type: dict
98 sample: {
99 "authentication": {
100 "symmetricKey": {
101 "primaryKey": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
102 "secondaryKey": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
103 },
104 "type": "sas",
105 "x509Thumbprint": {
106 "primaryThumbprint": null,
107 "secondaryThumbprint": null
108 }
109 },
110 "capabilities": {
111 "iotEdge": false
112 },
113 "changed": true,
114 "cloudToDeviceMessageCount": 0,
115 "connectionState": "Disconnected",
116 "connectionStateUpdatedTime": "0001-01-01T00:00:00",
117 "deviceId": "Testing",
118 "etag": "NzA2NjU2ODc=",
119 "failed": false,
120 "generationId": "636903014505613307",
121 "lastActivityTime": "0001-01-01T00:00:00",
122 "modules": [
123 {
124 "authentication": {
125 "symmetricKey": {
126 "primaryKey": "XXXXXXXXXXXXXXXXXXX",
127 "secondaryKey": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
128 },
129 "type": "sas",
130 "x509Thumbprint": {
131 "primaryThumbprint": null,
132 "secondaryThumbprint": null
133 }
134 },
135 "cloudToDeviceMessageCount": 0,
136 "connectionState": "Disconnected",
137 "connectionStateUpdatedTime": "0001-01-01T00:00:00",
138 "deviceId": "testdevice",
139 "etag": "MjgxOTE5ODE4",
140 "generationId": "636903840872788074",
141 "lastActivityTime": "0001-01-01T00:00:00",
142 "managedBy": null,
143 "moduleId": "test"
144 }
145 ],
146 "properties": {
147 "desired": {
148 "$metadata": {
149 "$lastUpdated": "2019-04-10T05:00:46.2702079Z",
150 "$lastUpdatedVersion": 8,
151 "period": {
152 "$lastUpdated": "2019-04-10T05:00:46.2702079Z",
153 "$lastUpdatedVersion": 8
154 }
155 },
156 "$version": 1,
157 "period": 100
158 },
159 "reported": {
160 "$metadata": {
161 "$lastUpdated": "2019-04-08T06:24:10.5613307Z"
162 },
163 "$version": 1
164 }
165 },
166 "status": "enabled",
167 "statusReason": null,
168 "statusUpdatedTime": "0001-01-01T00:00:00",
169 "tags": {
170 "location": {
171 "country": "us",
172 "city": "Redmond"
173 },
174 "sensor": "humidity"
175 }
176 }
177 ''' # NOQA
178
179 import traceback
180
181 from ansible.module_utils.basic import missing_required_lib
182 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
183
184 try:
185 from azure.iot.hub import IoTHubRegistryManager
186 except ImportError:
187 AZURE_IOT_HUB_IMPORT_ERROR = traceback.format_exc()
188 else:
189 AZURE_IOT_HUB_IMPORT_ERROR = None
190
191
192 class AzureRMIoTDeviceFacts(AzureRMModuleBase):
193
194 def __init__(self):
195
196 self.module_arg_spec = dict(
197 name=dict(type='str', aliases=['device_id']),
198 module_id=dict(type='str'),
199 query=dict(type='str'),
200 hub=dict(type='str', required=True),
201 hub_policy_name=dict(type='str', required=True),
202 hub_policy_key=dict(type='str', no_log=True, required=True),
203 top=dict(type='int')
204 )
205
206 self.results = dict(
207 changed=False,
208 iot_devices=[]
209 )
210
211 self.name = None
212 self.module_id = None
213 self.hub = None
214 self.hub_policy_name = None
215 self.hub_policy_key = None
216 self.top = None
217 self.query = None
218
219 self.mgmt_client = None
220 self._base_url = None
221
222 super(AzureRMIoTDeviceFacts, self).__init__(self.module_arg_spec, supports_check_mode=True)
223
224 if AZURE_IOT_HUB_IMPORT_ERROR:
225 self.fail(msg=missing_required_lib('azure-iot-hub', reason=("This module requires the Azure IoT Hub data-plane SDK (azure-iot-hub). "
226 "Installation may fail on some platforms due to uamqp wheel build issues.")),
227 exception=AZURE_IOT_HUB_IMPORT_ERROR)
228
229 def exec_module(self, **kwargs):
230
231 for key in self.module_arg_spec.keys():
232 setattr(self, key, kwargs[key])
233
234 self._base_url = '{0}.azure-devices.net'.format(self.hub)
235
236 connect_str = "HostName={0};SharedAccessKeyName={1};SharedAccessKey={2}".format(self._base_url, self.hub_policy_name, self.hub_policy_key)
237 self.mgmt_client = IoTHubRegistryManager.from_connection_string(connect_str)
238
239 response = []
240 if self.module_id:
241 response = [self.get_device_module()]
242 elif self.name:
243 response = [self.get_device()]
244 elif self.query is not None:
245 response = self.hub_query()
246 else:
247 response = self.list_devices()
248
249 self.results['iot_devices'] = response
250 return self.results
251
252 def get_device(self):
253 try:
254 response = self.mgmt_client.get_device(self.name)
255
256 response = self.format_item(response)
257 return response
258 except Exception as exc:
259 self.fail('Error when getting IoT Hub device {0}: {1}'.format(self.name, exc))
260
261 def get_device_module(self):
262 try:
263 response = self.mgmt_client.get_module(self.name, self.module_id)
264 return self.format_module(response)
265 except Exception as exc:
266 self.fail('Error when getting IoT Hub device {0}: {1}'.format(self.name, exc))
267
268 def list_device_modules(self):
269 try:
270 response = self.mgmt_client.get_modules(self.name)
271
272 return [self.format_module(item) for item in response]
273 except Exception as exc:
274 self.fail('Error when getting IoT Hub device {0}: {1}'.format(self.name, exc))
275
276 def list_devices(self):
277 try:
278 response = None
279 response = self.mgmt_client.get_devices(max_number_of_devices=1000)
280
281 response = [self.format_item(item) for item in response]
282 if self.top is not None:
283 return response[self.top - 1]
284 else:
285 return response
286 except Exception as exc:
287 if hasattr(exc, 'message'):
288 pass
289 else:
290 self.fail('Error when listing IoT Hub devices in {0}: {1}'.format(self.hub, exc))
291
292 def hub_query(self):
293 try:
294 response = None
295 response = self.mgmt_client.query_iot_hub(dict(query=self.query))
296
297 return [self.format_twin(item) for item in response.items]
298
299 except Exception as exc:
300 if hasattr(exc, 'message'):
301 pass
302 else:
303 self.fail('Error when listing IoT Hub devices in {0}: {1}'.format(self.hub, exc))
304
305 def format_module(self, item):
306 if not item:
307 return None
308 format_item = dict(
309 authentication=dict(),
310 cloudToDeviceMessageCount=item.cloud_to_device_message_count,
311 connectionState=item.connection_state,
312 connectionStateUpdatedTime=item.connection_state_updated_time,
313 deviceId=item.device_id,
314 etag=item.etag,
315 generationId=item.generation_id,
316 lastActivityTime=item.last_activity_time,
317 managedBy=item.managed_by,
318 moduleId=item.module_id
319 )
320 if item.authentication:
321 format_item['authentication']['symmetricKey'] = dict()
322 format_item['authentication']['symmetricKey']['primaryKey'] = item.authentication.symmetric_key.primary_key
323 format_item['authentication']['symmetricKey']['secondaryKey'] = item.authentication.symmetric_key.secondary_key
324
325 format_item['authentication']['type'] = item.authentication.type
326 format_item['authentication']["x509Thumbprint"] = dict()
327 format_item['authentication']["x509Thumbprint"]["primaryThumbprint"] = item.authentication.x509_thumbprint.primary_thumbprint
328 format_item['authentication']["x509Thumbprint"]['secondaryThumbprint'] = item.authentication.x509_thumbprint.secondary_thumbprint
329
330 return format_item
331
332 def format_item(self, item):
333 if not item:
334 return None
335 format_item = dict(
336 authentication=dict(),
337 capabilities=dict(),
338 cloudToDeviceMessageCount=item.cloud_to_device_message_count,
339 connectionState=item.connection_state,
340 connectionStateUpdatedTime=item.connection_state_updated_time,
341 deviceId=item.device_id,
342 etag=item.etag,
343 generationId=item.generation_id,
344 lastActivityTime=item.last_activity_time,
345 status=item.status,
346 statusReason=item.status_reason
347 )
348 if hasattr(item, 'status_updated_time'):
349 format_item['statusUpdatedTime'] = item.status_updated_time
350 if hasattr(item, 'modules'):
351 format_item['modules'] = item.modules
352 if item.authentication:
353 format_item['authentication']['symmetricKey'] = dict()
354 format_item['authentication']['symmetricKey']['primaryKey'] = item.authentication.symmetric_key.primary_key
355 format_item['authentication']['symmetricKey']['secondaryKey'] = item.authentication.symmetric_key.secondary_key
356
357 format_item['authentication']['type'] = item.authentication.type
358 format_item['authentication']["x509Thumbprint"] = dict()
359 format_item['authentication']["x509Thumbprint"]["primaryThumbprint"] = item.authentication.x509_thumbprint.primary_thumbprint
360 format_item['authentication']["x509Thumbprint"]['secondaryThumbprint'] = item.authentication.x509_thumbprint.secondary_thumbprint
361 if item.capabilities:
362 format_item['capabilities']["iotEdge"] = item.capabilities.iot_edge
363
364 return format_item
365
366 def format_twin(self, item):
367 if not item:
368 return None
369 format_twin = dict(
370 device_id=item.device_id,
371 module_id=item.module_id,
372 tags=item.tags,
373 properties=dict(),
374 etag=item.etag,
375 version=item.version,
376 device_etag=item.device_etag,
377 status=item.status,
378 cloud_to_device_message_count=item.cloud_to_device_message_count,
379 authentication_type=item.authentication_type,
380 )
381 if item.properties is not None:
382 format_twin['properties']['desired'] = item.properties.desired
383 format_twin['properties']['reported'] = item.properties.reported
384
385 return format_twin
386
387
388 def main():
389 AzureRMIoTDeviceFacts()
390
391
392 if __name__ == '__main__':
393 main()