チュートリアル: SiteWise Edge ゲートウェイでのアセットモデルのリストの取得 - AWS IoT SiteWise

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

チュートリアル: SiteWise Edge ゲートウェイでのアセットモデルのリストの取得

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

前提条件

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

このチュートリアルを完了するには、以下が必要です。

ステップ 1: SiteWise Edge ゲートウェイサービスの署名付き証明書を取得する

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

OpenSSL
注記

このコマンドを実行するには、OpenSSL がインストールされている必要があります。

ターミナルを開き、次のコマンドを実行して、 SiteWise エッジゲートウェイから署名付き証明書を取得します。を SiteWise Edge ゲートウェイの IP <sitewise_gateway_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 IoT SiteWise には AWS OpsHub を使用できます。詳細については、「 SiteWise Edge ゲートウェイの管理」を参照してください。

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

export PATH_TO_CERTIFICATE='<absolute_path_to_certificate>'

ステップ 2: SiteWise Edge ゲートウェイのホスト名を取得する

注記

このコマンドを実行するには、OpenSSL がインストールされている必要があります。

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

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

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

export GATEWAY_HOSTNAME='<your_edge_gateway_hostname>'

ステップ 3: SiteWise Edge ゲートウェイの一時的な認証情報を取得する

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

重要

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

for を使用して一時的な認証情報AWS OpsHubを取得する AWS IoT SiteWise

注記

AWS OpsHub for AWS IoT SiteWise アプリケーションをインストールしておく必要があります。

AWS OpsHub for AWS IoT SiteWise アプリケーションを使用して仮の認証情報を取得するには、以下の操作を行います。

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

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

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

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

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

SiteWise Edge ゲートウェイ API を使用して一時的な認証情報を取得する

SiteWise Edge ゲートウェイ API を使用して Python スクリプトまたは curl を使用できる一時的な認証情報を取得するには、まず SiteWise Edge ゲートウェイのユーザー名とパスワードが必要です。 SiteWise Edge ゲートウェイは SigV4 認証と認可を使用します。ユーザーの追加の詳細については、「LDAP」または「Linux ユーザープール」を参照してください。これらの認証情報は、以下のステップで AWS IoT SiteWise APIsを使用するために必要な SiteWise Edge ゲートウェイのローカル認証情報を取得するために使用します。

Python
注記

urllib3Python3 がインストールされている必要があります。

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:])
  2. ターミナルから 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 がインストールされている必要があります。

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" }
  2. ターミナルから次のコマンドを実行します。

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

ステップ 4: SiteWise Edge ゲートウェイでアセットモデルのリストを取得する

Edge ゲートウェイの署名付き証明書、 SiteWise エッジ SiteWise ゲートウェイのホスト名、および一時的な認証情報を取得したら、 ListAssetModels API を使用して SiteWise 、エッジゲートウェイ上のアセットモデルのリストを取得できます。

Python
注記

Python3Boto3、および BotoCoreがインストールされている必要があります。

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)
  2. ターミナルから list_asset_model.py を実行します。

    python3 list_asset_model.py
curl
注記

curl がインストールされている必要があります。

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 }