使用 API 实现 IoT Edge 流分析的 CI/CDImplement CI/CD for Stream Analytics on IoT Edge using APIs

可使用 REST API 启用 Azure 流分析作业的持续集成和部署管道。You can enable continuous integration and deployment for Azure Stream Analytics jobs using REST APIs. 本文举例说明该使用哪些 API 及其具体用法。This article provides examples on which APIs to use and how to use them.

从不同环境调用 APICall APIs from different environments

可从 Linux 和 Windows 调用 REST API。REST APIs can be called from both Linux and Windows. 以下命令演示了调用 API 的正确语法。The following commands demonstrate proper syntax for the API call. 本文稍后会介绍特定 API 的用法。Specific API usage will be outlined in later sections of this article.

LinuxLinux

对于 Linux,可使用 CurlWget 命令:For Linux, you can use Curl or Wget commands:

curl -u { <username:password> }  -H "Content-Type: application/json" -X { <method> } -d "{ <request body> }" { <url> }   
wget -q -O- --{ <method> } -data="<request body>" --header=Content-Type:application/json --auth-no-challenge --http-user="<Admin>" --http-password="<password>" <url>

WindowsWindows

对于 Windows,请使用 PowerShell:For Windows, use Powershell:

$user = "<username>" 
$pass = "<password>" 
$encodedCreds = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$pass))) 
$basicAuthValue = "Basic $encodedCreds" 
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" 
$headers.Add("Content-Type", 'application/json') 
$headers.Add("Authorization", $basicAuthValue) 
$content = "<request body>" 
$response = Invoke-RestMethod <url> -Method <method> -Body $content -Headers $Headers 
echo $response 

在 Edge 上创建 ASA 作业Create an ASA job on Edge

要创建流分析作业,请使用流分析 API 调用 PUT 方法。To create Stream Analytics job, call the PUT method using the Stream Analytics API.

方法Method 请求 URLRequest URL
PUTPUT https://management.chinacloudapi.cn/subscriptions/{\**subscription-id**}/resourcegroups/{**resource-group-name**}/providers/Microsoft.StreamAnalytics/streamingjobs/{**job-name**}?api-version=2017-04-01-preview

使用 curl 的命令示例****:Example of command using curl:

curl -u { <username:password> } -H "Content-Type: application/json" -X { <method> } -d "{ <request body> }" https://management.chinacloudapi.cn/subscriptions/{subscription-id}/resourcegroups/{resource-group-name}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobname}?api-version=2017-04-01-preview  

JSON 中的请求正文示例:Example of request body in JSON:

{ 
  "location": "China North", 
  "tags": { "key": "value", "ms-suppressjobstatusmetrics": "true" }, 
  "sku": {  
      "name": "Standard" 
    }, 
  "properties": { 
    "sku": {  
      "name": "standard" 
    }, 
       "eventsLateArrivalMaxDelayInSeconds": 1, 
       "jobType": "edge", 
    "inputs": [ 
      { 
        "name": "{inputname}", 
        "properties": { 
         "type": "stream", 
          "serialization": { 
            "type": "JSON", 
            "properties": { 
              "fieldDelimiter": ",", 
              "encoding": "UTF8" 
            } 
          }, 
          "datasource": { 
            "type": "GatewayMessageBus", 
            "properties": { 
            } 
          } 
        } 
      } 
    ], 
    "transformation": { 
      "name": "{queryName}", 
      "properties": { 
        "query": "{query}" 
      } 
    }, 
    "package": { 
      "storageAccount" : { 
        "accountName": "{blobstorageaccountname}", 
        "accountKey": "{blobstorageaccountkey}" 
      }, 
      "container": "{blobcontaine}]" 
    }, 
    "outputs": [ 
      { 
        "name": "{outputname}", 
        "properties": { 
          "serialization": { 
            "type": "JSON", 
            "properties": { 
              "fieldDelimiter": ",", 
              "encoding": "UTF8" 
            } 
          }, 
          "datasource": { 
            "type": "GatewayMessageBus", 
            "properties": { 
            } 
          } 
        } 
      } 
    ] 
  } 
} 

有关详细信息,请参阅 API 文档For more information, see the API documentation.

发布 Edge 程序包Publish Edge package

要在 IoT Edge 上发布流分析作业,请使用 Edge 程序包发布 API 调用 POST 方法。To publish a Stream Analytics job on IoT Edge, call the POST method using the Edge Package Publish API.

方法Method 请求 URLRequest URL
POSTPOST https://management.chinacloudapi.cn/subscriptions/{\**subscriptionid**}/resourceGroups/{**resourcegroupname**}/providers/Microsoft.StreamAnalytics/streamingjobs/{**jobname**}/publishedgepackage?api-version=2017-04-01-preview

在作业成功发布前,此异步操作会返回状态 202。This asynchronous operation returns a status of 202 until the job has been successfully published. 位置响应标头包含用于获取进程状态的 URI。The location response header contains the URI used to get the status of the process. 进程正在运行时,若调用位置标头中的 URI,则会返回状态 202。While the process is running, a call to the URI in the location header returns a status of 202. 进程结束时,位置标头中的 URI 会返回状态 200。When the process finishes, the URI in the location header returns a status of 200.

