📜 ⬆️ ⬇️

Cross-platform IoT: Using the Azure CLI and Azure IoT Hub

We present the first article from the cycle “Cross-platform IoT”. When reading the title, you might have a question: what does the CLI have to do with the IoT Hub? Quite simply, the developers presented a module that allows you to manage IoT Hub operations from the command line. Under the cat, you will learn how to activate support for the Azure IoT Hub in the Azure CLI, create and manage it further.



Cycle of articles "Cross-platform IoT"


1. Cross-platform IoT: Using Azure CLI and Azure IoT Hub
2. Cross-platform IoT: Device Operations
3. Cross-platform IoT: Troubleshooting
3. Loading ...

Azure CLI is a useful addition to a set of cross-platform tools for managing cloud resources. The tool develops so fast that sometimes it seems to me that it is better than the CLI version of PowerShell :). To date, there are two versions of the Azure CLI:

The functionality of the two versions is approximately the same, both of them are suitable for running IoT modules. Here is a brief information about the tasks for which the Azure CLI 2.0 was created.

We’ll start by installing the IoT components for the Azure CLI, then we’ll see how to use the CLI to create and manage the IoT Hub.
')
If you have not installed Azure CLI 2.0 yet, you can do it from here . The link contains instructions for installing CLI on any OS; we will use macOS. Python scripts provide installation of dependencies, and also set the path for the command “az” from the terminal.
The script will complement ~/.bashrc , which, as I noticed, interacts poorly with the MacOS terminal. To use the “az” alias for all Azure CLI commands, you need to add the following environment variable to your ~/.bash_profile configuration. To change the configuration, enter in bash nano ~/.bash_profile , and then save the settings:
 export PATH=\~/bin:$PATH 

Not displaying .bash_profile?


If .bash_profile is not available (this is typical for MacOS), you can simply create it using:
 cd ~/ touch .bash_profile 

To verify that the Azure CLI is working, open a terminal and enter:
 az --version 

A list of all components installed as part of the CLI will open:
 acs (2.0.0) appservice (0.1.1b5) batch (0.1.1b4) cloud (2.0.0) component (2.0.0) configure (2.0.0) container (0.1.1b4) core (2.0.0) documentdb (0.1.1b2) feedback (2.0.0) keyvault (0.1.1b5) network (2.0.0) nspkg (2.0.0) profile (2.0.0) redis (0.1.1b3) resource (2.0.0) role (2.0.0) sql (0.1.1b5) storage (2.0.1) vm (2.0.0) Python (Darwin) 2.7.10 (default, Jul 30 2016, 19:40:32) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] 

Keep in mind that the IoT module is not installed by default. Install it:
 az login az account set --subscription az component update --add iot az provider register -namespace Microsoft.Devices 

These teams will authenticate you and associate your account with your Azure subscription, install and register the IoT module. az –version should give the result with the new module.
 acs (2.0.0) appservice (0.1.1b5) ...... iot (0.1.1b3) ...... 

Next, the IoT module is divided into two groups, device and hub :

Help to commands: az iot device -h or az iot hub -h .

Go ahead - create a resource group and a new IoT Hub.
 az group create --name yourresourcegroupname --location westus az iot hub create --name youriothubname --location yourlocation --sku S1 --unit 1 --resource-group yourresourcegroupname 

I have indicated SKU S1 , but IoT Hub can be used in the free mode - F1 (available values: {F1,S1,S2,S3} ). In addition, unit indicates the number of units you want to create using the IoT Hub. It also indicates the region in which the IoT Hub will be created. You can skip this item - IoT Hub will be placed in the region with a group of resources. List of available regions (at the time of this writing): {westus,northeurope,eastasia,eastus,westeurope,southeastasia,japaneast,japanwest,australiaeast,australiasoutheast,westus2,westcentralus} .
If everything went well, you should see this answer:
 { "etag": "AAAAAAC2NAc=", "id": "/subscriptions/yournamespace/providers/Microsoft.Devices/IotHubs/youriothubname", "location": "westus", "name": "youriothubname", "properties": { .... } }, ... '' "type": "Microsoft.Devices/IotHubs" } 

We just created IoT Hub from the command line on a Mac! In the next post I will explain how to use the IoT Hub to add devices and perform other operations.

And some more useful commands Azure IoT CLI


To view the IoT Hub configuration, just type az iot hub list -g yourresourcegroupname - a list of all IoT az iot hub list -g yourresourcegroupname created in your resource group should appear. If you omit the resource group, all IoT Hub instances will appear in the subscription. To view detailed information about a specific IoT Hub, specify: az iot hub show -g yourresourcegroupname --name yourhubname .

