| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
|
| 11 |
DOCUMENTATION = ''' |
| 12 |
--- |
| 13 |
module: azure_rm_iotdevicemodule |
| 14 |
version_added: "0.1.2" |
| 15 |
short_description: Manage Azure IoT hub device module |
| 16 |
description: |
| 17 |
- Create, delete an Azure IoT hub device module. |
| 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 |
required: true |
| 40 |
device: |
| 41 |
description: |
| 42 |
- Device name the module associate with. |
| 43 |
required: true |
| 44 |
type: str |
| 45 |
state: |
| 46 |
description: |
| 47 |
- 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. |
| 48 |
type: str |
| 49 |
default: present |
| 50 |
choices: |
| 51 |
- absent |
| 52 |
- present |
| 53 |
auth_method: |
| 54 |
description: |
| 55 |
- The authorization type an entity is to be created with. |
| 56 |
type: str |
| 57 |
choices: |
| 58 |
- sas |
| 59 |
- certificate_authority |
| 60 |
- self_signed |
| 61 |
default: sas |
| 62 |
primary_key: |
| 63 |
description: |
| 64 |
- Explicit self-signed certificate thumbprint to use for primary key. |
| 65 |
- Explicit Shared Private Key to use for primary key. |
| 66 |
type: str |
| 67 |
aliases: |
| 68 |
- primary_thumbprint |
| 69 |
secondary_key: |
| 70 |
description: |
| 71 |
- Explicit self-signed certificate thumbprint to use for secondary key. |
| 72 |
- Explicit Shared Private Key to use for secondary key. |
| 73 |
type: str |
| 74 |
aliases: |
| 75 |
- secondary_thumbprint |
| 76 |
twin_tags: |
| 77 |
description: |
| 78 |
- A section that the solution back end can read from and write to. |
| 79 |
- Tags are not visible to device apps. |
| 80 |
- "The tag can be nested dictionary, '.', '$', '#', ' ' is not allowed in the key." |
| 81 |
- List is not supported. |
| 82 |
type: dict |
| 83 |
desired: |
| 84 |
description: |
| 85 |
- Used along with reported properties to synchronize device configuration or conditions. |
| 86 |
- "The tag can be nested dictionary, '.', '$', '#', ' ' is not allowed in the key." |
| 87 |
- List is not supported. |
| 88 |
type: dict |
| 89 |
extends_documentation_fragment: |
| 90 |
- azure.azcollection.azure |
| 91 |
- azure.azcollection.azure_tags |
| 92 |
|
| 93 |
author: |
| 94 |
- Yuwei Zhou (@yuwzho) |
| 95 |
|
| 96 |
''' |
| 97 |
|
| 98 |
EXAMPLES = ''' |
| 99 |
- name: Create simplest Azure IoT Hub device module |
| 100 |
azure_rm_iotdevicemodule: |
| 101 |
hub: myHub |
| 102 |
name: Testing |
| 103 |
device: mydevice |
| 104 |
hub_policy_name: iothubowner |
| 105 |
hub_policy_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" |
| 106 |
primary_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" |
| 107 |
secondary_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" |
| 108 |
|
| 109 |
- name: Create Azure IoT Edge device module |
| 110 |
azure_rm_iotdevice: |
| 111 |
hub: myHub |
| 112 |
device: mydevice |
| 113 |
name: Testing |
| 114 |
hub_policy_name: iothubowner |
| 115 |
hub_policy_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" |
| 116 |
primary_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" |
| 117 |
secondary_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" |
| 118 |
edge_enabled: true |
| 119 |
|
| 120 |
- name: Create Azure IoT Hub device module with module twin properties and tag |
| 121 |
azure_rm_iotdevice: |
| 122 |
hub: myHub |
| 123 |
name: Testing |
| 124 |
device: mydevice |
| 125 |
hub_policy_name: iothubowner |
| 126 |
hub_policy_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" |
| 127 |
primary_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" |
| 128 |
secondary_key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" |
| 129 |
twin_tags: |
| 130 |
location: |
| 131 |
country: US |
| 132 |
city: Redmond |
| 133 |
sensor: humidity |
| 134 |
desired: |
| 135 |
period: 100 |
| 136 |
''' |
| 137 |
|
| 138 |
RETURN = ''' |
| 139 |
module: |
| 140 |
description: |
| 141 |
- IoT Hub device. |
| 142 |
returned: always |
| 143 |
type: dict |
| 144 |
sample: { |
| 145 |
"authentication": { |
| 146 |
"symmetricKey": { |
| 147 |
"primaryKey": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", |
| 148 |
"secondaryKey": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" |
| 149 |
}, |
| 150 |
"type": "sas", |
| 151 |
"x509Thumbprint": { |
| 152 |
"primaryThumbprint": null, |
| 153 |
"secondaryThumbprint": null |
| 154 |
} |
| 155 |
}, |
| 156 |
"cloudToDeviceMessageCount": 0, |
| 157 |
"connectionState": "Disconnected", |
| 158 |
"connectionStateUpdatedTime": "0001-01-01T00:00:00", |
| 159 |
"deviceId": "mydevice", |
| 160 |
"etag": "ODM2NjI3ODg=", |
| 161 |
"generationId": "636904759703045768", |
| 162 |
"lastActivityTime": "0001-01-01T00:00:00", |
| 163 |
"managedBy": null, |
| 164 |
"moduleId": "Testing" |
| 165 |
} |
| 166 |
''' |
| 167 |
|
| 168 |
import re |
| 169 |
import traceback |
| 170 |
|
| 171 |
from ansible.module_utils.basic import missing_required_lib |
| 172 |
from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase |
| 173 |
|
| 174 |
try: |
| 175 |
from azure.iot.hub import IoTHubRegistryManager |
| 176 |
except ImportError: |
| 177 |
AZURE_IOT_HUB_IMPORT_ERROR = traceback.format_exc() |
| 178 |
else: |
| 179 |
AZURE_IOT_HUB_IMPORT_ERROR = None |
| 180 |
|
| 181 |
|
| 182 |
class AzureRMIoTDeviceModule(AzureRMModuleBase): |
| 183 |
|
| 184 |
def __init__(self): |
| 185 |
|
| 186 |
self.module_arg_spec = dict( |
| 187 |
name=dict(type='str', required=True), |
| 188 |
hub_policy_name=dict(type='str', required=True), |
| 189 |
hub_policy_key=dict(type='str', no_log=True, required=True), |
| 190 |
hub=dict(type='str', required=True), |
| 191 |
device=dict(type='str', required=True), |
| 192 |
state=dict(type='str', default='present', choices=['present', 'absent']), |
| 193 |
twin_tags=dict(type='dict'), |
| 194 |
desired=dict(type='dict'), |
| 195 |
auth_method=dict(type='str', choices=['self_signed', 'sas', 'certificate_authority'], default='sas'), |
| 196 |
primary_key=dict(type='str', no_log=True, aliases=['primary_thumbprint']), |
| 197 |
secondary_key=dict(type='str', no_log=True, aliases=['secondary_thumbprint']) |
| 198 |
) |
| 199 |
|
| 200 |
self.results = dict( |
| 201 |
changed=False, |
| 202 |
id=None |
| 203 |
) |
| 204 |
|
| 205 |
self.name = None |
| 206 |
self.hub = None |
| 207 |
self.device = None |
| 208 |
self.hub_policy_key = None |
| 209 |
self.hub_policy_name = None |
| 210 |
self.state = None |
| 211 |
self.twin_tags = None |
| 212 |
self.desired = None |
| 213 |
self.auth_method = None |
| 214 |
self.primary_key = None |
| 215 |
self.secondary_key = None |
| 216 |
self.managed_by = None |
| 217 |
self.etag = None |
| 218 |
|
| 219 |
self._base_url = None |
| 220 |
self.mgmt_client = None |
| 221 |
super(AzureRMIoTDeviceModule, self).__init__(self.module_arg_spec, supports_check_mode=True) |
| 222 |
|
| 223 |
if AZURE_IOT_HUB_IMPORT_ERROR: |
| 224 |
self.fail(msg=missing_required_lib('azure-iot-hub', reason=("This module requires the Azure IoT Hub data-plane SDK (azure-iot-hub). " |
| 225 |
"Installation may fail on some platforms due to uamqp wheel build issues.")), |
| 226 |
exception=AZURE_IOT_HUB_IMPORT_ERROR) |
| 227 |
|
| 228 |
def exec_module(self, **kwargs): |
| 229 |
|
| 230 |
for key in self.module_arg_spec.keys(): |
| 231 |
setattr(self, key, kwargs[key]) |
| 232 |
|
| 233 |
self._base_url = '{0}.azure-devices.net'.format(self.hub) |
| 234 |
connect_str = "HostName={0};SharedAccessKeyName={1};SharedAccessKey={2}".format(self._base_url, self.hub_policy_name, self.hub_policy_key) |
| 235 |
|
| 236 |
self.mgmt_client = IoTHubRegistryManager.from_connection_string(connect_str) |
| 237 |
|
| 238 |
changed = False |
| 239 |
|
| 240 |
module = self.get_module() |
| 241 |
if self.state == 'present': |
| 242 |
if not module: |
| 243 |
changed = True |
| 244 |
if not self.check_mode: |
| 245 |
module = self.create_module() |
| 246 |
else: |
| 247 |
self.etag = module.get('etag') |
| 248 |
|
| 249 |
twin = self.get_twin() |
| 250 |
if not twin.get('tags'): |
| 251 |
twin['tags'] = dict() |
| 252 |
twin_change = False |
| 253 |
if self.twin_tags and not self.is_equal(self.twin_tags, twin['tags']): |
| 254 |
twin_change = True |
| 255 |
if self.desired and not self.is_equal(self.desired, twin['properties']['desired']): |
| 256 |
self.module.warn('desired') |
| 257 |
twin_change = True |
| 258 |
if twin_change and not self.check_mode: |
| 259 |
twin_dict = dict() |
| 260 |
twin_dict['tags'] = self.twin_tags |
| 261 |
twin_dict['properties'] = dict() |
| 262 |
twin_dict['properties']['desired'] = self.desired |
| 263 |
twin = self.update_twin(twin_dict) |
| 264 |
|
| 265 |
changed = changed or twin_change |
| 266 |
module['tags'] = twin.get('tags') or dict() |
| 267 |
module['properties'] = twin.get('properties') or dict() |
| 268 |
else: |
| 269 |
if module and not self.check_mode: |
| 270 |
self.delete_module() |
| 271 |
changed = True |
| 272 |
|
| 273 |
self.results = module or dict() |
| 274 |
self.results['changed'] = changed |
| 275 |
return self.results |
| 276 |
|
| 277 |
def is_equal(self, updated, original): |
| 278 |
changed = False |
| 279 |
if not isinstance(updated, dict): |
| 280 |
self.fail('The Property or Tag should be a dict') |
| 281 |
for key in updated.keys(): |
| 282 |
if re.search(r'[.|$|#|\s]', key): |
| 283 |
self.fail("Property or Tag name has invalid characters: '.', '$', '#' or ' '. Got '{0}'".format(key)) |
| 284 |
original_value = original.get(key) |
| 285 |
updated_value = updated[key] |
| 286 |
if isinstance(updated_value, dict): |
| 287 |
if not isinstance(original_value, dict): |
| 288 |
changed = True |
| 289 |
original[key] = updated_value |
| 290 |
elif not self.is_equal(updated_value, original_value): |
| 291 |
changed = True |
| 292 |
elif original_value != updated_value: |
| 293 |
changed = True |
| 294 |
original[key] = updated_value |
| 295 |
return not changed |
| 296 |
|
| 297 |
def update_module(self): |
| 298 |
response = None |
| 299 |
try: |
| 300 |
if self.auth_method == 'sas': |
| 301 |
response = self.mgmt_client.update_module_with_sas(self.device, self.name, self.managed_by, self.etag, self.primary_key, self.secondary_key) |
| 302 |
elif self.auth_method == 'certificate_authority': |
| 303 |
response = self.mgmt_client.update_module_with_certificate_authority(self.device, self.name, self.managed_by, self.etag) |
| 304 |
elif self.auth_method == 'self_signed': |
| 305 |
response = self.mgmt_client.update_module_with_x509(self.device, |
| 306 |
self.name, self.managed_by, self.etag, self.primary_key, self.secondary_key) |
| 307 |
|
| 308 |
return self.format_module(response) |
| 309 |
except Exception as exc: |
| 310 |
if exc.status_code in [403] and self.edge_enabled: |
| 311 |
self.fail('Edge device is not supported in IoT Hub with Basic tier.') |
| 312 |
else: |
| 313 |
self.fail('Error when creating or updating IoT Hub device {0}: {1}'.format(self.name, exc.message or str(exc))) |
| 314 |
|
| 315 |
def create_module(self): |
| 316 |
response = None |
| 317 |
try: |
| 318 |
if self.auth_method == 'sas': |
| 319 |
response = self.mgmt_client.create_module_with_sas(self.device, self.name, self.managed_by, self.primary_key, self.secondary_key) |
| 320 |
elif self.auth_method == 'certificate_authority': |
| 321 |
response = self.mgmt_client.create_module_with_certificate_authority(self.device, self.name, self.managed_by) |
| 322 |
elif self.auth_method == 'self_signed': |
| 323 |
response = self.mgmt_client.create_module_with_x509(self.device_id, |
| 324 |
self.name, self.managed_by, self.primary_key, self.secondary_key) |
| 325 |
|
| 326 |
return self.format_module(response) |
| 327 |
except Exception as exc: |
| 328 |
self.fail('Error when creating or updating IoT Hub device {0}: {1}'.format(self.name, exc.message or str(exc))) |
| 329 |
|
| 330 |
def delete_module(self, etag): |
| 331 |
try: |
| 332 |
response = self.mgmt_client.delete_module(self.device, self.name) |
| 333 |
return response |
| 334 |
except Exception as exc: |
| 335 |
self.fail('Error when deleting IoT Hub device {0}: {1}'.format(self.name, exc.message or str(exc))) |
| 336 |
|
| 337 |
def get_module(self): |
| 338 |
try: |
| 339 |
response = self.mgmt_client.get_module(self.device, self.name) |
| 340 |
return self.format_module(response) |
| 341 |
except Exception: |
| 342 |
return None |
| 343 |
|
| 344 |
def get_twin(self): |
| 345 |
try: |
| 346 |
response = self.mgmt_client.get_twin(self.device) |
| 347 |
return self.format_twin(response) |
| 348 |
except Exception as exc: |
| 349 |
self.fail('Error when getting IoT Hub device {0} module twin {1}: {2}'.format(self.device, self.name, exc.message or str(exc))) |
| 350 |
|
| 351 |
def update_twin(self, twin): |
| 352 |
try: |
| 353 |
response = self.mgmt_client.update_twin(self.device, twin) |
| 354 |
return self.format_twin(response) |
| 355 |
except Exception as exc: |
| 356 |
self.fail('Error when creating or updating IoT Hub device {0} module twin {1}: {2}'.format(self.device, self.name, exc.message or str(exc))) |
| 357 |
|
| 358 |
def format_module(self, item): |
| 359 |
if not item: |
| 360 |
return None |
| 361 |
format_item = dict( |
| 362 |
authentication=dict(), |
| 363 |
cloudToDeviceMessageCount=item.cloud_to_device_message_count, |
| 364 |
connectionState=item.connection_state, |
| 365 |
connectionStateUpdatedTime=item.connection_state_updated_time, |
| 366 |
deviceId=item.device_id, |
| 367 |
etag=item.etag, |
| 368 |
generationId=item.generation_id, |
| 369 |
lastActivityTime=item.last_activity_time, |
| 370 |
managedBy=item.managed_by, |
| 371 |
moduleId=item.module_id |
| 372 |
) |
| 373 |
if item.authentication: |
| 374 |
format_item['authentication']['symmetricKey'] = dict() |
| 375 |
format_item['authentication']['symmetricKey']['primaryKey'] = item.authentication.symmetric_key.primary_key |
| 376 |
format_item['authentication']['symmetricKey']['secondaryKey'] = item.authentication.symmetric_key.secondary_key |
| 377 |
|
| 378 |
format_item['authentication']['type'] = item.authentication.type |
| 379 |
format_item['authentication']["x509Thumbprint"] = dict() |
| 380 |
format_item['authentication']["x509Thumbprint"]["primaryThumbprint"] = item.authentication.x509_thumbprint.primary_thumbprint |
| 381 |
format_item['authentication']["x509Thumbprint"]['secondaryThumbprint'] = item.authentication.x509_thumbprint.secondary_thumbprint |
| 382 |
|
| 383 |
return format_item |
| 384 |
|
| 385 |
def format_twin(self, item): |
| 386 |
if not item: |
| 387 |
return None |
| 388 |
format_twin = dict( |
| 389 |
device_id=item.device_id, |
| 390 |
module_id=item.module_id, |
| 391 |
tags=item.tags, |
| 392 |
properties=dict(), |
| 393 |
etag=item.etag, |
| 394 |
version=item.version, |
| 395 |
device_etag=item.device_etag, |
| 396 |
status=item.status, |
| 397 |
cloud_to_device_message_count=item.cloud_to_device_message_count, |
| 398 |
authentication_type=item.authentication_type, |
| 399 |
) |
| 400 |
if item.properties is not None: |
| 401 |
format_twin['properties']['desired'] = item.properties.desired |
| 402 |
format_twin['properties']['reported'] = item.properties.reported |
| 403 |
|
| 404 |
return format_twin |
| 405 |
|
| 406 |
|
| 407 |
def main(): |
| 408 |
AzureRMIoTDeviceModule() |
| 409 |
|
| 410 |
|
| 411 |
if __name__ == '__main__': |
| 412 |
main() |