使用 curl 的 Edge 程序包发布调用示例****:Example of an Edge package publish call using curl:

curl -d -X POST https://management.chinacloudapi.cn/subscriptions/{subscriptionid}/resourceGroups/{resourcegroupname}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobname}/publishedgepackage?api-version=2017-04-01-preview

调用 POST 后,应得到一个正文为空的响应。After making the POST call, you should expect a response with an empty body. 查找位于响应的 HEAD 中的 URL,并予以记录供将来使用。Look for the URL located in the HEAD of the response and record it for further use.

响应中的 HEAD 的 URL 示例:Example of the URL from the HEAD of response:

https://management.chinacloudapi.cn/subscriptions/{**subscriptionid**}/resourcegroups/{**resourcegroupname**}/providers/Microsoft.StreamAnalytics/StreamingJobs/{**resourcename**}/OperationResults/023a4d68-ffaf-4e16-8414-cb6f2e14fe23?api-version=2017-04-01-preview 

在运行以下命令前等待一到两分钟,先通过在响应的 HEAD 中发现的 URL 调用 API。A Wait for one to two minutes before running the following command to make an API call with the URL you found in the HEAD of the response. 如果未获得 200 响应,请重新运行该命令。Retry the command if you do not get a 200 response.

使用 curl 通过返回的 URL 调用 API 的示例****:Example of making API call with returned URL with curl:

curl -d -X GET https://management.chinacloudapi.cn/subscriptions/{subscriptionid}/resourceGroups/{resourcegroupname}/providers/Microsoft.StreamAnalytics/streamingjobs/{resourcename}/publishedgepackage?api-version=2017-04-01-preview 

响应中包括需添加到 Edge 部署脚本的信息。The response includes the information you need to add to the Edge deployment script. 以下示例显示了需收集的信息,以及要在部署清单中添加信息的位置。The examples below show what information you need to collect and where to add it in the deployment manifest.

成功发布后的响应正文示例:Sample response body after publishing successfully:

{ 
  edgePackageUrl : null 
  error : null 
  manifest : "{"supportedPlatforms":[{"os":"linux","arch":"amd64","features":[]},{"os":"linux","arch":"arm","features":[]},{"os":"windows","arch":"amd64","features":[]}],"schemaVersion":"2","name":"{jobname}","version":"1.0.0.0","type":"docker","settings":{"image":"{imageurl}","createOptions":null},"endpoints":{"inputs":["\],"outputs":["{outputnames}"]},"twin":{"contentType":"assignments","content":{"properties.desired":{"ASAJobInfo":"{asajobsasurl}","ASAJobResourceId":"{asajobresourceid}","ASAJobEtag":"{etag}","PublishTimeStamp":"{publishtimestamp}"}}}}" 
  status : "Succeeded" 
} 

部署清单示例:Sample of Deployment Manifest:

{ 
  "modulesContent": { 
    "$edgeAgent": { 
      "properties.desired": { 
        "schemaVersion": "1.0", 
        "runtime": { 
          "type": "docker", 
          "settings": { 
            "minDockerVersion": "v1.25", 
            "loggingOptions": "", 
            "registryCredentials": {} 
          } 
        }, 
        "systemModules": { 
          "edgeAgent": { 
            "type": "docker", 
            "settings": { 
              "image": "mcr.microsoft.com/azureiotedge-agent:1.0", 
              "createOptions": "{}" 
            } 
          }, 
          "edgeHub": { 
            "type": "docker", 
            "status": "running", 
            "restartPolicy": "always", 
            "settings": { 
              "image": "mcr.microsoft.com/azureiotedge-hub:1.0", 
              "createOptions": "{}" 
            } 
          } 
        }, 
        "modules": { 
          "<asajobname>": { 
            "version": "1.0", 
            "type": "docker", 
            "status": "running", 
            "restartPolicy": "always", 
            "settings": { 
              "image": "<settings.image>", 
              "createOptions": "<settings.createOptions>" 
            } 
            "version": "<version>", 
             "env": { 
              "PlanId": { 
               "value": "stream-analytics-on-iot-edge" 
          } 
        } 
      } 
    }, 
    "$edgeHub": { 
      "properties.desired": { 
        "schemaVersion": "1.0", 
        "routes": { 
            "route": "FROM /* INTO $upstream" 
        }, 
        "storeAndForwardConfiguration": { 
          "timeToLiveSecs": 7200 
        } 
      } 
    }, 
    "<asajobname>": { 
      "properties.desired": {<twin.content.properties.desired>} 
    } 
  } 
} 

配置部署清单后,请参阅使用 Azure CLI 部署 Azure IoT Edge 模块了解有关部署的信息。After the configuration of the deployment manifest, refer to Deploy Azure IoT Edge modules with Azure CLI for deployment.

后续步骤Next steps