

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# チュートリアル: AWS IoT SiteWise Edge ゲートウェイのアセットモデルを一覧表示する
<a name="edge-apis-tutorial"></a>

利用可能な AWS IoT SiteWise APIs のサブセットとエッジ固有の APIs を使用して、エッジ上のアセットモデルとそのアセットを操作できます。このチュートリアルでは、 AWS IoT SiteWise Edge ゲートウェイへの一時的な認証情報を取得し、SiteWise Edge ゲートウェイでアセットモデルのリストを取得する方法について説明します。

## 前提条件
<a name="edge-apis-tutorial-prerequisites"></a>

このチュートリアルの手順では、さまざまなツールを利用できます。そうしたツールを使用するには、対応する前提条件がインストールされていることを確認してください。

このチュートリアルを完了するには、以下が必要です。
+ A がデプロイされて、[AWS IoT SiteWise Edge セルフホストゲートウェイの要件](configure-gateway-ggv2.md) が稼働中
+ ポート 443 経由で同じネットワーク内の SiteWise Edge ゲートウェイにアクセスします。
+ [OpenSSL](https://www.openssl.org/) のインストール
+ (AWS OpsHub for AWS IoT SiteWise) [AWS OpsHub for AWS IoT SiteWise アプリケーション](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/manage-gateways-ggv2.html#opshub-app)
+ (curl) [curl](https://ec.haxx.se/install/) のインストール
+ (Python) [urllib3](https://urllib3.readthedocs.io/en/stable/index.html) のインストール
+ (パイソン) [Python3](https://www.python.org/downloads/) のインストール
+ (Python) [Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) のインストール
+ (Python) [BotoCore](https://botocore.amazonaws.com/v1/documentation/api/latest/index.html) のインストール

## ステップ 1: SiteWise Edge ゲートウェイサービスの署名入り証明書を取得する
<a name="edge-apis-tutorial-gateway-cert"></a>

SiteWise Edge ゲートウェイで使用できる API への TLS 接続を確立するには、信頼済みの証明書が必要です。この証明書は、OpenSSL または AWS OpsHub for を使用して生成できます AWS IoT SiteWise。

------
#### [ OpenSSL ]

**注記**  
このコマンドを実行するには、[OpenSSL](https://www.openssl.org/) がインストールされている必要があります。

ターミナルを開き、次のコマンドを実行して、SiteWise Edge ゲートウェイから署名入り証明書を取得します。`<sitewise_gateway_ip>` を SiteWise Edge ゲートウェイの IP に置き換えます。

```
openssl s_client -connect {{<sitewise_gateway_ip>}}:443 </dev/null 2>/dev/null | openssl x509 -outform PEM > GatewayCert.pem
```

------
#### [ AWS OpsHub for AWS IoT SiteWise ]

は AWS OpsHub に使用できます AWS IoT SiteWise。詳細については、「[SiteWise Edge ゲートウェイを管理](manage-gateways-ggv2.md)」を参照してください。

------

このチュートリアルでは、ダウンロードした SiteWise Edge ゲートウェイ証明書への絶対パスが使用されています。次のコマンドを実行して、証明書の完全なパスをエクスポートします。`<absolute_path_to_certificate>` の部分はその証明書へのパスに置き換えます。

```
export PATH_TO_CERTIFICATE='{{<absolute_path_to_certificate>}}'
```

## ステップ 2: SiteWise Edge ゲートウェイのホスト名を取得する
<a name="edge-apis-tutorial-gateway-hostname"></a>

**注記**  
このコマンドを実行するには、[OpenSSL](https://www.openssl.org/) がインストールされている必要があります。

このチュートリアルを完了するには、SiteWise Edge ゲートウェイのホスト名が必要です。SiteWise Edge ゲートウェイのホスト名を取得するには、以下を実行します。`<sitewise_gateway_ip>` を SiteWise Edge ゲートウェイの IP に置き換えます。

```
openssl s_client -connect {{<sitewise_gateway_ip>}}:443 </dev/null 2>/dev/null | grep -Po 'CN = \K.*'| head -1
```

後で使用するため、次のコマンドを実行してホスト名をエクスポートします。`<your_edge_gateway_hostname>` を SiteWise Edge ゲートウェイのホスト名に置き換えます。

```
export GATEWAY_HOSTNAME='{{<your_edge_gateway_hostname>}}'
```

## ステップ 3: SiteWise Edge ゲートウェイの仮の認証情報を取得する
<a name="edge-apis-tutorial-temporary-credentials"></a>

署名付き証明書と SiteWise Edge ゲートウェイのホスト名がわかったので、ゲートウェイで API を実行できるように仮の認証情報を取得する必要があります。これらの認証情報は、 AWS OpsHub の を通じて取得 AWS IoT SiteWise することも、API を使用して SiteWise Edge ゲートウェイから直接取得することもできます。 APIs

**重要**  
認証情報は 4 時間ごとに有効期限が切れるため、SiteWise Edge ゲートウェイで API を使用する直前に認証情報を取得する必要があります。認証情報を 4 時間以上キャッシュしないでください。

### for を使用して一時的な認証情報 AWS OpsHub を取得する AWS IoT SiteWise
<a name="edge-apis-tutorial-temp-creds-opshub"></a>

**注記**  
[AWS OpsHubAWS IoT SiteWise アプリケーション用の](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/manage-gateways-ggv2.html#opshub-app) をインストールする必要があります。

for AWS OpsHub AWS IoT SiteWise Application を使用して一時的な認証情報を取得するには、次の手順を実行します。

1. アプリケーションにログインします。

1. **[設定]** を選択します。

1. [**認証**] で [**認証情報のコピー**] を選択します。

1. 環境に合ったオプションを展開し、[**コピー**] を選択します。

1. 後で使用するため認証情報を保存しておきます。

### SiteWise Edge ゲートウェイの API を使用して仮の認証情報を取得する
<a name="edge-apis-tutorial-temp-creds-api"></a>

SiteWise Edge ゲートウェイの API を使用して仮の認証情報を取得するには、Python スクリプトまたは curl を使用できます。まず、SiteWise Edge ゲートウェイのユーザー名とパスワードが必要です。SiteWise Edge ゲートウェイは SigV4 の認証と認可を使用します。ユーザーの追加の詳細については、「[LDAP](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/manage-gateways-ggv2.html#opshub-app)」または「[Linux ユーザープール](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/manage-gateways-ggv2.html#opshub-app)」を参照してください。これらの認証情報は、 AWS IoT SiteWise APIs を使用するために必要な SiteWise Edge ゲートウェイのローカル認証情報を取得するために、次のステップで使用されます。

------
#### [ Python ]

**注記**  
[urllib3](https://urllib3.readthedocs.io/en/stable/index.html) と [Python3](https://www.python.org/downloads/) がインストールされている必要があります。

**Python を使用して認証情報を取得する**

1. **get\_credentials.py** というファイルを作成し、そのファイルに次のコードをコピーします。

   ```
   '''
   The following demonstrates how to get the credentials from the SiteWise Edge gateway. You will need to add local users or connect your system to LDAP/AD
   https://docs.aws.amazon.com/iot-sitewise/latest/userguide/manage-gateways-ggv2.html#create-user-pool
   
   Example usage:
       python3 get_credentials.py -e https://<gateway_hostname> -c <path_to_certificate> -u '<gateway_username>' -p '<gateway_password>' -m '<method>'
   '''
   import urllib3
   import json
   import urllib.parse
   import sys
   import os
   import getopt
   
   """
   This function retrieves the AWS IoT SiteWise Edge gateway credentials.
   """
   def get_credentials(endpoint,certificatePath, user, password, method):
       http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs= certificatePath)
       encoded_body = json.dumps({
           "username": user,
           "password": password,
           "authMechanism": method,
       })
   
       url =  urllib.parse.urljoin(endpoint, "/authenticate")
   
       response = http.request('POST', url,
           headers={'Content-Type': 'application/json'}, 
           body=encoded_body)
       
       if response.status != 200:
           raise Exception(f'Failed to authenticate! Response status {response.status}')
   
       auth_data = json.loads(response.data.decode('utf-8'))
   
       accessKeyId = auth_data["accessKeyId"]
       secretAccessKey = auth_data["secretAccessKey"]
       sessionToken = auth_data["sessionToken"]
       region = "edge"
   
       return accessKeyId, secretAccessKey, sessionToken, region
   
   def print_help():
       print('Usage:')
       print(f'{os.path.basename(__file__)} -e <endpoint> -c <path/to/certificate> -u <user> -p <password> -m <method> -a <alias>')
       print('')
       print('-e, --endpoint   edge gateway endpoint. Usually the Edge gateway hostname.')
       print('-c, --cert_path path to downloaded gateway certificate')
       print('-u, --user       Edge user')
       print('-p, --password   Edge password')
       print('-m, --method     (Optional) Authentication method (linux, winnt, ldap), default is linux')
       sys.exit()
   
   
   def parse_args(argv):
       endpoint = ""
       certificatePath = None
       user = None
       password = None
       method = "linux"
       
       try:
           opts, args = getopt.getopt(argv, "he:c:u:p:m:", ["endpoint=","cert_path=", "user=", "password=", "method="])
       except getopt.GetoptError:
           print_help()
   
       for opt, arg in opts:
           if opt == '-h':
               print_help()
           elif opt in ("-e", "--endpoint"):
               endpoint = arg
           elif opt in ("-u", "--user"):
               user = arg
           elif opt in ("-p", "--password"):
               password = arg
           elif opt in ("-m", "--method"):
               method = arg.lower()
           elif opt in ("-c", "--cert_path"):
               certificatePath = arg
   
       if method not in ['ldap', 'linux', 'winnt']:
           print("not valid method parameter, required are ldap, linux, winnt")
           print_help()
   
       if (user == None or password == None):
           print("To authenticate against edge user, password have to be passed together, and the region has to be set to 'edge'")
           print_help()
       
       if(endpoint == ""):
           print("You must provide a valid and reachable gateway hostname")
           print_help()
   
       return endpoint,certificatePath, user, password, method
   
   
   def main(argv):
       # get the command line args
       endpoint, certificatePath, user, password, method = parse_args(argv)
       
       accessKeyId, secretAccessKey, sessionToken, region=get_credentials(endpoint, certificatePath, user, password, method)
   
       print("Copy and paste the following credentials into the shell, they are valid for 4 hours:")
       print(f"export AWS_ACCESS_KEY_ID={accessKeyId}")
       print(f"export AWS_SECRET_ACCESS_KEY={secretAccessKey}")
       print(f"export AWS_SESSION_TOKEN={sessionToken}")
       print(f"export AWS_REGION={region}")
       print()
       
       
       
   
   if __name__ == "__main__":
      main(sys.argv[1:])
   ```

1. ターミナルから **get\_credentials.py** を実行します。`<gateway_username>` および `<gateway_password>` の部分は作成した認証情報に置き換えます。

   ```
   python3 get_credentials.py -e https://$GATEWAY_HOSTNAME -c $PATH_TO_CERTIFICATE -u '{{<gateway_username>}}' -p '{{<gateway_password>}}' -m 'linux'
   ```

------
#### [ curl ]

**注記**  
[curl](https://ec.haxx.se/install/) がインストールされている必要があります。

**curl を使用して認証情報を取得する**

1. ターミナルから次のコマンドを実行します。<gateway\_username> および <gateway\_password> の部分は作成した認証情報に置き換えます。

   ```
   curl --cacert $PATH_TO_CERTIFICATE --location \
   -X POST https://$GATEWAY_HOSTNAME:443/authenticate \
   --header 'Content-Type: application/json' \
   --data-raw '{
       "username": "<gateway_username>",
       "password": "<gateway_password>",
       "authMechanism": "linux"
   }'
   ```

   レスポンスは次のようになります。

   ```
   {
       "username": "sweuser",
       "accessKeyId": "<accessKeyId>",
       "secretAccessKey": "<secretAccessKey>",
       "sessionToken": "<sessionToken>",
       "sessionExpiryTime": "2022-11-17T04:51:40.927095Z",
       "authMechanism": "linux",
       "role": "edge-user"
   }
   ```

1. ターミナルから次のコマンドを実行します。

   ```
   export AWS_ACCESS_KEY_ID=<accessKeyId>
   export AWS_SECRET_ACCESS_KEY=<secretAccessKey>
   export AWS_SESSION_TOKEN=<sessionToken>
   export AWS_REGION=edge
   ```

------

## ステップ 4: SiteWise Edge ゲートウェイ上のアセットモデルのリストを取得する
<a name="edge-apis-tutorial-get-asset-models"></a>

署名入り証明書、SiteWise Edge ゲートウェイのホスト名、および SiteWise Edge ゲートウェイの仮の認証情報が揃ったので、`ListAssetModels` API を使用して SiteWise Edge ゲートウェイ上のアセットモデルのリストを取得できます。

------
#### [ Python ]

**注記**  
[Python3](https://www.python.org/downloads/)、[Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)、および [BotoCore](https://botocore.amazonaws.com/v1/documentation/api/latest/index.html) がインストールされている必要があります。

**Python を使用してアセットモデルのリストを取得する**

1. **list\_asset\_model.py** というファイルを作成し、そのファイルに次のコードをコピーします。

   ```
   import json
   import boto3
   import botocore
   import os
   
   # create the client using the credentials
   client = boto3.client("iotsitewise", 
       endpoint_url= "https://"+ os.getenv("GATEWAY_HOSTNAME"),
       region_name=os.getenv("AWS_REGION"), 
       aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"), 
       aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"), 
       aws_session_token=os.getenv("AWS_SESSION_TOKEN"),
       verify=os.getenv("PATH_TO_CERTIFICATE"),
       config=botocore.config.Config(inject_host_prefix=False))
   
   # call the api using local credentials
   response = client.list_asset_models()
   print(response)
   ```

1. ターミナルから **list\_asset\_model.py** を実行します。

   ```
   python3 list_asset_model.py
   ```

------
#### [ curl ]

**注記**  
[curl](https://ec.haxx.se/install/) がインストールされている必要があります。

**curl を使用してアセットモデルのリストを取得する**

ターミナルから、次のコマンドを実行します。

```
curl \
  --request GET https://$GATEWAY_HOSTNAME:443/asset-models \
  --cacert $PATH_TO_CERTIFICATE \
  --aws-sigv4 "aws:amz:edge:iotsitewise" \
  --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \
  -H "x-amz-security-token:$AWS_SESSION_TOKEN"
```

レスポンスは次のようになります。

```
{
    "assetModelSummaries": [
        {
            "arn": "arn:aws:iotsitewise:{region}:{account-id}:asset-model/{asset-model-id}",
            "creationDate": 1.669245291E9,
            "description": "This is a small example asset model",
            "id": "{asset-model-id}",
            "lastUpdateDate": 1.669249038E9,
            "name": "Some Metrics Model",
            "status": {
                "error": null,
                "state": "ACTIVE"
            }
        },
        .
        .
        .
    ],
    "nextToken": null
}
```

------