

終止支援通知：在 2025 年 12 月 15 日， AWS 將終止對 的支援 AWS IoT Analytics。2025 年 12 月 15 日之後，您將無法再存取 AWS IoT Analytics 主控台或 AWS IoT Analytics 資源。如需詳細資訊，請參閱[AWS IoT Analytics 終止支援](https://docs.aws.amazon.com/iotanalytics/latest/userguide/iotanalytics-end-of-support.html)。

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用自訂容器進行分析
<a name="automate-custom-container"></a>

本節包含如何使用 Jupyter 筆記本建置 Docker 容器的相關資訊。如果您重複使用第三方建置的筆記本，有安全風險：包含的容器可以使用您的使用者許可來執行任意程式碼。此外，筆記本產生的 HTML 可以顯示在 AWS IoT Analytics 主控台中，在顯示 HTML 的電腦上提供潛在的攻擊向量。在使用任何第三方筆記本之前，請確定您信任其撰寫者。

您可以建立自己的自訂容器，並使用 AWS IoT Analytics 服務執行它。若要這樣做，您可以設定 Docker 映像並將其上傳至 Amazon ECR，然後設定資料集以執行容器動作。本章節提供使用 Octave 的程序範例。

此教學課程假設您擁有：
+ 安裝在本機電腦的 Octave
+ 在本機電腦上設定的 Docker 帳戶
+ 具有 Amazon ECR 或 AWS IoT Analytics 存取權 AWS 的帳戶

**步驟 1：設定 Docker 影像**

在此教學課程中您需要三個主要檔案。其名稱和內容在此：
+ `Dockerfile` – Docker 容器化程序的初始設定。

  ```
  FROM ubuntu:16.04
  
  # Get required set of software
  RUN apt-get update
  RUN apt-get install -y software-properties-common
  RUN apt-get install -y octave
  RUN apt-get install -y python3-pip
  
  # Get boto3 for S3 and other libraries
  RUN pip3 install --upgrade pip
  RUN pip3 install boto3
  RUN pip3 install urllib3
  
  # Move scripts over
  ADD moment moment
  ADD run-octave.py run-octave.py
  
  # Start python script
  ENTRYPOINT ["python3", "run-octave.py"]
  ```
+ `run-octave.py` – 從 剖析 JSON AWS IoT Analytics、執行 Octave 指令碼，並將成品上傳至 Amazon S3。

  ```
  import boto3
  import json
  import os
  import sys
  from urllib.parse import urlparse
  
  # Parse the JSON from IoT Analytics
  with open('/opt/ml/input/data/iotanalytics/params') as params_file:
      params = json.load(params_file)
  
  variables = params['Variables']
  
  order = variables['order']
  input_s3_bucket = variables['inputDataS3BucketName']
  input_s3_key = variables['inputDataS3Key']
  output_s3_uri = variables['octaveResultS3URI']
  
  local_input_filename = "input.txt"
  local_output_filename = "output.mat"
  
  # Pull input data from S3...
  s3 = boto3.resource('s3')
  s3.Bucket(input_s3_bucket).download_file(input_s3_key, local_input_filename)
  
  # Run Octave Script
  os.system("octave moment {} {} {}".format(local_input_filename, local_output_filename, order))
  
  # # Upload the artifacts to S3
  output_s3_url = urlparse(output_s3_uri)
  output_s3_bucket = output_s3_url.netloc
  output_s3_key = output_s3_url.path[1:]
  
  s3.Object(output_s3_bucket, output_s3_key).put(Body=open(local_output_filename, 'rb'), ACL='bucket-owner-full-control')
  ```
+ `moment` – 簡單的 Octave 指令碼，可根據輸入或輸出檔案和指定的順序來計算時刻。

  ```
  #!/usr/bin/octave -qf
  
  arg_list = argv ();
  input_filename = arg_list{1};
  output_filename = arg_list{2};
  order = str2num(arg_list{3});
  
  [D,delimiterOut]=importdata(input_filename)
  M = moment(D, order)
  
  save(output_filename,'M')
  ```

1. 下載每個檔案的內容。建立新的目錄，並將所有檔案放入其中，然後`cd`放入該目錄。

1. 執行下列命令。

   ```
   docker build -t octave-moment .
   ```

1. 您應該會在 Docker 儲存庫中看到新的映像。執行下列命令來驗證它。

   ```
   docker image ls | grep octave-moment
   ```

**步驟 2：將 Docker 映像上傳至 Amazon ECR 儲存庫**

1. 在 Amazon ECR 中建立儲存庫。

   ```
   aws ecr create-repository --repository-name octave-moment
   ```

1. 取得 Docker 環境的登入。

   ```
   aws ecr get-login
   ```

1. 複製輸出並執行它。輸出看起來應該如下。

   ```
   docker login -u AWS -p {{password}} -e none https://{{your-aws-account-id}}.dkr.ecr..amazonaws.com
   ```

1. 標記您使用 Amazon ECR 儲存庫標籤建立的映像。

   ```
   docker tag {{your-image-id}}  {{your-aws-account-id}}.dkr.ecr.{{region}}.amazonaws.com/octave-moment
   ```

1. 將映像推送至 Amazon ECR。

   ```
   docker push {{your-aws-account-id}}.dkr.ecr.{{region}}.amazonaws.com/octave-moment
   ```

**步驟 3：將範例資料上傳至 Amazon S3 儲存貯體**

1. 下載以下內容以存檔 `input.txt`。

   ```
   0.857549  -0.987565  -0.467288  -0.252233  -2.298007
    0.030077  -1.243324  -0.692745   0.563276   0.772901
   -0.508862  -0.404303  -1.363477  -1.812281  -0.296744
   -0.203897   0.746533   0.048276   0.075284   0.125395
    0.829358   1.246402  -1.310275  -2.737117   0.024629
    1.206120   0.895101   1.075549   1.897416   1.383577
   ```

1. 建立名為 的 Amazon S3 儲存貯體`octave-sample-data-{{your-aws-account-id}}`。

1. 將檔案上傳至您剛建立的 Amazon S3 `input.txt`儲存貯體。您現在應該有一個名為 的儲存貯`octave-sample-data-{{your-aws-account-id}}`體，其中包含 `input.txt` 檔案。

**步驟 4：建立容器執行角色**

1. 將以下內容複製到名為 的檔案`role1.json`。將 {{your-aws-account-id}} 取代為 AWS 您的帳戶 ID，並將 {{aws-region}} 取代為您 AWS 資源 AWS 的區域。
**注意**  
此範例包含全域條件內容金鑰，以防止混淆代理人安全問題。如需詳細資訊，請參閱[預防跨服務混淆代理人](cross-service-confused-deputy-prevention.md)。

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Principal": {
                   "Service": [
                       "sagemaker.amazonaws.com",
                       "iotanalytics.amazonaws.com"
                   ]
               },
               "Action": "sts:AssumeRole",
               "Condition": {
                   "StringEquals": {
                       "aws:SourceAccount": "{{123456789012}}"
                   },
                   "ArnLike": {
                       "aws:SourceArn": "arn:aws:iotanalytics:{{us-east-1}}:{{123456789012}}:dataset/{{your-dataset}}"
                   }
               }
           }
       ]
   }
   ```

------

1. 使用您下載的檔案建立角色 AWS IoT Analytics，以授予對 SageMaker AI 和 `role1.json`的存取許可。

   ```
   aws iam create-role --role-name container-execution-role --assume-role-policy-document file://role1.json
   ```

1. 將以下內容下載至名為 的檔案，`policy1.json`並以{{`your-account-id`}}您的帳戶 ID 取代 （請參閱 下的第二個 ARN`Statement:Resource`)。

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "s3:GetBucketLocation",
                   "s3:PutObject",
                   "s3:GetObject",
                   "s3:PutObjectAcl"
               ],
               "Resource": [
                   "arn:aws:s3:*:*:dataset/*",
                   "arn:aws:s3:*:*:octave-sample-data-{{123456789012}}/*"
               ]
           },
           {
               "Effect": "Allow",
               "Action": [
                   "iotanalytics:*"
               ],
               "Resource": "*"
           },
           {
               "Effect": "Allow",
               "Action": [
                   "ecr:GetAuthorizationToken",
                   "ecr:GetDownloadUrlForLayer",
                   "ecr:BatchGetImage",
                   "ecr:BatchCheckLayerAvailability",
                   "logs:CreateLogGroup",
                   "logs:CreateLogStream",
                   "logs:DescribeLogStreams",
                   "logs:GetLogEvents",
                   "logs:PutLogEvents"
               ],
               "Resource": "*"
           },
           {
               "Effect": "Allow",
               "Action": [
                   "s3:GetBucketLocation",
                   "s3:ListBucket",
                   "s3:ListAllMyBuckets"
               ],
               "Resource": "*"
           }
       ]
   }
   ```

