Triển khai, quan sát và cập nhật
Nhiệm vụ 1: Soạn stack
Phần tiêu đề “Nhiệm vụ 1: Soạn stack”Generator cung cấp các khối xây dựng, không phải deployment. Stack của bạn quyết định nơi lưu trữ artifacts, role nào có thể đọc chúng, và fleet nào nhận component. Thay thế 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); }}Chức năng của từng phần:
GreengrassArtifactBuckettạo kho lưu trữ artifact được giữ lại, có phiên bản, chỉ dùng TLS.grantReadTocấp cho token exchange role quyềns3:GetObjecttrêncom.example.Pulse/*, bao gồm mọi artifact key mà resolver ghi cho component này.Pulsemở rộngGreengrassComponentVersion. Nó đọc recipe vàpulse.zipmàpulse-artifactđã build, tải lên archive dưới một key được hash nội dung, và xuất bản phiên bản component. Thuộc tínhbucketcủa nó nhận chính constructGreengrassArtifactBucket.GreengrassDeploymentvớitargetArntriển khai đến thing group mà script thiết lập đã tạo.addComponent(pulse)đặt phiên bản đã resolve vào component map của deployment và thêm dependency CloudFormation vào tài nguyên phiên bản component, do đó IoT job không thể đến thiết bị trước khi phiên bản tồn tại.- Hai giá trị
CfnParameterđến từ.greengrass-tutorial.env. Truyền chúng dưới dạng parameters giữ cho stack không có literals cụ thể theo tài khoản và cho phép bộ e2e suite tổng hợp cùng một file.
Nhiệm vụ 2: Bootstrap và triển khai
Phần tiêu đề “Nhiệm vụ 2: Bootstrap và triển khai”Tải các giá trị đã ghi lại, đồng bộ hóa các tham chiếu dự án và dependency manifests, cài đặt các dependencies workspace đã cập nhật, và bootstrap CDK trong tài khoản và Region nếu bạn chưa làm trước đó:
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:bootstrapTriển khai stack. packages/infra/src/main.ts đặt stack trong stage greengrass-tutorial-infra-sandbox, và target deploy chạy cdk deploy mà không có stage riêng, do đó lệnh đặt tên cho stage đó và truyền các ARN của role và thing group dưới dạng parameters 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 phụ thuộc vào ^assemble, và dự án shared constructs phụ thuộc vào assemble của dự án telemetry, chạy pulse-artifact. Do đó, mỗi lần deploy đều xuất bản artifact khớp với source hiện tại của bạn. Target chạy cdk deploy mà không có express mode, do đó nó chấp nhận revision deployment sau này thay thế tài nguyên deployment. Đọc deployment revisions trước khi sử dụng deploy-sandbox cho Greengrass.
Ở lần deploy đầu tiên, version resolver không tìm thấy phiên bản đã xuất bản nào của com.example.Pulse và xuất bản 1.0.0. Deployment sau đó đến thing group, và core device tải xuống artifact với token exchange role và khởi động component. Cho phép một đến hai phút sau khi stack hoàn thành.
Nhiệm vụ 3: Theo dõi heartbeat
Phần tiêu đề “Nhiệm vụ 3: Theo dõi heartbeat”Mở AWS IoT console trong $TUTORIAL_AWS_REGION, chọn MQTT test client, và đăng ký topic:
tutorial/greengrass/heartbeatCứ mỗi 30 giây một message đến:
{"sequence": 3, "greeting": "hello from pulse"}AWS CLI không thể đăng ký các MQTT topics. Nếu bạn thích MQTT client của riêng mình, kết nối nó với data endpoint của tài khoản với certificate và policy riêng của nó, mà tutorial này không tạo:
aws --profile "$TUTORIAL_AWS_PROFILE" --region "$TUTORIAL_AWS_REGION" iot describe-endpoint \ --endpoint-type iot:Data-ATS --query endpointAddress --output textNhiệm vụ 4: Kiểm tra thiết bị
Phần tiêu đề “Nhiệm vụ 4: Kiểm tra thiết bị”Một deployment thành công chứng minh thiết bị đã áp dụng deployment document. Nó không chứng minh component chạy. Kiểm tra lifecycle state của component đã cài đặt:
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 textMong đợi 1.0.0 và RUNNING. Sau đó đọc log riêng của component trên instance với mẫu Systems Manager từ module 2:
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 textLog hiển thị kết nối IPC và một dòng cho mỗi heartbeat:
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/heartbeatNếu deployment báo cáo SUCCEEDED nhưng component là BROKEN, hoặc get-core-device báo cáo UNHEALTHY, hãy làm theo các bước khắc phục sự cố component.
Nhiệm vụ 5: Cập nhật component
Phần tiêu đề “Nhiệm vụ 5: Cập nhật component”Thay đổi greeting trong 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()Triển khai lại với cùng lệnh:
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 thấy source đã thay đổi và rebuild pulse-artifact. Content hash của archive thay đổi, do đó resolver phân bổ 1.0.1, artifact được tải lên dưới một key mới, một phiên bản component mới được xuất bản, và một revision deployment mới hướng thing group đến nó. Recipe vẫn nói NEXT_PATCH; không có gì trong workspace ghi lại số.
Xác minh cả phiên bản đã cài đặt và payload:
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 textMong đợi 1.0.1 và RUNNING. Trong MQTT test client, greeting thay đổi thành hello from the updated pulse, và sequence khởi động lại từ 0 vì process component đã được khởi động lại.
Tiếp tục với Remove and clean up.