デプロイ、監視、更新
タスク1: スタックを構成する
Section titled “タスク1: スタックを構成する”ジェネレーターはビルディングブロックを提供しましたが、デプロイメントではありません。スタックは、アーティファクトの保存場所、どのロールがそれらを読み取れるか、どのフリートがコンポーネントを受け取るかを決定します。packages/infra/src/stacks/application-stack.tsを置き換えます:
import { GreengrassArtifactBucket, GreengrassDeployment, Pulse,} from '@greengrass-tutorial/common-constructs';import { CfnParameter, Stack, type StackProps } from 'aws-cdk-lib';import { Role } from 'aws-cdk-lib/aws-iam';import type { Construct } from 'constructs';
export class ApplicationStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props);
// Both values are written to .greengrass-tutorial.env by the setup script // and passed with --parameters on every deploy. const tokenExchangeRoleArn = new CfnParameter( this, 'TokenExchangeRoleArn', { type: 'String', description: 'ARN of the core device token exchange role', }, ); const thingGroupArn = new CfnParameter(this, 'ThingGroupArn', { type: 'String', description: 'ARN of the thing group that holds the core device', });
// The retained artifact repository, and the read grant the core device // needs to fetch this component's artifacts from it. const artifacts = new GreengrassArtifactBucket(this, 'Artifacts'); const tokenExchangeRole = Role.fromRoleArn( this, 'TokenExchangeRole', tokenExchangeRoleArn.valueAsString, ); artifacts.grantReadTo(tokenExchangeRole, 'com.example.Pulse/*');
// Publishes the artifact built by pulse-artifact, then deploys it to the // existing thing group. addComponent carries the resolved NEXT_PATCH // version and orders the deployment after the component version. const pulse = new Pulse(this, 'Pulse', { bucket: artifacts }); const fleet = new GreengrassDeployment(this, 'Fleet', { targetArn: thingGroupArn.valueAsString, }); fleet.addComponent(pulse); }}import { Stack, StackProps } from 'aws-cdk-lib';import { Construct } from 'constructs';import { GreengrassArtifactBucket, GreengrassDeployment, Pulse,} from '@greengrass-tutorial/common-constructs';import { CfnParameter, Stack, type StackProps } from 'aws-cdk-lib';import { Role } from 'aws-cdk-lib/aws-iam';import type { Construct } from 'constructs';
export class ApplicationStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props);
// The code that defines your stack goes here // Both values are written to .greengrass-tutorial.env by the setup script // and passed with --parameters on every deploy. const tokenExchangeRoleArn = new CfnParameter( this, 'TokenExchangeRoleArn', { type: 'String', description: 'ARN of the core device token exchange role', }, ); const thingGroupArn = new CfnParameter(this, 'ThingGroupArn', { type: 'String', description: 'ARN of the thing group that holds the core device', });
// The retained artifact repository, and the read grant the core device // needs to fetch this component's artifacts from it. const artifacts = new GreengrassArtifactBucket(this, 'Artifacts'); const tokenExchangeRole = Role.fromRoleArn( this, 'TokenExchangeRole', tokenExchangeRoleArn.valueAsString, ); artifacts.grantReadTo(tokenExchangeRole, 'com.example.Pulse/*');
// Publishes the artifact built by pulse-artifact, then deploys it to the // existing thing group. addComponent carries the resolved NEXT_PATCH // version and orders the deployment after the component version. const pulse = new Pulse(this, 'Pulse', { bucket: artifacts }); const fleet = new GreengrassDeployment(this, 'Fleet', { targetArn: thingGroupArn.valueAsString, }); fleet.addComponent(pulse); }}各部分の役割:
GreengrassArtifactBucketは、保持され、バージョン管理され、TLSのみのアーティファクトリポジトリを作成します。grantReadToは、トークン交換ロールにcom.example.Pulse/*に対するs3:GetObjectを付与します。これは、リゾルバーがこのコンポーネントに対して書き込むすべてのアーティファクトキーをカバーします。PulseはGreengrassComponentVersionを拡張します。これは、pulse-artifactがビルドしたレシピとpulse.zipを読み取り、コンテンツハッシュ化されたキーの下にアーカイブをアップロードし、コンポーネントバージョンを公開します。そのbucketプロパティは、GreengrassArtifactBucketコンストラクト自体を受け取ります。targetArnを持つGreengrassDeploymentは、セットアップスクリプトが作成したモノのグループにデプロイします。addComponent(pulse)は、解決されたバージョンをデプロイメントのコンポーネントマップに配置し、コンポーネントバージョンリソースにCloudFormation依存関係を追加するため、バージョンが存在する前にIoTジョブがデバイスに到達することはありません。- 2つの
CfnParameter値は.greengrass-tutorial.envから取得されます。これらをパラメータとして渡すことで、スタックをアカウント固有のリテラルから解放し、e2eスイートが同じファイルを合成できるようにします。
タスク2: ブートストラップとデプロイ
Section titled “タスク2: ブートストラップとデプロイ”記録された値を読み込み、プロジェクト参照と依存関係マニフェストを同期し、更新されたワークスペース依存関係をインストールし、まだ行っていない場合はアカウントとリージョンでCDKをブートストラップします:
source .greengrass-tutorial.envpnpm nx syncyarn nx syncnpx nx syncbunx nx syncpnpm installyarnnpm installbun installAWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" pnpm nx run @greengrass-tutorial/infra:bootstrapAWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" yarn nx run @greengrass-tutorial/infra:bootstrapAWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" npx nx run @greengrass-tutorial/infra:bootstrapAWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" bunx nx run @greengrass-tutorial/infra:bootstrapスタックをデプロイします。packages/infra/src/main.tsは、スタックをステージgreengrass-tutorial-infra-sandboxに配置し、deployターゲットは独自のステージなしでcdk deployを実行するため、コマンドはそのステージに名前を付け、ロールとモノのグループARNをCloudFormationパラメータとして渡します:
AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" pnpm nx run @greengrass-tutorial/infra:deploy -- "greengrass-tutorial-infra-sandbox/**" --parameters TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" yarn nx run @greengrass-tutorial/infra:deploy -- "greengrass-tutorial-infra-sandbox/**" --parameters TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" npx nx run @greengrass-tutorial/infra:deploy -- "greengrass-tutorial-infra-sandbox/**" --parameters TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" bunx nx run @greengrass-tutorial/infra:deploy -- "greengrass-tutorial-infra-sandbox/**" --parameters TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"deployは^assembleに依存し、共有コンストラクトプロジェクトはテレメトリプロジェクトのassembleに依存し、これはpulse-artifactを実行します。したがって、すべてのデプロイは現在のソースに一致するアーティファクトを公開します。ターゲットはエクスプレスモードなしでcdk deployを実行するため、デプロイメントリソースを置き換える後のデプロイメントリビジョンを受け入れます。Greengrassでdeploy-sandboxを使用する前に、デプロイメントリビジョンを読んでください。
最初のデプロイでは、バージョンリゾルバーはcom.example.Pulseの公開されたバージョンを見つけられず、1.0.0を公開します。その後、デプロイメントがモノのグループに到達し、コアデバイスはトークン交換ロールでアーティファクトをダウンロードし、コンポーネントを起動します。スタックが完了してから1〜2分待ちます。
タスク3: ハートビートを監視する
Section titled “タスク3: ハートビートを監視する”$TUTORIAL_AWS_REGIONでAWS IoTコンソールを開き、MQTTテストクライアントを選択し、トピックをサブスクライブします:
tutorial/greengrass/heartbeat30秒ごとにメッセージが到着します:
{"sequence": 3, "greeting": "hello from pulse"}AWS CLIはMQTTトピックをサブスクライブできません。独自のMQTTクライアントを使用する場合は、独自の証明書とポリシーを使用してアカウントのデータエンドポイントに接続してください。このチュートリアルではこれらを作成しません:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" iot describe-endpoint \ --endpoint-type iot:Data-ATS --query endpointAddress --output textタスク4: デバイスを確認する
Section titled “タスク4: デバイスを確認する”デプロイメントが成功したことは、デバイスがデプロイメントドキュメントを適用したことを証明します。コンポーネントが実行されていることを証明するものではありません。インストールされたコンポーネントのライフサイクル状態を確認します:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" greengrassv2 list-installed-components \ --core-device-thing-name "$TUTORIAL_THING_NAME" \ --query 'installedComponents[?componentName==`com.example.Pulse`].[componentVersion,lifecycleState]' \ --output text1.0.0とRUNNINGが表示されるはずです。次に、モジュール2のSystems Managerパターンを使用して、インスタンス上のコンポーネント自身のログを読み取ります:
cat > /tmp/greengrass-tutorial-command.json <<'EOF'{ "commands": ["#!/bin/bash", "tail -n 20 /greengrass/v2/logs/com.example.Pulse.log"] }EOF
TUTORIAL_COMMAND_ID=$(aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" ssm send-command \ --instance-ids "$TUTORIAL_INSTANCE_ID" --document-name AWS-RunShellScript \ --parameters file:///tmp/greengrass-tutorial-command.json \ --query Command.CommandId --output text)sleep 5aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" ssm get-command-invocation \ --command-id "$TUTORIAL_COMMAND_ID" --instance-id "$TUTORIAL_INSTANCE_ID" \ --query StandardOutputContent --output textログには、IPC接続とハートビートごとに1行が表示されます:
INFO:awsiot.eventstreamrpc:<Connection ...> /greengrass/v2/ipc.socket:0> connectedINFO:com.example.Pulse:Published heartbeat 0 to tutorial/greengrass/heartbeatINFO:com.example.Pulse:Published heartbeat 1 to tutorial/greengrass/heartbeatデプロイメントがSUCCEEDEDを報告しているのにコンポーネントがBROKENである場合、またはget-core-deviceがUNHEALTHYを報告する場合は、コンポーネントのトラブルシューティング手順に従ってください。
タスク5: コンポーネントを更新する
Section titled “タスク5: コンポーネントを更新する”packages/telemetry/greengrass/pulse/main.pyの挨拶を変更します:
import jsonimport loggingimport time
from awsiot.greengrasscoreipc.clientv2 import GreengrassCoreIPCClientV2
logging.basicConfig(level=logging.INFO)logger = logging.getLogger("com.example.Pulse")
TOPIC = "tutorial/greengrass/heartbeat"PUBLISH_INTERVAL_SECONDS = 30GREETING = "hello from the updated pulse"
def publish_heartbeat(client: GreengrassCoreIPCClientV2, sequence: int) -> None: payload = json.dumps({"sequence": sequence, "greeting": GREETING}).encode("utf-8") client.publish_to_iot_core(topic_name=TOPIC, qos="1", payload=payload) logger.info("Published heartbeat %s to %s", sequence, TOPIC)
def main() -> None: client = GreengrassCoreIPCClientV2() sequence = 0 while True: publish_heartbeat(client, sequence) sequence += 1 time.sleep(PUBLISH_INTERVAL_SECONDS)
if __name__ == "__main__": main()import jsonimport loggingimport time
from awsiot.greengrasscoreipc.clientv2 import GreengrassCoreIPCClientV2
logging.basicConfig(level=logging.INFO)logger = logging.getLogger("com.example.Pulse")
TOPIC = "tutorial/greengrass/heartbeat"PUBLISH_INTERVAL_SECONDS = 30GREETING = "hello from pulse"GREETING = "hello from the updated pulse"
def publish_heartbeat(client: GreengrassCoreIPCClientV2, sequence: int) -> None: payload = json.dumps({"sequence": sequence, "greeting": GREETING}).encode("utf-8") client.publish_to_iot_core(topic_name=TOPIC, qos="1", payload=payload) logger.info("Published heartbeat %s to %s", sequence, TOPIC)
def main() -> None: client = GreengrassCoreIPCClientV2() sequence = 0 while True: publish_heartbeat(client, sequence) sequence += 1 time.sleep(PUBLISH_INTERVAL_SECONDS)
if __name__ == "__main__": main()同じコマンドで再度デプロイします:
AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" pnpm nx run @greengrass-tutorial/infra:deploy -- "greengrass-tutorial-infra-sandbox/**" --parameters TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" yarn nx run @greengrass-tutorial/infra:deploy -- "greengrass-tutorial-infra-sandbox/**" --parameters TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" npx nx run @greengrass-tutorial/infra:deploy -- "greengrass-tutorial-infra-sandbox/**" --parameters TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"AWS_PROFILE="$TUTORIAL_AWS_PROFILE" AWS_REGION="$TUTORIAL_AWS_REGION" bunx nx run @greengrass-tutorial/infra:deploy -- "greengrass-tutorial-infra-sandbox/**" --parameters TokenExchangeRoleArn="$TUTORIAL_TOKEN_EXCHANGE_ROLE_ARN" --parameters ThingGroupArn="$TUTORIAL_THING_GROUP_ARN"Nxは変更されたソースを検出し、pulse-artifactを再ビルドします。アーカイブのコンテンツハッシュが変更されるため、リゾルバーは1.0.1を割り当て、アーティファクトは新しいキーの下にアップロードされ、新しいコンポーネントバージョンが公開され、新しいデプロイメントリビジョンがモノのグループをそれに向けます。レシピはまだNEXT_PATCHと言っています。ワークスペースには番号は記録されません。
インストールされたバージョンとペイロードの両方を確認します:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" greengrassv2 list-installed-components \ --core-device-thing-name "$TUTORIAL_THING_NAME" \ --query 'installedComponents[?componentName==`com.example.Pulse`].[componentVersion,lifecycleState]' \ --output text1.0.1とRUNNINGが表示されるはずです。MQTTテストクライアントでは、挨拶がhello from the updated pulseに変更され、コンポーネントプロセスが再起動されたため、シーケンスが0から再開されます。
削除とクリーンアップに進みます。