------

1. 使用您剛下載`policy.json`的檔案建立 IAM 政策。

   ```
   aws iam create-policy --policy-name ContainerExecutionPolicy --policy-document file://policy1.json
   ```

1. 將政策連接到角色。

   ```
   aws iam attach-role-policy --role-name container-execution-role --policy-arn arn:aws:iam::{{your-account-id}}:policy/ContainerExecutionPolicy
   ```

**步驟 5：使用容器動作建立資料集**

1. 將以下內容下載至名為 的 fie{{`region`}}，`cli-input.json`並以適當的值取代 {{`your-account-id`}}和 的所有執行個體。

   ```
   {
       "datasetName": "octave_dataset",
       "actions": [
           {
               "actionName": "octave",
               "containerAction": {
                   "image": "{{your-account-id}}.dkr.ecr.{{region}}.amazonaws.com/octave-moment",
                   "executionRoleArn": "arn:aws:iam::{{your-account-id}}:role/container-execution-role",
                   "resourceConfiguration": {
                       "computeType": "ACU_1",
                       "volumeSizeInGB": 1
                   },
                   "variables": [
                       {
                           "name": "octaveResultS3URI",
                           "outputFileUriValue": {
                               "fileName": "output.mat"
                           }
                       },
                       {
                           "name": "inputDataS3BucketName",
                           "stringValue": "octave-sample-data-{{your-account-id}}"
                       },
                       {
                           "name": "inputDataS3Key",
                           "stringValue": "input.txt"
                       },
                       {
                           "name": "order",
                           "stringValue": "3"
                       }
                   ]
               } 
           }
       ]
   }
   ```

1. 使用`cli-input.json`您剛下載和編輯的檔案建立資料集。

   ```
   aws iotanalytics create-dataset —cli-input-json file://cli-input.json
   ```

**步驟 6：叫用資料集內容產生**

1. 執行下列命令。

   ```
   aws iotanalytics create-dataset-content --dataset-name octave-dataset
   ```

**步驟 7：取得資料集內容**

1. 執行下列命令。

   ```
   aws iotanalytics get-dataset-content --dataset-name octave-dataset --version-id \$LATEST
   ```

1. 您可能需要等待幾分鐘，直到 `DatasetContentState`為 `SUCCEEDED`。

**步驟 8：在 Octave上列印輸出**

1. 執行下列命令，使用 Octave shell 從容器列印輸出。

   ```
   bash> octave
   octave> load output.mat
   octave> disp(M)
   -0.016393 -0.098061 0.380311 -0.564377 -1.318744
   ```