IoT Hub by default creates a set of policies that can be used for access. To view a list of policies, type az iot hub policy list --hub-name youriothubname . Policies are an important element of the work of IoT Hub. Always adhere to the principle of "least privilege" and choose a policy that corresponds to the current operation. For example, the iothubowner policy iothubowner IoT Hub administrator rights and should not be used, in particular, to connect a device.

To simply get the connection strings for the IoT az iot hub show-connection-string -g yourresourcegroupname created, type az iot hub show-connection-string -g yourresourcegroupname .

Note that by default, the above command uses the connection string for the iothubowner policy, which provides full control of your IoT Hub. It is recommended to set detailed policies. They guarantee the least access rights. To do this, use the option --policy-name and specify the name of the policy.

You can also use the az iot device to create a device; instead, we will use the IoT Hub Explorer to demonstrate these features. IoT Hub Explorer provides several additional commands. It seems to me that all the functionality of IoT Hub Explorer will be included in a future version of the IoT component for the Azure CLI.

What's inside the Azure CLI?


One of the advantages of the Azure CLI is that it uses the REST API to create resources and objects in Azure. If you want to understand what's going on inside and debug processes, you can use the -debug option, which provides a trace of all calls made and any accompanying exceptions that may have occurred during processing. For example, for a command of this type:
 az iot hub show-connection-string -g yourresourcegroupname --debug" 

should display something like the following:
 Command arguments ['iot', 'hub', 'show-connection-string', '-g', 'yourrgname'] Current active cloud 'AzureCloud' {'active_directory': 'https://login.microsoftonline.com', 'active_directory_graph_resource_id': 'https://graph.windows.net/', 'active_directory_resource_id': 'https://management.core.windows.net/', 'management': 'https://management.core.windows.net/', ....... 'storage_endpoint': 'core.windows.net'} Registered application event handler 'CommandTableParams.Loaded' at Registered application event handler 'CommandTable.Loaded' at Successfully loaded command table from module 'iot'. .......... g': 'gzip, deflate' msrest.http_logger : 'Accept': 'application/json' msrest.http_logger : 'User-Agent': 'python/2.7.10 (Darwin-16.4.0-x86_64-i386-64bit) requests/2.13.0 msrest/0.4.6 msrest_azure/0.4.7 iothubclient/0.2.1 Azure-SDK-For-Python AZURECLI/2.0.0' msrest.http_logger : 'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzUU4wQlpTN3M0bk4tQmRyamJGMFlfTGRNTSIsImtpZCI6ImEzUU4wQlpTN3M0bk4tQmRyamJGMFlfTGRNTSJ9..jEAMzSd4bV0x_hu8cNnQ7fActL6uIm97U7pkwCz79eaSfEnBdqF8hXEJlwQh9GYL0A3r8olNdjr1ugiVH6Y0RFutn7iD8E-etkVI9btE1aseZ3vvZqYeKPhA1VytBsTpb4XO2ZI094VynTeALoxe7bbuEzl5YaeqtbC5EM0PMhPB04o7K1ZF49nGKvA385MHJU3G-_JT3zV-wdQWDj5QKfkEJ0a9AsQ9fM7bxyTdm_m5tQ4a-kp61r92e1SzcpXgCD7TXRHxrZ2wa65rtD8tRmHt6LOi7a4Yx2wPFUpFoeQAcN7p7RKW6t_Cn8eyyvWrrUXximBcTB4rtQTgXCfVUw' 

As you can see, the Azure CLI makes REST calls on our behalf using current tokens and performs the necessary operations. Once answers are received, it translates the response into the desired format and displays it in the terminal.

The final value without using the - --debug option will be as follows:
 [ { "connectionString": "HostName=youriothub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=yourkey=, "name": "youriothub" } ] 

Another useful operation that is available in the Azure CLI is output . It allows you to format the final value using various parsing tools. For example, using the same command that was used above, we can change the format of the final value from JSON (by default) to a table.
 az iot hub show-connection-string -g yourresourcegroupname -o table" 

The final value should take the form of a table:
 ConnectionString -------------------------------------------------------------------------------------------------------------------------------------- -------------- HostName=youriothub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=yourkey= Name youriothub 

Finally, using Azure CLI queries in conjunction with Unix commands, you can create powerful scripts to transfer the final value from one command to another.

For example, the commands below use a query to retrieve data on all IoT Hubs created in the western region within a single subscription, and then reformat the result into tsv:
 az iot hub list --query "[?contains(location,'westus')].{Name:name}" -o tsv 

The query language (JMESPath) is effective in filtering queries, you can read more about it here .

That's all for now. The next post will be about using the IoT Azure Center browser to create devices and perform send and receive operations with it.

Ahriman and Schvepsss worked on the material .

Source: https://habr.com/ru/post/333530/


All Articles