Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_iotdevice.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
14 version_added: "0.1.2"
15 short_description: Manage Azure IoT hub device
16 description:
17 - Create, delete an 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 'RegistryWrite, ServiceConnect, DeviceConnect' accesses. You may get 401 error when you lack any of these.
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 required: true
40 state:
41 description:
42 - State of the IoT hub. Use C(present) to create or update an IoT hub device and C(absent) to delete an IoT hub device.
43 type: str
44 default: present
45 choices:
46 - absent
47 - present
48 auth_method:
49 description:
50 - The authorization type an entity is to be created with.
51 type: str
52 choices:
53 - sas
54 - certificate_authority
55 - self_signed
56 default: sas
57 primary_key:
58 description:
59 - Explicit self-signed certificate thumbprint to use for primary key.
60 - Explicit Shared Private Key to use for primary key.
61 type: str
62 aliases:
63 - primary_thumbprint
64 secondary_key:
65 description:
66 - Explicit self-signed certificate thumbprint to use for secondary key.
67 - Explicit Shared Private Key to use for secondary key.
68 type: str
69 aliases:
70 - secondary_thumbprint
71 status:
72 description:
73 - Set device status upon creation.
74 type: bool
75 edge_enabled:
76 description:
77 - Flag indicating edge enablement.
78 - Not supported in IoT Hub with Basic tier.
79 type: bool
80 twin_tags:
81 description:
82 - A section that the solution back end can read from and write to.
83 - Tags are not visible to device apps.
84 - "The tag can be nested dictionary, '.', '$', '#', ' ' is not allowed in the key."
85 - List is not supported.
86 - Not supported in IoT Hub with Basic tier.
87 type: dict
88 desired:
89 description:
90 - Used along with reported properties to synchronize device configuration or conditions.
91 - "The tag can be nested dictionary, '.', '$', '#', ' ' is not allowed in the key."
92 - List is not supported.
93 - Not supported in IoT Hub with Basic tier.
94 type: dict
95 device_scope:
96 description:
97 - The scope of the device. Default value is C(None).
98 - The I(device_scpe) shoud start with 'ms-azure-iot-edge://'. Sample as C(ms-azure-iot-edge://{{ edge_device_name }}-{{ generation_id }}).
99 type: str
100 extends_documentation_fragment:
101 - azure.azcollection.azure
102 - azure.azcollection.azure_tags
103
104 author:
105 - Yuwei Zhou (@yuwzho)
106
107 '''
108
109 EXAMPLES = '''
110 - name: Create simplest Azure IoT Hub device
111 azure_rm_iotdevice:
112 hub: myHub
113 name: Testing
114 hub_policy_name: iothubowner
115 hub_policy_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
116 primary_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
117 secondary_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
118
119 - name: Create Azure IoT Edge device
120 azure_rm_iotdevice:
121 hub: myHub
122 name: Testing
123 hub_policy_name: iothubowner
124 hub_policy_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
125 primary_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
126 secondary_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
127 edge_enabled: true
128
129 - name: Create Azure IoT Hub device with device twin properties and tag
130 azure_rm_iotdevice:
131 hub: myHub
132 name: Testing
133 hub_policy_name: iothubowner
134 hub_policy_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
135 primary_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
136 secondary_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
137 twin_tags:
138 location:
139 country: US
140 city: Redmond
141 sensor: humidity
142 desired:
143 period: 100
144 '''
145
146 RETURN = '''
147 device:
148 description:
149 - IoT Hub device.
150 returned: always
151 type: dict
152 sample: {
153 "authentication": {
154 "symmetricKey": {
155 "primaryKey": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
156 "secondaryKey": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
157 },
158 "type": "sas",
159 "x509Thumbprint": {
160 "primaryThumbprint": null,
161 "secondaryThumbprint": null
162 }
163 },
164 "capabilities": {
165 "iotEdge": false
166 },
167 "changed": true,
168 "cloudToDeviceMessageCount": 0,
169 "connectionState": "Disconnected",
170 "connectionStateUpdatedTime": "0001-01-01T00:00:00",
171 "deviceId": "Testing",
172 "etag": "NzA2NjU2ODc=",
173 "failed": false,
174 "generationId": "636903014505613307",
175 "lastActivityTime": "0001-01-01T00:00:00",
176 "modules": [
177 {
178 "authentication": {
179 "symmetricKey": {
180 "primaryKey": "XXXXXXXXXXXXXXXXXXX",
181 "secondaryKey": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
182 },
183 "type": "sas",
184 "x509Thumbprint": {
185 "primaryThumbprint": null,
186 "secondaryThumbprint": null
187 }
188 },
189 "cloudToDeviceMessageCount": 0,
190 "connectionState": "Disconnected",
191 "connectionStateUpdatedTime": "0001-01-01T00:00:00",
192 "deviceId": "testdevice",
193 "etag": "MjgxOTE5ODE4",
194 "generationId": "636903840872788074",
195 "lastActivityTime": "0001-01-01T00:00:00",
196 "managedBy": null,
197 "moduleId": "test"
198 }
199 ],
200 "properties": {
201 "desired": {
202 "$metadata": {
203 "$lastUpdated": "2019-04-10T05:00:46.2702079Z",
204 "$lastUpdatedVersion": 8,
205 "period": {
206 "$lastUpdated": "2019-04-10T05:00:46.2702079Z",
207 "$lastUpdatedVersion": 8
208 }
209 },
210 "$version": 1,
211 "period": 100
212 },
213 "reported": {
214 "$metadata": {
215 "$lastUpdated": "2019-04-08T06:24:10.5613307Z"
216 },
217 "$version": 1
218 }
219 },
220 "status": "enabled",
221 "statusReason": null,
222 "statusUpdatedTime": "0001-01-01T00:00:00",
223 "tags": {
224 "location": {
225 "country": "us",
226 "city": "Redmond"
227 },
228 "sensor": "humidity"
229 }
230 }
231 ''' # NOQA
232
233 import re
234 import traceback
235
236 from ansible.module_utils.basic import missing_required_lib
237 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
238
239 try:
240 from azure.iot.hub import IoTHubRegistryManager
241 except ImportError:
242 AZURE_IOT_HUB_IMPORT_ERROR = traceback.format_exc()
243 else:
244 AZURE_IOT_HUB_IMPORT_ERROR = None
245
246
247 class AzureRMIoTDevice(AzureRMModuleBase):
248
249 def __init__(self):
250
251 self.module_arg_spec = dict(
252 name=dict(type='str', required=True),
253 hub_policy_name=dict(type='str', required=True),
254 hub_policy_key=dict(type='str', no_log=True, required=True),
255 hub=dict(type='str', required=True),
256 state=dict(type='str', default='present', choices=['present', 'absent']),
257 status=dict(type='bool'),
258 edge_enabled=dict(type='bool'),
259 twin_tags=dict(type='dict'),
260 desired=dict(type='dict'),
261 auth_method=dict(type='str', choices=['self_signed', 'sas', 'certificate_authority'], default='sas'),
262 primary_key=dict(type='str', no_log=True, aliases=['primary_thumbprint']),
263 secondary_key=dict(type='str', no_log=True, aliases=['secondary_thumbprint']),
264 device_scope=dict(type='str'),
265 )
266
267 self.results = dict(
268 changed=False,
269 id=None
270 )
271
272 self.name = None
273 self.hub = None
274 self.hub_policy_key = None
275 self.hub_policy_name = None
276 self.state = None
277 self.status = None
278 self.edge_enabled = None
279 self.twin_tags = None
280 self.desired = None
281 self.auth_method = None
282 self.primary_key = None
283 self.secondary_key = None
284 self.device_scope = None
285
286 self._base_url = None
287 self.mgmt_client = None
288 super(AzureRMIoTDevice, self).__init__(self.module_arg_spec, supports_check_mode=True)
289
290 if AZURE_IOT_HUB_IMPORT_ERROR:
291 self.fail(msg=missing_required_lib('azure-iot-hub', reason=("This module requires the Azure IoT Hub data-plane SDK (azure-iot-hub). "
292 "Installation may fail on some platforms due to uamqp wheel build issues.")),
293 exception=AZURE_IOT_HUB_IMPORT_ERROR)
294
295 def exec_module(self, **kwargs):
296
297 for key in self.module_arg_spec.keys():
298 setattr(self, key, kwargs[key])
299
300 self._base_url = '{0}.azure-devices.net'.format(self.hub)
301
302 connect_str = "HostName={0};SharedAccessKeyName={1};SharedAccessKey={2}".format(self._base_url, self.hub_policy_name, self.hub_policy_key)
303 self.mgmt_client = IoTHubRegistryManager.from_connection_string(connect_str)
304
305 changed = False
306 update_changed = False
307
308 device = self.get_device()
309
310 if self.status is not None and not self.status:
311 device['status'] = 'disabled'
312
313 if self.state == 'present':
314 if not device:
315 changed = True
316 else:
317 update_changed = True
318 if self.edge_enabled is not None and self.edge_enabled != device['capabilities']['iotEdge']:
319 changed = True
320 device['capabilities']['iotEdge'] = self.edge_enabled
321 if self.status is not None:
322 status = 'enabled' if self.status else 'disabled'
323 if status != device['status']:
324 changed = True
325 device['status'] = status
326 if self.device_scope is not None and self.device_scope != device['device_scope']:
327 changed = True
328 if not self.check_mode:
329 if changed and update_changed:
330 device = self.update_device(device)
331 elif changed:
332 device = self.create_device()
333
334 twin = self.get_twin()
335
336 if twin:
337 if not twin.get('tags'):
338 twin['tags'] = dict()
339 twin_change = False
340 if self.twin_tags and not self.is_equal(self.twin_tags, twin['tags']):
341 twin_change = True
342 if self.desired and not self.is_equal(self.desired, twin['properties']['desired']):
343 twin_change = True
344 if twin_change and not self.check_mode:
345 twin_dict = dict()
346 twin_dict['tags'] = self.twin_tags
347 twin_dict['properties'] = dict()
348 twin_dict['properties']['desired'] = self.desired
349
350 twin = self.update_twin(twin_dict)
351
352 changed = changed or twin_change
353 device['tags'] = twin.get('tags') or dict()
354 device['properties'] = twin.get('properties') or dict()
355 device['modules'] = self.list_device_modules()
356 elif self.twin_tags or self.desired:
357 self.fail("Device twin is not supported in IoT Hub with basic tier.")
358 else:
359 if not self.check_mode:
360 if device:
361 changed = True
362 self.delete_device(device['etag'])
363 else:
364 changed = True
365 self.results = device or dict()
366 self.results['changed'] = changed
367 return self.results
368
369 def is_equal(self, updated, original):
370 changed = False
371 if not isinstance(updated, dict):
372 self.fail('The Property or Tag should be a dict')
373 for key in updated.keys():
374 if re.search(r'[.|$|#|\s]', key):
375 self.fail("Property or Tag name has invalid characters: '.', '$', '#' or ' '. Got '{0}'".format(key))
376 original_value = original.get(key)
377 updated_value = updated[key]
378 if isinstance(updated_value, dict):
379 if not isinstance(original_value, dict):
380 changed = True
381 original[key] = updated_value
382 elif not self.is_equal(updated_value, original_value):
383 changed = True
384 elif original_value != updated_value:
385 changed = True
386 original[key] = updated_value
387 return not changed
388
389 def update_device(self, device):
390 response = None
391 try:
392 if self.auth_method == 'sas':
393 response = self.mgmt_client.update_device_with_sas(self.name, device['etag'],
394 self.primary_key, self.secondary_key, self.status, iot_edge=self.edge_enabled,
395 device_scope=self.device_scope)
396 elif self.auth_method == 'self_signed':
397 response = self.mgmt_client.update_device_with_certificate_authority(self.name, self.status, iot_edge=self.edge_enabled,
398 device_scope=self.device_scope)
399 elif self.auth_method == 'certificate_authority':
400 response = self.mgmt_client.update_device_with_x509(self.name, device['etag'], self.primary_key, self.secondary_key,
401 self.status, iot_edge=self.edge_enabled, device_scope=self.device_scope)
402
403 return self.format_item(response)
404 except Exception as exc:
405 self.fail('Error when creating or updating IoT Hub device {0}: {1}'.format(self.name, exc.message or str(exc)))
406
407 def create_device(self):
408 response = None
409 try:
410 if self.auth_method == 'sas':
411 response = self.mgmt_client.create_device_with_sas(self.name, self.primary_key, self.secondary_key,
412 self.status, iot_edge=self.edge_enabled, device_scope=self.device_scope)
413 elif self.auth_method == 'self_signed':
414 response = self.mgmt_client.create_device_with_certificate_authority(self.name, self.status,
415 iot_edge=self.edge_enabled, device_scope=self.device_scope)
416 elif self.auth_method == 'certificate_authority':
417 response = self.mgmt_client.create_device_with_x509(self.name,
418 self.primary_key, self.secondary_key, self.status,
419 iot_edge=self.edge_enabled, device_scope=self.device_scope)
420
421 return self.format_item(response)
422 except Exception as exc:
423 self.fail('Error when creating or updating IoT Hub device {0}: {1}'.format(self.name, exc.message or str(exc)))
424
425 def delete_device(self, etag):
426 try:
427 response = self.mgmt_client.delete_device(self.name, etag=etag)
428 return response
429
430 except Exception as exc:
431 self.fail('Error when deleting IoT Hub device {0}: {1}'.format(self.name, exc.message or str(exc)))
432
433 def get_device(self):
434 try:
435 response = self.mgmt_client.get_device(self.name)
436
437 response = self.format_item(response)
438 return response
439 except Exception as exc:
440 self.log('Error when getting IoT Hub device {0}: {1}'.format(self.name, exc))
441
442 def get_twin(self):
443 try:
444 response = self.mgmt_client.get_twin(self.name)
445 return self.format_twin(response)
446 except Exception as exc:
447 self.fail('Error when getting IoT Hub device {0} twin: {1}'.format(self.name, exc.message or str(exc)))
448
449 def update_twin(self, twin):
450 try:
451 response = self.mgmt_client.update_twin(self.name, twin)
452
453 return self.format_twin(response)
454 except Exception as exc:
455 self.fail('Error when creating or updating IoT Hub device twin {0}: {1}'.format(self.name, exc.message or str(exc)))
456
457 def list_device_modules(self):
458 try:
459 response = None
460 response = self.mgmt_client.get_modules(self.name)
461
462 response = [self.format_item(item) for item in response]
463 return response
464
465 except Exception as exc:
466 if hasattr(exc, 'message'):
467 pass
468 else:
469 self.fail('Error when listing IoT Hub devices in {0}: {1}'.format(self.hub, exc))
470
471 def format_twin(self, item):
472 if not item:
473 return None
474 format_twin = dict(
475 device_id=item.device_id,
476 module_id=item.module_id,
477 tags=item.tags,
478 properties=dict(),
479 etag=item.etag,
480 version=item.version,
481 device_etag=item.device_etag,
482 status=item.status,
483 cloud_to_device_message_count=item.cloud_to_device_message_count,
484 authentication_type=item.authentication_type,
485 )
486 if item.properties is not None:
487 format_twin['properties']['desired'] = item.properties.desired
488 format_twin['properties']['reported'] = item.properties.reported
489
490 return format_twin
491
492 def format_item(self, item):
493 if not item:
494 return None
495 format_item = dict(
496 authentication=dict(),
497 capabilities=dict(),
498 cloudToDeviceMessageCount=item.cloud_to_device_message_count,
499 connectionState=item.connection_state,
500 connectionStateUpdatedTime=item.connection_state_updated_time,
501 deviceId=item.device_id,
502 etag=item.etag,
503 generationId=item.generation_id,
504 lastActivityTime=item.last_activity_time,
505 device_scope=item.device_scope if hasattr(item, 'device_scope') else None
506 )
507 if hasattr(item, 'status_updated_time'):
508 format_item['statusUpdatedTime'] = item.status_updated_time
509 if hasattr(item, 'status_reason'):
510 format_item['status_reason'] = item.status_reason
511 if hasattr(item, 'status'):
512 format_item['status'] = item.status
513 if hasattr(item, 'modules'):
514 format_item['modules'] = item.modules
515 if item.authentication:
516 format_item['authentication']['symmetricKey'] = dict()
517 format_item['authentication']['symmetricKey']['primaryKey'] = item.authentication.symmetric_key.primary_key
518 format_item['authentication']['symmetricKey']['secondaryKey'] = item.authentication.symmetric_key.secondary_key
519
520 format_item['authentication']['type'] = item.authentication.type
521 format_item['authentication']["x509Thumbprint"] = dict()
522 format_item['authentication']["x509Thumbprint"]["primaryThumbprint"] = item.authentication.x509_thumbprint.primary_thumbprint
523 format_item['authentication']["x509Thumbprint"]['secondaryThumbprint'] = item.authentication.x509_thumbprint.secondary_thumbprint
524 format_item['capabilities'] = dict()
525 if hasattr(item, 'capabilities') and item.capabilities is not None:
526 format_item['capabilities']["iotEdge"] = item.capabilities.iot_edge
527
528 return format_item
529
530
531 def main():
532 AzureRMIoTDevice()
533
534
535 if __name__ == '__main__':
536 main()